Compare commits

...

36 Commits

Author SHA1 Message Date
Prominence 93b6b357c1 Switching to 17 version of java. 2022-04-17 01:13:11 +03:00
dependabot[bot] c0dd184965 Bump jacoco-maven-plugin from 0.8.7 to 0.8.8 (#32)
Bumps [jacoco-maven-plugin](https://github.com/jacoco/jacoco) from 0.8.7 to 0.8.8.
- [Release notes](https://github.com/jacoco/jacoco/releases)
- [Commits](https://github.com/jacoco/jacoco/compare/v0.8.7...v0.8.8)

---
updated-dependencies:
- dependency-name: org.jacoco:jacoco-maven-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-17 01:05:54 +03:00
dependabot[bot] 08d0aa091d Bump maven-jar-plugin from 3.2.0 to 3.2.2 (#33)
Bumps [maven-jar-plugin](https://github.com/apache/maven-jar-plugin) from 3.2.0 to 3.2.2.
- [Release notes](https://github.com/apache/maven-jar-plugin/releases)
- [Commits](https://github.com/apache/maven-jar-plugin/compare/maven-jar-plugin-3.2.0...maven-jar-plugin-3.2.2)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-jar-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-17 01:05:36 +03:00
dependabot[bot] 93ae514550 Bump maven-compiler-plugin from 3.8.1 to 3.10.1 (#35)
Bumps [maven-compiler-plugin](https://github.com/apache/maven-compiler-plugin) from 3.8.1 to 3.10.1.
- [Release notes](https://github.com/apache/maven-compiler-plugin/releases)
- [Commits](https://github.com/apache/maven-compiler-plugin/compare/maven-compiler-plugin-3.8.1...maven-compiler-plugin-3.10.1)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-compiler-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-17 01:05:17 +03:00
dependabot[bot] 2a15788569 Bump maven-javadoc-plugin from 3.3.0 to 3.3.2 (#36)
Bumps [maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 3.3.0 to 3.3.2.
- [Release notes](https://github.com/apache/maven-javadoc-plugin/releases)
- [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.3.0...maven-javadoc-plugin-3.3.2)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-javadoc-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-17 01:04:27 +03:00
Prominence 37d7a2b3f5 Merge remote-tracking branch 'origin/master' into dev 2022-04-17 00:59:49 +03:00
dependabot[bot] 6790848c32 Bump nexus-staging-maven-plugin from 1.6.8 to 1.6.12 (#34)
* Merged changes from dev branch.

* Updated README.md

* Releasing 2.3.0 version.

* Bump nexus-staging-maven-plugin from 1.6.8 to 1.6.12

Bumps nexus-staging-maven-plugin from 1.6.8 to 1.6.12.

---
updated-dependencies:
- dependency-name: org.sonatype.plugins:nexus-staging-maven-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: Alexey Zinchenko <Prominence@users.noreply.github.com>
Co-authored-by: Prominence <alexey.zinchenko@protonmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-04-17 00:49:21 +03:00
Prominence ec988c5f26 Releasing 2.3.0 version. 2022-04-17 00:41:54 +03:00
Prominence 7b8d46bb7a Updated README.md 2022-04-17 00:26:38 +03:00
Alexey Zinchenko 6ae281af0d Merged changes from dev branch. 2022-04-17 00:25:07 +03:00
Prominence 23a1fa5a7b Preparing for merge. 2022-04-17 00:23:16 +03:00
Prominence 1cac951aaa Preparing for merge. 2022-04-17 00:20:23 +03:00
Prominence 58e648be42 Updated SNAPSHOT version. 2022-04-16 22:32:10 +03:00
Prominence f30bcad5dc Updated SNAPSHOT version. 2022-04-16 22:26:32 +03:00
Prominence 5793722181 Updated docs about timeout settings. 2022-04-15 00:40:51 +03:00
Prominence 40462397c1 Added methods and fields to represent daily moonrise/moonset information. Added tests. Fixed UKRAINIAN language constant name. Updated docs. 2022-04-15 00:37:04 +03:00
Prominence 44b543e65c Another portion of refactoring. Updated dependencies. 2022-04-14 23:30:44 +03:00
Prominence 13b20fc7e9 Moved mappers into separate package. 2022-04-14 20:28:23 +03:00
Prominence 2a531dd683 Started global refactoring. Added timeout parameters for requests. 2022-04-13 00:13:27 +03:00
dependabot-preview[bot] 1e1054903e Bump slf4j-api from 1.7.31 to 1.7.32 (#30)
Bumps [slf4j-api](https://github.com/qos-ch/slf4j) from 1.7.31 to 1.7.32.
- [Release notes](https://github.com/qos-ch/slf4j/releases)
- [Commits](https://github.com/qos-ch/slf4j/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-07-21 11:00:43 +03:00
dependabot-preview[bot] ff5b6c7a33 Bump jackson-databind from 2.12.3 to 2.12.4 (#29)
Bumps [jackson-databind](https://github.com/FasterXML/jackson) from 2.12.3 to 2.12.4.
- [Release notes](https://github.com/FasterXML/jackson/releases)
- [Commits](https://github.com/FasterXML/jackson/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-07-07 10:55:04 +03:00
dependabot-preview[bot] db1cf858d8 Bump slf4j-api from 1.7.30 to 1.7.31 (#28)
Bumps [slf4j-api](https://github.com/qos-ch/slf4j) from 1.7.30 to 1.7.31.
- [Release notes](https://github.com/qos-ch/slf4j/releases)
- [Commits](https://github.com/qos-ch/slf4j/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-06-21 09:13:57 +03:00
dependabot-preview[bot] c2cc110dab Bump maven-javadoc-plugin from 3.2.0 to 3.3.0 (#27)
Bumps [maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 3.2.0 to 3.3.0.
- [Release notes](https://github.com/apache/maven-javadoc-plugin/releases)
- [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-3.2.0...maven-javadoc-plugin-3.3.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-05-24 10:58:02 +03:00
dependabot-preview[bot] d4c2472254 Bump junit-jupiter-engine from 5.7.1 to 5.7.2 (#26)
Bumps [junit-jupiter-engine](https://github.com/junit-team/junit5) from 5.7.1 to 5.7.2.
- [Release notes](https://github.com/junit-team/junit5/releases)
- [Commits](https://github.com/junit-team/junit5/compare/r5.7.1...r5.7.2)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-05-17 11:01:01 +03:00
dependabot-preview[bot] 380e3e458b Bump junit-platform-runner from 1.7.1 to 1.7.2 (#25)
Bumps [junit-platform-runner](https://github.com/junit-team/junit5) from 1.7.1 to 1.7.2.
- [Release notes](https://github.com/junit-team/junit5/releases)
- [Commits](https://github.com/junit-team/junit5/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-05-17 11:00:48 +03:00
dependabot-preview[bot] 246c07db97 Bump maven-gpg-plugin from 1.6 to 3.0.1 (#24)
Bumps [maven-gpg-plugin](https://github.com/apache/maven-gpg-plugin) from 1.6 to 3.0.1.
- [Release notes](https://github.com/apache/maven-gpg-plugin/releases)
- [Commits](https://github.com/apache/maven-gpg-plugin/compare/maven-gpg-plugin-1.6...maven-gpg-plugin-3.0.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-05-10 18:40:15 +03:00
dependabot-preview[bot] f19a627313 Bump jacoco-maven-plugin from 0.8.6 to 0.8.7 (#23)
Bumps [jacoco-maven-plugin](https://github.com/jacoco/jacoco) from 0.8.6 to 0.8.7.
- [Release notes](https://github.com/jacoco/jacoco/releases)
- [Commits](https://github.com/jacoco/jacoco/compare/v0.8.6...v0.8.7)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-05-05 11:03:47 +03:00
dependabot-preview[bot] 6438c323ff Upgrade to GitHub-native Dependabot (#22)
Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-04-29 01:49:29 +03:00
dependabot-preview[bot] 1cbff68338 Bump jackson-databind from 2.12.2 to 2.12.3 (#21)
Bumps [jackson-databind](https://github.com/FasterXML/jackson) from 2.12.2 to 2.12.3.
- [Release notes](https://github.com/FasterXML/jackson/releases)
- [Commits](https://github.com/FasterXML/jackson/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2021-04-22 11:05:09 +03:00
Prominence 1e08f4f8ae Switched to snapshot version. 2021-04-17 17:23:57 +03:00
Prominence bfa15fd9fe Made rebase onto master branch.
Implemented Air Pollution API functionality.

Preparing for merge.
2021-04-17 17:22:12 +03:00
Alexey Zinchenko 3c8b00eae1 Releasing 2.2.0 version. 2021-04-17 17:14:51 +03:00
Prominence f2c672b864 Added doc link. 2021-04-15 00:04:06 +03:00
Alexey Zinchenko e594ffb7ad 2.1.1 version implementation. 2021-04-15 00:00:48 +03:00
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
153 changed files with 15217 additions and 3086 deletions
+9
View File
@@ -0,0 +1,9 @@
version: 2
updates:
- package-ecosystem: maven
directory: "/"
schedule:
interval: daily
time: "03:00"
open-pull-requests-limit: 10
target-branch: dev
+2 -2
View File
@@ -13,10 +13,10 @@ name: "CodeQL"
on:
push:
branches: [ master ]
branches: [ dev ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master ]
branches: [ dev ]
schedule:
- cron: '27 20 * * 1'
+11 -4
View File
@@ -5,12 +5,15 @@ Java API for OpenWeatherMap services.
Free:
* Current weather data
* 5 day / 3-hour forecast
* One Call API
* Air pollution
Other:
* Request timeout settings
### Will be implemented later:
Free:
* One Call API
* Air pollution
* Geocoding API
* Weather Stations
* Weather Triggers
@@ -26,14 +29,14 @@ Paid:
<dependency>
<groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
<version>2.0.1</version>
<version>2.3.0</version>
</dependency>
```
### Gradle coordinates:
```groovy
compile('com.github.prominence:openweathermap-api:2.0.1')
compile('com.github.prominence:openweathermap-api:2.3.0')
```
### Documentation
@@ -42,6 +45,10 @@ compile('com.github.prominence:openweathermap-api:2.0.1')
* [OpenWeatherMap Java API - 1.2](docs/Release_1.2.md)
* [OpenWeatherMap Java API - 2.0.0](docs/Release_2.0.0.md)
* [OpenWeatherMap Java API - 2.0.1](docs/Release_2.0.1.md)
* [OpenWeatherMap Java API - 2.1.0](docs/Release_2.1.0.md)
* [OpenWeatherMap Java API - 2.1.1](docs/Release_2.1.1.md)
* [OpenWeatherMap Java API - 2.2.0](docs/Release_2.2.0.md)
* [OpenWeatherMap Java API - 2.3.0](docs/Release_2.3.0.md)
* [OpenWeatherMap Java API - SNAPSHOT](docs/SNAPSHOT.md)
### License
+1 -1
View File
@@ -79,7 +79,7 @@ final Weather weather = openWeatherClient
final List<Weather> weatherList = openWeatherClient
.currentWeather()
.multiple()
.byCitiesInCycle(Coordinate.withValues(55.5, 37.5))
.byCitiesInCycle(Coordinate.of(55.5, 37.5))
.language(Language.GERMAN)
.unitSystem(UnitSystem.IMPERIAL)
.retrieve()
+1 -1
View File
@@ -79,7 +79,7 @@ final Weather weather = openWeatherClient
final List<Weather> weatherList = openWeatherClient
.currentWeather()
.multiple()
.byCitiesInCycle(Coordinate.withValues(55.5, 37.5))
.byCitiesInCycle(Coordinate.of(55.5, 37.5))
.language(Language.GERMAN)
.unitSystem(UnitSystem.IMPERIAL)
.retrieve()
+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*)
+486
View File
@@ -0,0 +1,486 @@
### 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.1</version>
</dependency>
```
### Gradle coordinates:
```groovy
compile('com.github.prominence:openweathermap-api:2.1.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()`
* `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). |
| `getProbabilityOfPrecipitationPercentage()` | Returns probability of precipitation 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). |
| `getProbabilityOfPrecipitationPercentage()` | Returns probability of precipitation 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*)
+538
View File
@@ -0,0 +1,538 @@
### Implemented features:
* Current weather data
* 5 day / 3-hour forecast
* One Call API
* Air Pollution
### Maven coordinates:
```xml
<dependency>
<groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
<version>2.2.0</version>
</dependency>
```
### Gradle coordinates:
```groovy
compile('com.github.prominence:openweathermap-api:2.2.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()`
* `airPollution()`
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). |
| `getProbabilityOfPrecipitationPercentage()` | Returns probability of precipitation 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). |
| `getProbabilityOfPrecipitationPercentage()` | Returns probability of precipitation 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`. |
#### Air Pollution API
Examples:
```java
final AirPollutionDetails airPollutionDetails = openWeatherClient
.airPollution()
.current()
.byCoordinate(Coordinate.of(53.54, 27.34))
.retrieve()
.asJava();
```
```java
final AirPollutionDetails airPollutionDetails = openWeatherClient
.airPollution()
.historical()
.byCoordinateAndPeriod(Coordinate.of(53.54, 27.34), 1606223802, 1606482999)
.retrieve()
.asJava();
```
`com.github.prominence.openweathermap.api.model.air.pollution.AirPollutionDetails`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|---------------------------------------------------------------------------|
| `getCoordinate()` | Returns `Coordinate` object. Available fields: `latitude`, `longitude`. |
| `getAirPollutionRecords()` | Returns list of `AirPollutionRecord` objects. |
`com.github.prominence.openweathermap.api.model.air.pollution.AirPollutionRecord`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|---------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with air pollution forecast time. |
| `getAirQualityIndex()` | Returns `AirQualityIndex` object. |
| `getCO()` | Returns carbon monoxide concentration value in μg/m^3.s. |
| `getCarbonMonoxide()` | An alias for `getCO()` method. |
| `getNO()` | Returns nitrogen monoxide concentration value in μg/m^3. |
| `getNitrogenMonoxide()` | An alias for `getNO()` method. |
| `getNO2()` | Returns nitrogen dioxide concentration value in μg/m^3. |
| `getNitrogenDioxide()` | An alias for `getNO2()` method. |
| `getO3()` | Returns ozone concentration value in μg/m^3. |
| `getOzone()` | An alias for `getO3()` method. |
| `getSO2()` | Returns sulphur dioxide concentration value in μg/m^3. |
| `getSulphurDioxide()` | An alias for `getSO2()` method. |
| `getPM2_5()` | Returns fine particles matter concentration value in μg/m^3. |
| `getFineParticlesMatter()` | An alias for `getPM2_5()` method. |
| `getPM10()` | Returns coarse particulate matter concentration value in μg/m^3. |
| `getCoarseParticulateMatter()`| An alias for `getPM10()` method. |
| `getNH3()` | Returns ammonia concentration value in μg/m^3. |
| `getAmmonia()` | An alias for `getNH3()` method. |
### 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*)
+552
View File
@@ -0,0 +1,552 @@
### Implemented features:
* Current weather data
* 5 day / 3-hour forecast
* One Call API
* Air Pollution
Other:
* Request timeout settings
### Maven coordinates:
```xml
<dependency>
<groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
<version>2.3.0</version>
</dependency>
```
### Gradle coordinates:
```groovy
compile('com.github.prominence:openweathermap-api:2.3.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()`
* `airPollution()`
Also, it is possible to set timeouts for the requests on `openWeatherClient` object:
```java
openWeatherClient.setReadTimeout(1000);
openWeatherClient.setConnectTimeout(1000);
```
Timeout settings are passed to the requesters as a copy.
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). |
| `getProbabilityOfPrecipitationPercentage()` | Returns probability of precipitation 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. |
| `getMoonriseTime()` | Returns `LocalDateTime` object with moonrise time. |
| `getMoonsetTime()` | Returns `LocalDateTime` object with moonset time. |
| `getMoonPhase()` | Returns `MoonPhase` object with `MoonType` info and value. |
| `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). |
| `getProbabilityOfPrecipitationPercentage()` | Returns probability of precipitation 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`. |
#### Air Pollution API
Examples:
```java
final AirPollutionDetails airPollutionDetails = openWeatherClient
.airPollution()
.current()
.byCoordinate(Coordinate.of(53.54, 27.34))
.retrieve()
.asJava();
```
```java
final AirPollutionDetails airPollutionDetails = openWeatherClient
.airPollution()
.historical()
.byCoordinateAndPeriod(Coordinate.of(53.54, 27.34), 1606223802, 1606482999)
.retrieve()
.asJava();
```
`com.github.prominence.openweathermap.api.model.air.pollution.AirPollutionDetails`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|---------------------------------------------------------------------------|
| `getCoordinate()` | Returns `Coordinate` object. Available fields: `latitude`, `longitude`. |
| `getAirPollutionRecords()` | Returns list of `AirPollutionRecord` objects. |
`com.github.prominence.openweathermap.api.model.air.pollution.AirPollutionRecord`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|---------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with air pollution forecast time. |
| `getAirQualityIndex()` | Returns `AirQualityIndex` object. |
| `getCO()` | Returns carbon monoxide concentration value in μg/m^3.s. |
| `getCarbonMonoxide()` | An alias for `getCO()` method. |
| `getNO()` | Returns nitrogen monoxide concentration value in μg/m^3. |
| `getNitrogenMonoxide()` | An alias for `getNO()` method. |
| `getNO2()` | Returns nitrogen dioxide concentration value in μg/m^3. |
| `getNitrogenDioxide()` | An alias for `getNO2()` method. |
| `getO3()` | Returns ozone concentration value in μg/m^3. |
| `getOzone()` | An alias for `getO3()` method. |
| `getSO2()` | Returns sulphur dioxide concentration value in μg/m^3. |
| `getSulphurDioxide()` | An alias for `getSO2()` method. |
| `getPM2_5()` | Returns fine particles matter concentration value in μg/m^3. |
| `getFineParticlesMatter()` | An alias for `getPM2_5()` method. |
| `getPM10()` | Returns coarse particulate matter concentration value in μg/m^3. |
| `getCoarseParticulateMatter()`| An alias for `getPM10()` method. |
| `getNH3()` | Returns ammonia concentration value in μg/m^3. |
| `getAmmonia()` | An alias for `getNH3()` method. |
### 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.UKRAINIAN | 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.13.2.2
* org.slf4j:slf4j-api:1.7.36 (*compile*)
* org.junit.jupiter:junit-jupiter-engine:5.8.2 (*test*)
* org.junit.platform:junit-platform-runner:1.8.2 (*test*)
+348 -51
View File
@@ -1,6 +1,12 @@
### Implemented features:
* Current weather data
* 5 day / 3-hour forecast
* One Call API
* Air Pollution
Other:
* Request timeout settings
### Maven coordinates:
@@ -8,14 +14,14 @@
<dependency>
<groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
<version>2.0.1-SNAPSHOT</version>
<version>3.0.0-SNAPSHOT</version>
</dependency>
```
### Gradle coordinates:
```groovy
compile('com.github.prominence:openweathermap-api:2.0.1-SNAPSHOT')
compile('com.github.prominence:openweathermap-api:3.0.0-SNAPSHOT')
```
### How to use:
@@ -29,6 +35,15 @@ where `API_TOKEN` is your token([you can get it here](https://home.openweatherma
Currently, available APIs are:
* `currentWeather()`
* `forecast5Day3HourStep()`
* `oneCall()`
* `airPollution()`
Also, it is possible to set timeouts for the requests on `openWeatherClient` object:
```java
openWeatherClient.setReadTimeout(1000);
openWeatherClient.setConnectTimeout(1000);
```
Timeout settings are passed to the requesters as a copy.
Default(more or less) customization points:
```java
@@ -79,7 +94,7 @@ final Weather weather = openWeatherClient
final List<Weather> weatherList = openWeatherClient
.currentWeather()
.multiple()
.byCitiesInCycle(Coordinate.withValues(55.5, 37.5))
.byCitiesInCycle(Coordinate.of(55.5, 37.5))
.language(Language.GERMAN)
.unitSystem(UnitSystem.IMPERIAL)
.retrieve()
@@ -103,11 +118,8 @@ You are able to set preferable options(via chain methods) and execute appropriat
| Method | Description |
|---------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getState()` | Returns short weather description. Example: `Clear`. |
| `getDescription()` | Returns weather description. Example: `clear sky`. |
| `getWeatherIconId()` | Returns a weather state ID. Examples: `01d`, `01n`, `11n`, etc. |
| `getWeatherIconUrl()` | Returns a link to weather icon hosted on https://openweathermap.org website. |
| `getCalculatedOn()` | Returns `LocalDateTime` object with data calculation time. |
| `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. |
@@ -170,7 +182,7 @@ final String forecastXml = getClient()
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):
`com.github.prominence.openweathermap.api.model.forecast.free.Forecast`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------|
@@ -187,11 +199,8 @@ A forecast for Minsk with 15 timestamps.
| Method | Description |
|-------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getState()` | Returns short weather description. Example: `Clear`. |
| `getDescription()` | Returns weather description. Example: `clear sky`. |
| `getWeatherIconId()` | Returns a weather state ID. Examples: `01d`, `01n`, `11n`, etc. |
| `getWeatherIconUrl()` | Returns a link to weather icon hosted on https://openweathermap.org website. |
| `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. |
@@ -203,44 +212,331 @@ A forecast for Minsk with 15 timestamps.
| `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). |
| `getProbabilityOfPrecipitationPercentage()` | Returns probability of precipitation 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. |
| `getMoonriseTime()` | Returns `LocalDateTime` object with moonrise time. |
| `getMoonsetTime()` | Returns `LocalDateTime` object with moonset time. |
| `getMoonPhase()` | Returns `MoonPhase` object with `MoonType` info and value. |
| `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). |
| `getProbabilityOfPrecipitationPercentage()` | Returns probability of precipitation 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`. |
#### Air Pollution API
Examples:
```java
final AirPollutionDetails airPollutionDetails = openWeatherClient
.airPollution()
.current()
.byCoordinate(Coordinate.of(53.54, 27.34))
.retrieve()
.asJava();
```
```java
final AirPollutionDetails airPollutionDetails = openWeatherClient
.airPollution()
.historical()
.byCoordinateAndPeriod(Coordinate.of(53.54, 27.34), 1606223802, 1606482999)
.retrieve()
.asJava();
```
`com.github.prominence.openweathermap.api.model.air.pollution.AirPollutionDetails`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|---------------------------------------------------------------------------|
| `getCoordinate()` | Returns `Coordinate` object. Available fields: `latitude`, `longitude`. |
| `getAirPollutionRecords()` | Returns list of `AirPollutionRecord` objects. |
`com.github.prominence.openweathermap.api.model.air.pollution.AirPollutionRecord`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|---------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with air pollution forecast time. |
| `getAirQualityIndex()` | Returns `AirQualityIndex` object. |
| `getCO()` | Returns carbon monoxide concentration value in μg/m^3.s. |
| `getCarbonMonoxide()` | An alias for `getCO()` method. |
| `getNO()` | Returns nitrogen monoxide concentration value in μg/m^3. |
| `getNitrogenMonoxide()` | An alias for `getNO()` method. |
| `getNO2()` | Returns nitrogen dioxide concentration value in μg/m^3. |
| `getNitrogenDioxide()` | An alias for `getNO2()` method. |
| `getO3()` | Returns ozone concentration value in μg/m^3. |
| `getOzone()` | An alias for `getO3()` method. |
| `getSO2()` | Returns sulphur dioxide concentration value in μg/m^3. |
| `getSulphurDioxide()` | An alias for `getSO2()` method. |
| `getPM2_5()` | Returns fine particles matter concentration value in μg/m^3. |
| `getFineParticlesMatter()` | An alias for `getPM2_5()` method. |
| `getPM10()` | Returns coarse particulate matter concentration value in μg/m^3. |
| `getCoarseParticulateMatter()`| An alias for `getPM10()` method. |
| `getNH3()` | Returns ammonia concentration value in μg/m^3. |
| `getAmmonia()` | An alias for `getNH3()` method. |
### 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. |
| 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.UKRAINIAN | 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 |
@@ -250,6 +546,7 @@ A forecast for Minsk with 15 timestamps.
| 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*)
* com.fasterxml.jackson.core:jackson-databind:2.13.2.2
* org.slf4j:slf4j-api:1.7.36 (*compile*)
* org.junit.jupiter:junit-jupiter-engine:5.8.2 (*test*)
* org.junit.platform:junit-platform-runner:1.8.2 (*test*)
+26 -15
View File
@@ -6,7 +6,7 @@
<groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
<version>2.0.1</version>
<version>3.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Java OpenWeatherMap API</name>
@@ -27,7 +27,7 @@
<licenses>
<license>
<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>
</license>
</licenses>
@@ -61,16 +61,16 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<version>3.10.1</version>
<configuration>
<source>8</source>
<target>8</target>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<version>3.2.2</version>
<configuration>
<excludes>
<exclude>**/test/*</exclude>
@@ -80,7 +80,7 @@
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.8</version>
<version>1.6.12</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
@@ -104,7 +104,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.2.0</version>
<version>3.3.2</version>
<configuration>
<source>8</source>
</configuration>
@@ -120,7 +120,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<version>3.0.1</version>
<executions>
<execution>
<id>sign-artifacts</id>
@@ -134,7 +134,7 @@
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.6</version>
<version>0.8.8</version>
<executions>
<execution>
<goals>
@@ -150,6 +150,12 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
@@ -157,20 +163,25 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.2</version>
<version>2.13.2.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
<version>1.7.36</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>1.8.2</version>
</dependency>
</dependencies>
</project>
@@ -23,12 +23,14 @@
package com.github.prominence.openweathermap.api;
import com.github.prominence.openweathermap.api.annotation.SubscriptionAvailability;
import com.github.prominence.openweathermap.api.conf.TimeoutSettings;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.request.air.pollution.AirPollutionRequester;
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.weather.CurrentWeatherRequester;
import com.github.prominence.openweathermap.api.request.weather.CurrentWeatherRequesterImpl;
import static com.github.prominence.openweathermap.api.enums.SubscriptionPlan.*;
import static com.github.prominence.openweathermap.api.enums.SubscriptionPlan.ALL;
/**
* The main public API client to communicate with OpenWeatherMap services.
@@ -36,22 +38,31 @@ import static com.github.prominence.openweathermap.api.enums.SubscriptionPlan.*;
*/
public class OpenWeatherMapClient {
private final String apiKey;
private final TimeoutSettings timeoutSettings = new TimeoutSettings();
/**
* Created OpenWeatherMap client object.
* @param apiKey API key obtained on <a href="https://home.openweathermap.org/api_keys">OpwnWeatherMap site</a>.
* @param apiKey API key obtained on <a href="https://home.openweathermap.org/api_keys">OpenWeatherMap site</a>.
*/
public OpenWeatherMapClient(String apiKey) {
this.apiKey = apiKey;
}
public void setConnectionTimeout(int connectionTimeout) {
timeoutSettings.setConnectionTimeout(connectionTimeout);
}
public void setReadTimeout(int readTimeout) {
timeoutSettings.setReadTimeout(readTimeout);
}
/**
* 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);
return new CurrentWeatherRequester(new RequestSettings(apiKey, timeoutSettings));
}
/**
@@ -60,6 +71,26 @@ public class OpenWeatherMapClient {
*/
@SubscriptionAvailability(plans = ALL)
public FiveDayThreeHourStepForecastRequester forecast5Day3HourStep() {
return new FiveDayThreeHourStepForecastRequesterImpl(apiKey);
return new FiveDayThreeHourStepForecastRequester(new RequestSettings(apiKey, timeoutSettings));
}
/**
* 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 OneCallWeatherRequester(new RequestSettings(apiKey, timeoutSettings));
}
/**
* Air Pollution <a href="https://openweathermap.org/api/air-pollution">API</a>.
* Air Pollution API provides current, forecast and historical air pollution data for any coordinates on the globe.
* @return requester for air pollution information retrieval.
*/
@SubscriptionAvailability(plans = ALL)
public AirPollutionRequester airPollution() {
return new AirPollutionRequester(new RequestSettings(apiKey, timeoutSettings));
}
}
@@ -0,0 +1,58 @@
/*
* Copyright (c) 2022 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.conf;
public class TimeoutSettings {
private Integer connectionTimeout;
private Integer readTimeout;
public TimeoutSettings() {
this(2000, 2000);
}
public TimeoutSettings(Integer connectionTimeout, Integer readTimeout) {
this.connectionTimeout = connectionTimeout;
this.readTimeout = readTimeout;
}
public TimeoutSettings(TimeoutSettings from) {
this.connectionTimeout = from.connectionTimeout;
this.readTimeout = from.readTimeout;
}
public Integer getConnectionTimeout() {
return connectionTimeout;
}
public void setConnectionTimeout(Integer connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public Integer getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(Integer readTimeout) {
this.readTimeout = readTimeout;
}
}
@@ -0,0 +1,80 @@
/*
*
* * 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;
/**
* The enum Air quality index.
*/
public enum AirQualityIndex {
/**
* Good air quality index.
*/
GOOD(1),
/**
* Fair air quality index.
*/
FAIR(2),
/**
* Moderate air quality index.
*/
MODERATE(3),
/**
* Poor air quality index.
*/
POOR(4),
/**
* Very poor air quality index.
*/
VERY_POOR(5);
private final int value;
AirQualityIndex(int index) {
this.value = index;
}
/**
* Gets value.
*
* @return the value
*/
public int getValue() {
return value;
}
/**
* Gets by index.
*
* @param index the index
* @return the by index
*/
public static AirQualityIndex getByIndex(int index) {
final Optional<AirQualityIndex> optionalAirQualityIndex = Arrays.stream(values()).filter(airQualityIndex -> airQualityIndex.getValue() == index).findFirst();
return optionalAirQualityIndex.orElse(null);
}
}
@@ -27,11 +27,26 @@ package com.github.prominence.openweathermap.api.enums;
* 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.
*/
@@ -47,6 +62,11 @@ public enum Language {
*/
CZECH("cz"),
/**
* Danish language
*/
DANISH("da"),
/**
* German language.
*/
@@ -62,6 +82,11 @@ public enum Language {
*/
ENGLISH("en"),
/**
* Basque language.
*/
BASQUE("eu"),
/**
* Persian language.
*/
@@ -82,6 +107,16 @@ public enum Language {
*/
GALICIAN("gl"),
/**
* Hebrew language.
*/
HEBREW("he"),
/**
* Hindi language.
*/
HINDI("hi"),
/**
* Croatian language.
*/
@@ -92,6 +127,11 @@ public enum Language {
*/
HUNGARIAN("hu"),
/**
* Indonesian language.
*/
INDONESIAN("id"),
/**
* Italian language.
*/
@@ -122,6 +162,11 @@ public enum Language {
*/
MACEDONIAN("mk"),
/**
* Norwegian language.
*/
NORWEGIAN("no"),
/**
* Dutch language.
*/
@@ -137,6 +182,11 @@ public enum Language {
*/
PORTUGUESE("pt"),
/**
* Português Brasil language.
*/
PORTUGUES_BRAZIL("pt_br"),
/**
* Romanian language.
*/
@@ -165,7 +215,17 @@ public enum Language {
/**
* Spanish language.
*/
SPANISH("en"),
SPANISH("es"),
/**
* Serbian language.
*/
SERBIAN("sr"),
/**
* Thai language.
*/
THAI("th"),
/**
* Turkish language.
@@ -173,9 +233,9 @@ public enum Language {
TURKISH("tr"),
/**
* Ukranian language.
* Ukrainian language.
*/
UKRANIAN("uk"),
UKRAINIAN("uk"),
/**
* Vietnamese language.
@@ -190,7 +250,12 @@ public enum Language {
/**
* Chinese traditional language.
*/
CHINESE_TRADITIONAL("zh_tw");
CHINESE_TRADITIONAL("zh_tw"),
/**
* Zulu language.
*/
ZULU("zu");
private final String value;
@@ -0,0 +1,62 @@
/*
* Copyright (c) 2022 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;
public enum MoonType {
NEW_MOON,
WAXING_CRESCENT,
FIRST_QUARTER_MOON,
WAXING_GIBBOUS,
FULL_MOON,
WANING_GIBBOUS,
LAST_QUARTER_MOON,
WANING_CRESCENT,
INVALID;
private static final double precision = 0.000001d;
public static MoonType valueOf(double numericValue) {
if (equals(numericValue, 0) || equals(numericValue, 1)) {
return NEW_MOON;
} else if (equals(numericValue, 0.25)) {
return FIRST_QUARTER_MOON;
} else if (equals(numericValue, 0.5)) {
return FULL_MOON;
} else if (equals(numericValue, 0.75)) {
return LAST_QUARTER_MOON;
} else if (numericValue > 0 && numericValue < 0.25) {
return WAXING_CRESCENT;
} else if (numericValue > 0.25 && numericValue < 0.5) {
return WAXING_GIBBOUS;
} else if (numericValue > 0.5 && numericValue < 0.75) {
return WANING_GIBBOUS;
} else if (numericValue > 0.75 && numericValue < 1) {
return WANING_CRESCENT;
}
return INVALID;
}
private static boolean equals(double d1, double d2) {
return Math.abs(d1 - d2) < precision;
}
}
@@ -20,31 +20,45 @@
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
package com.github.prominence.openweathermap.api.enums;
/**
* The interface Request customizer.
*
* @param <T> the type parameter
* The enum One call result options.
*/
public interface RequestCustomizer<T extends RequestCustomizer<?>> {
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;
}
/**
* Customize language.
* Gets value.
*
* @param language the language
* @return the request customizer
* @return the value
*/
T language(Language language);
/**
* Customize unit system.
*
* @param unitSystem the unit system
* @return the request customizer
*/
T unitSystem(UnitSystem unitSystem);
public String getValue() {
return value;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
* Copyright (c) 2022 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
@@ -20,27 +20,23 @@
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request;
package com.github.prominence.openweathermap.api.enums;
/**
* The interface Request terminator.
*
* @param <T> the type parameter
* @param <S> the type parameter
*/
public interface RequestTerminator<T, S> {
public enum ResponseType {
HTML("html"),
XML("xml");
private final String value;
ResponseType(String value) {
this.value = value;
}
/**
* Java object response format.
*
* @return the java object
* Returns language's value.
* @return value.
*/
T asJava();
/**
* JSON response format.
*
* @return the JSON string
*/
S asJSON();
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 + ')';
}
}
@@ -0,0 +1,102 @@
/*
* Copyright (c) 2022 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.mapper;
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.AirQualityIndex;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.model.air.pollution.AirPollutionDetails;
import com.github.prominence.openweathermap.api.model.air.pollution.AirPollutionRecord;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
/**
* The type Air pollution response mapper.
*/
public class AirPollutionResponseMapper {
/**
* Map to air pollution air pollution.
*
* @param json the json
* @return the air pollution
*/
public AirPollutionDetails mapToAirPollution(String json) {
final ObjectMapper objectMapper = new ObjectMapper();
AirPollutionDetails airPollutionDetails;
try {
final JsonNode root = objectMapper.readTree(json);
airPollutionDetails = mapToAirPollution(root);
} catch (JsonProcessingException e) {
throw new RuntimeException("Cannot parse Air Pollution response");
}
return airPollutionDetails;
}
private AirPollutionDetails mapToAirPollution(JsonNode rootNode) {
final AirPollutionDetails airPollutionDetails = new AirPollutionDetails();
airPollutionDetails.setCoordinate(parseCoordinate(rootNode.get("coord")));
final List<AirPollutionRecord> sampleList = new ArrayList<>();
final JsonNode sampleListNode = rootNode.get("list");
sampleListNode.forEach(sampleNode -> {
sampleList.add(parseAirPollutionSample(sampleNode));
});
airPollutionDetails.setAirPollutionRecords(sampleList);
return airPollutionDetails;
}
private AirPollutionRecord parseAirPollutionSample(JsonNode sampleNode) {
AirPollutionRecord airPollutionRecord = new AirPollutionRecord();
airPollutionRecord.setForecastTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(sampleNode.get("dt").asInt()), TimeZone.getDefault().toZoneId()));
airPollutionRecord.setAirQualityIndex(AirQualityIndex.getByIndex(sampleNode.get("main").get("aqi").asInt()));
final JsonNode componentsNode = sampleNode.get("components");
airPollutionRecord.setCO(componentsNode.get("co").asDouble());
airPollutionRecord.setNO(componentsNode.get("no").asDouble());
airPollutionRecord.setNO2(componentsNode.get("no2").asDouble());
airPollutionRecord.setO3(componentsNode.get("o3").asDouble());
airPollutionRecord.setSO2(componentsNode.get("so2").asDouble());
airPollutionRecord.setPM2_5(componentsNode.get("pm2_5").asDouble());
airPollutionRecord.setPM10(componentsNode.get("pm10").asDouble());
airPollutionRecord.setNH3(componentsNode.get("nh3").asDouble());
return airPollutionRecord;
}
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;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
* Copyright (c) 2022 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
@@ -20,15 +20,15 @@
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.weather;
package com.github.prominence.openweathermap.api.mapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.prominence.openweathermap.api.model.weather.*;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.*;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
@@ -83,7 +83,6 @@ import java.util.TimeZone;
* --- cod Internal parameter
*/
public class CurrentWeatherResponseMapper {
private final UnitSystem unitSystem;
/**
@@ -102,12 +101,12 @@ public class CurrentWeatherResponseMapper {
* @return the weather object
*/
public Weather getSingle(String json) {
ObjectMapper objectMapper = new ObjectMapper();
final ObjectMapper objectMapper = new ObjectMapper();
Weather weather;
try {
JsonNode root = objectMapper.readTree(json);
final JsonNode root = objectMapper.readTree(json);
weather = getSingle(root);
} catch (IOException e) {
} catch (JsonProcessingException e) {
throw new RuntimeException("Cannot parse Weather response");
}
@@ -115,10 +114,11 @@ public class CurrentWeatherResponseMapper {
}
private Weather getSingle(JsonNode rootNode) {
JsonNode weatherState = rootNode.get("weather").get(0);
Weather weather = Weather.forValue(weatherState.get("main").asText(), weatherState.get("description").asText());
weather.setWeatherIconId(weatherState.get("icon").asText());
final JsonNode weatherArrayNode = rootNode.get("weather");
final JsonNode weatherNode = weatherArrayNode != null ? weatherArrayNode.get(0) : null;
final Weather weather = new Weather();
weather.setWeatherState(parseWeatherState(weatherNode));
weather.setTemperature(parseTemperature(rootNode));
weather.setAtmosphericPressure(parsePressure(rootNode));
weather.setHumidity(parseHumidity(rootNode));
@@ -130,7 +130,7 @@ public class CurrentWeatherResponseMapper {
final JsonNode dtNode = rootNode.get("dt");
if (dtNode != null) {
weather.setCalculatedOn(LocalDateTime.ofInstant(Instant.ofEpochSecond(dtNode.asInt()), TimeZone.getDefault().toZoneId()));
weather.setCalculationTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(dtNode.asInt()), TimeZone.getDefault().toZoneId()));
}
return weather;
@@ -143,25 +143,37 @@ public class CurrentWeatherResponseMapper {
* @return the list of weathers
*/
public List<Weather> getList(String json) {
ObjectMapper objectMapper = new ObjectMapper();
List<Weather> weatherList = new ArrayList<>();
final ObjectMapper objectMapper = new ObjectMapper();
final List<Weather> weatherList = new ArrayList<>();
try {
final JsonNode root = objectMapper.readTree(json);
final JsonNode listNode = root.get("list");
listNode.forEach(jsonNode -> weatherList.add(getSingle(jsonNode)));
} catch (IOException e) {
} catch (JsonProcessingException e) {
throw new RuntimeException("Cannot parse Weather response");
}
return weatherList;
}
private Temperature parseTemperature(JsonNode rootNode) {
Temperature temperature;
final JsonNode mainNode = rootNode.get("main");
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 JsonNode mainNode = rootNode.get("main");
final double tempValue = mainNode.get("temp").asDouble();
temperature = Temperature.withValue(tempValue, unitSystem.getTemperatureUnit());
final Temperature temperature = Temperature.withValue(tempValue, unitSystem.getTemperatureUnit());
final JsonNode feelsLikeNode = mainNode.get("feels_like");
if (feelsLikeNode != null) {
@@ -181,7 +193,7 @@ public class CurrentWeatherResponseMapper {
private AtmosphericPressure parsePressure(JsonNode rootNode) {
final JsonNode mainNode = rootNode.get("main");
AtmosphericPressure atmosphericPressure = AtmosphericPressure.withValue(mainNode.get("pressure").asDouble());
final AtmosphericPressure atmosphericPressure = AtmosphericPressure.withValue(mainNode.get("pressure").asDouble());
final JsonNode seaLevelNode = mainNode.get("sea_level");
final JsonNode groundLevelNode = mainNode.get("grnd_level");
@@ -205,7 +217,7 @@ public class CurrentWeatherResponseMapper {
final JsonNode windNode = rootNode.get("wind");
double speed = windNode.get("speed").asDouble();
Wind wind = Wind.withValue(speed, unitSystem.getWindUnit());
final Wind wind = Wind.withValue(speed, unitSystem.getWindUnit());
final JsonNode degNode = windNode.get("deg");
if (degNode != null) {
@@ -224,11 +236,11 @@ public class CurrentWeatherResponseMapper {
if (rainNode != null) {
final JsonNode oneHourNode = rainNode.get("1h");
final JsonNode threeHourNode = rainNode.get("3h");
if (oneHourNode != null && oneHourNode.isDouble() && threeHourNode != null && threeHourNode.isDouble()) {
if (oneHourNode != null && threeHourNode != null) {
return Rain.withValues(oneHourNode.asDouble(), threeHourNode.asDouble());
} else if (oneHourNode != null && oneHourNode.isDouble()) {
} else if (oneHourNode != null) {
return Rain.withOneHourLevelValue(oneHourNode.asDouble());
} else if (threeHourNode != null && threeHourNode.isDouble()) {
} else if (threeHourNode != null) {
return Rain.withThreeHourLevelValue(threeHourNode.asDouble());
}
}
@@ -240,11 +252,11 @@ public class CurrentWeatherResponseMapper {
if (snowNode != null) {
final JsonNode oneHourNode = snowNode.get("1h");
final JsonNode threeHourNode = snowNode.get("3h");
if (oneHourNode != null && oneHourNode.isDouble() && threeHourNode != null && threeHourNode.isDouble()) {
if (oneHourNode != null && threeHourNode != null) {
return Snow.withValues(oneHourNode.asDouble(), threeHourNode.asDouble());
} else if (oneHourNode != null && oneHourNode.isDouble()) {
} else if (oneHourNode != null) {
return Snow.withOneHourLevelValue(oneHourNode.asDouble());
} else if (threeHourNode != null && threeHourNode.isDouble()) {
} else if (threeHourNode != null) {
return Snow.withThreeHourLevelValue(threeHourNode.asDouble());
}
}
@@ -252,19 +264,17 @@ public class CurrentWeatherResponseMapper {
}
private Clouds parseClouds(JsonNode rootNode) {
Clouds clouds = null;
final JsonNode cloudsNode = rootNode.get("clouds");
final JsonNode allValueNode = cloudsNode.get("all");
if (allValueNode != null) {
clouds = Clouds.withValue((byte) allValueNode.asInt());
return Clouds.withValue((byte) allValueNode.asInt());
}
return clouds;
return null;
}
private Location parseLocation(JsonNode rootNode) {
Location location = Location.withValues(rootNode.get("id").asInt(), rootNode.get("name").asText());
final Location location = Location.withValues(rootNode.get("id").asInt(), rootNode.get("name").asText());
final JsonNode timezoneNode = rootNode.get("timezone");
if (timezoneNode != null) {
@@ -281,10 +291,10 @@ public class CurrentWeatherResponseMapper {
final JsonNode sunriseNode = sysNode.get("sunrise");
final JsonNode sunsetNode = sysNode.get("sunset");
if (sunriseNode != null) {
location.setSunrise(LocalDateTime.ofInstant(Instant.ofEpochSecond(sunriseNode.asInt()), TimeZone.getDefault().toZoneId()));
location.setSunriseTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(sunriseNode.asInt()), TimeZone.getDefault().toZoneId()));
}
if (sunsetNode != null) {
location.setSunset(LocalDateTime.ofInstant(Instant.ofEpochSecond(sunsetNode.asInt()), TimeZone.getDefault().toZoneId()));
location.setSunsetTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(sunsetNode.asInt()), TimeZone.getDefault().toZoneId()));
}
}
@@ -297,10 +307,10 @@ public class CurrentWeatherResponseMapper {
}
private Coordinate parseCoordinate(JsonNode rootNode) {
JsonNode latitudeNode = rootNode.get("lat");
JsonNode longitudeNode = rootNode.get("lon");
final JsonNode latitudeNode = rootNode.get("lat");
final JsonNode longitudeNode = rootNode.get("lon");
if (latitudeNode != null && longitudeNode != null) {
return Coordinate.withValues(latitudeNode.asDouble(), longitudeNode.asDouble());
return Coordinate.of(latitudeNode.asDouble(), longitudeNode.asDouble());
}
return null;
}
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
* Copyright (c) 2022 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
@@ -20,8 +20,9 @@
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.forecast.free;
package com.github.prominence.openweathermap.api.mapper;
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;
@@ -32,7 +33,6 @@ 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.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
@@ -87,7 +87,6 @@ import java.util.TimeZone;
* |- city.timezone Shift in seconds from UTC
*/
public class FiveDayThreeHourStepForecastResponseMapper {
private final UnitSystem unitSystem;
/**
@@ -106,12 +105,12 @@ public class FiveDayThreeHourStepForecastResponseMapper {
* @return the forecast
*/
public Forecast mapToForecast(String json) {
ObjectMapper objectMapper = new ObjectMapper();
final ObjectMapper objectMapper = new ObjectMapper();
Forecast forecast;
try {
JsonNode root = objectMapper.readTree(json);
final JsonNode root = objectMapper.readTree(json);
forecast = mapToForecast(root);
} catch (IOException e) {
} catch (JsonProcessingException e) {
throw new RuntimeException("Cannot parse Forecast response");
}
@@ -119,12 +118,12 @@ public class FiveDayThreeHourStepForecastResponseMapper {
}
private Forecast mapToForecast(JsonNode root) {
Forecast forecast = new Forecast();
final Forecast forecast = new Forecast();
forecast.setLocation(parseLocation(root.get("city")));
List<WeatherForecast> forecasts = new ArrayList<>(root.get("cnt").asInt());
final List<WeatherForecast> forecasts = new ArrayList<>(root.get("cnt").asInt());
JsonNode forecastListNode = root.get("list");
final JsonNode forecastListNode = root.get("list");
forecastListNode.forEach(forecastNode -> forecasts.add(parseWeatherForecast(forecastNode)));
forecast.setWeatherForecasts(forecasts);
@@ -133,14 +132,14 @@ public class FiveDayThreeHourStepForecastResponseMapper {
}
private WeatherForecast parseWeatherForecast(JsonNode rootNode) {
JsonNode weatherNode = rootNode.get("weather").get(0);
WeatherForecast weatherForecast = WeatherForecast.forValue(
weatherNode.get("main").asText(),
weatherNode.get("description").asText()
);
weatherForecast.setWeatherIconId(weatherNode.get("icon").asText());
final WeatherForecast weatherForecast = new WeatherForecast();
final JsonNode weatherArrayNode = rootNode.get("weather");
if (weatherArrayNode != null) {
final JsonNode weatherNode = weatherArrayNode.get(0);
weatherForecast.setWeatherState(parseWeatherState(weatherNode));
}
JsonNode mainNode = rootNode.get("main");
final JsonNode mainNode = rootNode.get("main");
weatherForecast.setTemperature(parseTemperature(mainNode));
weatherForecast.setAtmosphericPressure(parsePressure(mainNode));
weatherForecast.setHumidity(parseHumidity(mainNode));
@@ -149,7 +148,7 @@ public class FiveDayThreeHourStepForecastResponseMapper {
weatherForecast.setRain(parseRain(rootNode));
weatherForecast.setSnow(parseSnow(rootNode));
JsonNode sysNode = rootNode.get("sys");
final JsonNode sysNode = rootNode.get("sys");
if (sysNode != null) {
weatherForecast.setDayTime("d".equals(sysNode.get("pod").asText()) ? DayTime.DAY : DayTime.NIGHT);
}
@@ -160,9 +159,23 @@ public class FiveDayThreeHourStepForecastResponseMapper {
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();
Temperature temperature = Temperature.withValue(tempValue, unitSystem.getTemperatureUnit());
final Temperature temperature = Temperature.withValue(tempValue, unitSystem.getTemperatureUnit());
final JsonNode tempMaxNode = rootNode.get("temp_max");
if (tempMaxNode != null) {
@@ -172,7 +185,7 @@ public class FiveDayThreeHourStepForecastResponseMapper {
if (tempMinNode != null) {
temperature.setMinTemperature(tempMinNode.asDouble());
}
final JsonNode tempFeelsLike = rootNode.get("fells_like");
final JsonNode tempFeelsLike = rootNode.get("feels_like");
if (tempFeelsLike != null) {
temperature.setFeelsLike(tempFeelsLike.asDouble());
}
@@ -181,7 +194,7 @@ public class FiveDayThreeHourStepForecastResponseMapper {
}
private AtmosphericPressure parsePressure(JsonNode rootNode) {
AtmosphericPressure atmosphericPressure = AtmosphericPressure.withValue(rootNode.get("pressure").asDouble());
final AtmosphericPressure atmosphericPressure = AtmosphericPressure.withValue(rootNode.get("pressure").asDouble());
final JsonNode seaLevelNode = rootNode.get("sea_level");
final JsonNode groundLevelNode = rootNode.get("grnd_level");
@@ -203,7 +216,7 @@ public class FiveDayThreeHourStepForecastResponseMapper {
final JsonNode windNode = root.get("wind");
double speed = windNode.get("speed").asDouble();
Wind wind = Wind.withValue(speed, unitSystem.getWindUnit());
final Wind wind = Wind.withValue(speed, unitSystem.getWindUnit());
final JsonNode degNode = windNode.get("deg");
if (degNode != null) {
wind.setDegrees(degNode.asDouble());
@@ -228,26 +241,24 @@ public class FiveDayThreeHourStepForecastResponseMapper {
if (snowNode != null) {
final JsonNode threeHourNode = snowNode.get("3h");
if (threeHourNode != null) {
Rain.withThreeHourLevelValue(threeHourNode.asDouble());
return Snow.withThreeHourLevelValue(threeHourNode.asDouble());
}
}
return null;
}
private Clouds parseClouds(JsonNode rootNode) {
Clouds clouds = null;
final JsonNode cloudsNode = rootNode.get("clouds");
final JsonNode allValueNode = cloudsNode.get("all");
if (allValueNode != null) {
clouds = Clouds.withValue((byte) allValueNode.asInt());
return Clouds.withValue((byte) allValueNode.asInt());
}
return clouds;
return null;
}
private Location parseLocation(JsonNode rootNode) {
Location location = Location.withValues(rootNode.get("id").asInt(), rootNode.get("name").asText());
final Location location = Location.withValues(rootNode.get("id").asInt(), rootNode.get("name").asText());
final JsonNode timezoneNode = rootNode.get("timezone");
if (timezoneNode != null) {
@@ -262,10 +273,10 @@ public class FiveDayThreeHourStepForecastResponseMapper {
final JsonNode sunriseNode = rootNode.get("sunrise");
final JsonNode sunsetNode = rootNode.get("sunset");
if (sunriseNode != null) {
location.setSunrise(LocalDateTime.ofInstant(Instant.ofEpochSecond(sunriseNode.asLong()), TimeZone.getDefault().toZoneId()));
location.setSunriseTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(sunriseNode.asLong()), TimeZone.getDefault().toZoneId()));
}
if (sunsetNode != null) {
location.setSunset(LocalDateTime.ofInstant(Instant.ofEpochSecond(sunsetNode.asLong()), TimeZone.getDefault().toZoneId()));
location.setSunsetTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(sunsetNode.asLong()), TimeZone.getDefault().toZoneId()));
}
final JsonNode coordNode = rootNode.get("coord");
@@ -282,10 +293,10 @@ public class FiveDayThreeHourStepForecastResponseMapper {
}
private Coordinate parseCoordinate(JsonNode rootNode) {
JsonNode latitudeNode = rootNode.get("lat");
JsonNode longitudeNode = rootNode.get("lon");
final JsonNode latitudeNode = rootNode.get("lat");
final JsonNode longitudeNode = rootNode.get("lon");
if (latitudeNode != null && longitudeNode != null) {
return Coordinate.withValues(latitudeNode.asDouble(), longitudeNode.asDouble());
return Coordinate.of(latitudeNode.asDouble(), longitudeNode.asDouble());
}
return null;
}
@@ -0,0 +1,442 @@
/*
* Copyright (c) 2022 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.mapper;
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 OneCall 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 OneCall 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()));
final JsonNode moonriseTimeNode = dailyNode.get("moonrise");
if (moonriseTimeNode != null) {
daily.setMoonriseTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(moonriseTimeNode.asInt()), TimeZone.getDefault().toZoneId()));
}
final JsonNode moonsetTimeNode = dailyNode.get("moonset");
if (moonsetTimeNode != null) {
daily.setMoonsetTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(moonsetTimeNode.asInt()), TimeZone.getDefault().toZoneId()));
}
final JsonNode moonPhaseNode = dailyNode.get("moon_phase");
if (moonPhaseNode != null) {
daily.setMoonPhase(new MoonPhase(moonPhaseNode.asDouble()));
}
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;
}
}
@@ -31,9 +31,8 @@ public class Coordinate {
private double latitude;
private double longitude;
private Coordinate(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
private Coordinate() {
}
/**
@@ -42,14 +41,11 @@ public class Coordinate {
* @param longitude longitude
* @return coordinate object.
*/
public static Coordinate withValues(double latitude, double longitude) {
if (latitude < -90 || latitude > 90) {
throw new IllegalArgumentException("Latitude value must be in the next range: [-90.0; 90.0].");
}
if (longitude < -180 || longitude > 180) {
throw new IllegalArgumentException("Longitude value must be in the next range: [-180.0; 180.0].");
}
return new Coordinate(latitude, longitude);
public static Coordinate of(double latitude, double longitude) {
final Coordinate coordinate = new Coordinate();
coordinate.setLatitude(latitude);
coordinate.setLongitude(longitude);
return coordinate;
}
/**
@@ -154,7 +154,7 @@ public class Temperature {
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Temperature: ");
stringBuilder.append(value);
stringBuilder.append(' ');
@@ -0,0 +1,136 @@
/*
* 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 com.github.prominence.openweathermap.api.enums.WeatherCondition;
import java.util.Objects;
/**
* The type Weather state.
*/
public class WeatherState {
private final int id;
private final String name;
private final String description;
private String iconId;
private final WeatherCondition weatherConditionEnum;
public WeatherState(Integer id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
this.weatherConditionEnum = WeatherCondition.getById(id);
}
/**
* 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 icon id.
*
* @return the icon id
*/
public String getIconId() {
return iconId;
}
/**
* Sets icon id.
*
* @param iconId the icon id
*/
public void setIconId(String iconId) {
this.iconId = iconId;
}
/**
* Gets weather condition enum.
*
* @return the weather condition enum
*/
public WeatherCondition getWeatherConditionEnum() {
return weatherConditionEnum;
}
/**
* Gets weather icon url.
*
* @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
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WeatherState that = (WeatherState) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name) &&
Objects.equals(description, that.description) &&
Objects.equals(iconId, that.iconId);
}
@Override
public int hashCode() {
return Objects.hash(id, name, description, iconId, weatherConditionEnum);
}
@Override
public String toString() {
return "Weather state: " + name + "(" + description + ").";
}
}
@@ -0,0 +1,87 @@
/*
*
* * 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.air.pollution;
import com.github.prominence.openweathermap.api.model.Coordinate;
import java.util.List;
import java.util.Objects;
/**
* The type Air pollution.
*/
public class AirPollutionDetails {
private Coordinate coordinate;
private List<AirPollutionRecord> airPollutionRecords;
/**
* 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 air pollution details.
*
* @return the air pollution details
*/
public List<AirPollutionRecord> getAirPollutionRecords() {
return airPollutionRecords;
}
/**
* Sets air pollution details.
*
* @param airPollutionRecords the air pollution details
*/
public void setAirPollutionRecords(List<AirPollutionRecord> airPollutionRecords) {
this.airPollutionRecords = airPollutionRecords;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AirPollutionDetails that = (AirPollutionDetails) o;
return Objects.equals(coordinate, that.coordinate) && Objects.equals(airPollutionRecords, that.airPollutionRecords);
}
@Override
public int hashCode() {
return Objects.hash(coordinate, airPollutionRecords);
}
}
@@ -0,0 +1,376 @@
/*
*
* * 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.air.pollution;
import com.github.prominence.openweathermap.api.enums.AirQualityIndex;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.stream.Stream;
/**
* The type Air pollution record.
*/
public class AirPollutionRecord {
private LocalDateTime forecastTime;
private AirQualityIndex airQualityIndex;
private Double CO;
private Double NO;
private Double NO2;
private Double O3;
private Double SO2;
private Double PM2_5;
private Double PM10;
private Double NH3;
/**
* 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 air quality index.
*
* @return the air quality index
*/
public AirQualityIndex getAirQualityIndex() {
return airQualityIndex;
}
/**
* Sets air quality index.
*
* @param airQualityIndex the air quality index
*/
public void setAirQualityIndex(AirQualityIndex airQualityIndex) {
this.airQualityIndex = airQualityIndex;
}
/**
* Gets carbon monoxide concentration value in μg/m^3.
*
* @return the carbon monoxide value
*/
public Double getCO() {
return CO;
}
/**
* Gets carbon monoxide concentration value in μg/m^3.
*
* @return the carbon monoxide value
*/
public Double getCarbonMonoxide() {
return getCO();
}
/**
* Sets carbon monoxide concentration value in μg/m^3.
*
* @param CO the carbon monoxide value
*/
public void setCO(Double CO) {
this.CO = CO;
}
/**
* Gets nitrogen monoxide concentration value in μg/m^3.
*
* @return the nitrogen monoxide value
*/
public Double getNO() {
return NO;
}
/**
* Gets nitrogen monoxide concentration value in μg/m^3.
*
* @return the nitrogen monoxide value
*/
public Double getNitrogenMonoxide() {
return getNO();
}
/**
* Sets nitrogen monoxide concentration value in μg/m^3.
*
* @param NO the nitrogen monoxide value
*/
public void setNO(Double NO) {
this.NO = NO;
}
/**
* Gets nitrogen dioxide concentration value in μg/m^3.
*
* @return the nitrogen dioxide value
*/
public Double getNO2() {
return NO2;
}
/**
* Gets nitrogen dioxide concentration value in μg/m^3.
*
* @return the nitrogen dioxide value
*/
public Double getNitrogenDioxide() {
return getNO2();
}
/**
* Sets nitrogen dioxide concentration value in μg/m^3.
*
* @param NO2 the nitrogen dioxide value
*/
public void setNO2(Double NO2) {
this.NO2 = NO2;
}
/**
* Gets ozone concentration value in μg/m^3.
*
* @return the ozone value
*/
public Double getO3() {
return O3;
}
/**
* Gets ozone concentration value in μg/m^3.
*
* @return the ozone value
*/
public Double getOzone() {
return getO3();
}
/**
* Sets ozone concentration value in μg/m^3.
*
* @param o3 the ozone value
*/
public void setO3(Double o3) {
O3 = o3;
}
/**
* Gets sulphur dioxide concentration value in μg/m^3.
*
* @return the sulphur dioxide value
*/
public Double getSO2() {
return SO2;
}
/**
* Gets sulphur dioxide concentration value in μg/m^3.
*
* @return the sulphur dioxide value
*/
public Double getSulphurDioxide() {
return getSO2();
}
/**
* Sets sulphur dioxide concentration value in μg/m^3.
*
* @param SO2 the sulphur dioxide value
*/
public void setSO2(Double SO2) {
this.SO2 = SO2;
}
/**
* Gets fine particles matter concentration value in μg/m^3.
*
* @return the fine particles matter value
*/
public Double getPM2_5() {
return PM2_5;
}
/**
* Gets fine particles matter concentration value in μg/m^3.
*
* @return the fine particles matter value
*/
public Double getFineParticlesMatter() {
return getPM2_5();
}
/**
* Sets fine particles matter concentration value in μg/m^3.
*
* @param PM2_5 the fine particles matter value
*/
public void setPM2_5(Double PM2_5) {
this.PM2_5 = PM2_5;
}
/**
* Gets coarse particulate matter concentration value in μg/m^3.
*
* @return the coarse particulate matter value
*/
public Double getPM10() {
return PM10;
}
/**
* Gets coarse particulate matter concentration value in μg/m^3.
*
* @return the coarse particulate matter value
*/
public Double getCoarseParticulateMatter() {
return getPM10();
}
/**
* Sets coarse particulate matter concentration value in μg/m^3.
*
* @param PM10 the coarse particulate matter value
*/
public void setPM10(Double PM10) {
this.PM10 = PM10;
}
/**
* Gets ammonia concentration value in μg/m^3.
*
* @return the ammonia value
*/
public Double getNH3() {
return NH3;
}
/**
* Gets ammonia concentration value in μg/m^3.
*
* @return the ammonia value
*/
public Double getAmmonia() {
return getNH3();
}
/**
* Sets ammonia concentration value in μg/m^3.
*
* @param NH3 the ammonia value
*/
public void setNH3(Double NH3) {
this.NH3 = NH3;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AirPollutionRecord that = (AirPollutionRecord) o;
return Objects.equals(forecastTime, that.forecastTime) && airQualityIndex == that.airQualityIndex && Objects.equals(CO, that.CO) && Objects.equals(NO, that.NO) && Objects.equals(NO2, that.NO2) && Objects.equals(O3, that.O3) && Objects.equals(SO2, that.SO2) && Objects.equals(PM2_5, that.PM2_5) && Objects.equals(PM10, that.PM10) && Objects.equals(NH3, that.NH3);
}
@Override
public int hashCode() {
return Objects.hash(forecastTime, airQualityIndex, CO, NO, NO2, O3, SO2, PM2_5, PM10, NH3);
}
@Override
public String toString() {
final StringBuilder stringBuilder = new StringBuilder()
.append("Air Pollution Record for ")
.append(forecastTime)
.append(", AQI=")
.append(airQualityIndex.name())
.append(".");
final boolean anyConcentrationAvailable = Stream.of(CO, NO, NO2, O3, SO2, PM2_5, PM10, NH3).anyMatch(Objects::nonNull);
if (anyConcentrationAvailable) {
stringBuilder.append(" Concentrations:");
if (CO != null) {
stringBuilder
.append(" CO(Carbon monoxide) = ")
.append(CO)
.append(" μg/m^3;");
}
if (NO != null) {
stringBuilder
.append(" NO(Nitrogen monoxide) = ")
.append(NO)
.append(" μg/m^3;");
}
if (NO2 != null) {
stringBuilder
.append(" NO2(Nitrogen dioxide) = ")
.append(NO2)
.append(" μg/m^3;");
}
if (O3 != null) {
stringBuilder
.append(" O3(Ozone) = ")
.append(O3)
.append(" μg/m^3;");
}
if (SO2 != null) {
stringBuilder
.append(" SO2(Sulphur dioxide) = ")
.append(SO2)
.append(" μg/m^3;");
}
if (PM2_5 != null) {
stringBuilder
.append(" PM2.5(Fine particles matter) = ")
.append(PM2_5)
.append(" μg/m^3;");
}
if (PM10 != null) {
stringBuilder
.append(" PM10(Coarse particulate matter) = ")
.append(PM10)
.append(" μg/m^3;");
}
if (NH3 != null) {
stringBuilder
.append(" NH3(Ammonia) = ")
.append(NH3)
.append(" μg/m^3;");
}
}
return stringBuilder.toString();
}
}
@@ -36,8 +36,8 @@ public class Location {
private String name;
private String countryCode;
private LocalDateTime sunrise;
private LocalDateTime sunset;
private LocalDateTime sunriseTime;
private LocalDateTime sunsetTime;
private ZoneOffset zoneOffset;
private Coordinate coordinate;
@@ -114,32 +114,32 @@ public class Location {
* Returns location sunrise time.
* @return sunrise time
*/
public LocalDateTime getSunrise() {
return sunrise;
public LocalDateTime getSunriseTime() {
return sunriseTime;
}
/**
* Sets location sunrise time.
* @param sunrise sunrise time
* @param sunriseTime sunrise time
*/
public void setSunrise(LocalDateTime sunrise) {
this.sunrise = sunrise;
public void setSunriseTime(LocalDateTime sunriseTime) {
this.sunriseTime = sunriseTime;
}
/**
* Returns location sunset time.
* @return sunset time
*/
public LocalDateTime getSunset() {
return sunset;
public LocalDateTime getSunsetTime() {
return sunsetTime;
}
/**
* Sets location sunset time.
* @param sunset sunset time
* @param sunsetTime sunset time
*/
public void setSunset(LocalDateTime sunset) {
this.sunset = sunset;
public void setSunsetTime(LocalDateTime sunsetTime) {
this.sunsetTime = sunsetTime;
}
/**
@@ -198,8 +198,8 @@ public class Location {
return id == location.id &&
Objects.equals(name, location.name) &&
Objects.equals(countryCode, location.countryCode) &&
Objects.equals(sunrise, location.sunrise) &&
Objects.equals(sunset, location.sunset) &&
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);
@@ -207,7 +207,7 @@ public class Location {
@Override
public int hashCode() {
return Objects.hash(id, name, countryCode, sunrise, sunset, zoneOffset, coordinate, population);
return Objects.hash(id, name, countryCode, sunriseTime, sunsetTime, zoneOffset, coordinate, population);
}
@Override
@@ -30,41 +30,41 @@ import java.util.Objects;
public class Rain {
private static final String DEFAULT_UNIT = "mm";
private double threeHourRainLevel;
private double threeHourLevel;
private Rain(double threeHourRainLevel) {
this.threeHourRainLevel = threeHourRainLevel;
private Rain(double threeHourLevel) {
this.threeHourLevel = threeHourLevel;
}
/**
* Creates {@link Rain} object with correctness check.
* @param threeHourRainLevel 3-hour rain level value
* @param threeHourLevel 3-hour rain level value
* @return rain object.
*/
public static Rain withThreeHourLevelValue(double threeHourRainLevel) {
if (threeHourRainLevel < 0) {
public static Rain withThreeHourLevelValue(double threeHourLevel) {
if (threeHourLevel < 0) {
throw new IllegalArgumentException("Rain level value cannot be negative.");
}
return new Rain(threeHourRainLevel);
return new Rain(threeHourLevel);
}
/**
* Returns 3-hour rain level value.
* @return 3-hour rain level value
*/
public double getThreeHourRainLevel() {
return threeHourRainLevel;
public double getThreeHourLevel() {
return threeHourLevel;
}
/**
* Sets 3-hour rain level value with correctness check.
* @param threeHourRainLevel 3-hour rain level value
* @param threeHourLevel 3-hour rain level value
*/
public void setThreeHourRainLevel(double threeHourRainLevel) {
if (threeHourRainLevel < 0) {
public void setThreeHourLevel(double threeHourLevel) {
if (threeHourLevel < 0) {
throw new IllegalArgumentException("Rain level value cannot be negative.");
}
this.threeHourRainLevel = threeHourRainLevel;
this.threeHourLevel = threeHourLevel;
}
/**
@@ -80,18 +80,18 @@ public class Rain {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Rain rain = (Rain) o;
return Double.compare(rain.threeHourRainLevel, threeHourRainLevel) == 0;
return Double.compare(rain.threeHourLevel, threeHourLevel) == 0;
}
@Override
public int hashCode() {
return Objects.hash(threeHourRainLevel);
return Objects.hash(threeHourLevel);
}
@Override
public String toString() {
return "3-hour rain level: " +
threeHourRainLevel + ' ' +
threeHourLevel + ' ' +
getUnit();
}
}
@@ -30,41 +30,41 @@ import java.util.Objects;
public class Snow {
private static final String DEFAULT_UNIT = "mm";
private double threeHourSnowLevel;
private double threeHourLevel;
private Snow(double threeHourSnowLevel) {
this.threeHourSnowLevel = threeHourSnowLevel;
private Snow(double threeHourLevel) {
this.threeHourLevel = threeHourLevel;
}
/**
* Creates {@link Snow} object with correctness check.
* @param threeHourSnowLevel 3-hour snow level value
* @param threeHourLevel 3-hour snow level value
* @return snow object.
*/
public static Snow withThreeHourLevelValue(double threeHourSnowLevel) {
if (threeHourSnowLevel < 0) {
public static Snow withThreeHourLevelValue(double threeHourLevel) {
if (threeHourLevel < 0) {
throw new IllegalArgumentException("Snow level value cannot be negative.");
}
return new Snow(threeHourSnowLevel);
return new Snow(threeHourLevel);
}
/**
* Returns 3-hour snow level value.
* @return 3-hour snow level value
*/
public double getThreeHourSnowLevel() {
return threeHourSnowLevel;
public double getThreeHourLevel() {
return threeHourLevel;
}
/**
* Sets 3-hour snow level value with correctness check.
* @param threeHourSnowLevel 3-hour snow level value
* @param threeHourLevel 3-hour snow level value
*/
public void setThreeHourSnowLevel(double threeHourSnowLevel) {
if (threeHourSnowLevel < 0) {
public void setThreeHourLevel(double threeHourLevel) {
if (threeHourLevel < 0) {
throw new IllegalArgumentException("Snow level value cannot be negative.");
}
this.threeHourSnowLevel = threeHourSnowLevel;
this.threeHourLevel = threeHourLevel;
}
/**
@@ -80,18 +80,18 @@ public class Snow {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Snow snow = (Snow) o;
return Double.compare(snow.threeHourSnowLevel, threeHourSnowLevel) == 0;
return Double.compare(snow.threeHourLevel, threeHourLevel) == 0;
}
@Override
public int hashCode() {
return Objects.hash(threeHourSnowLevel);
return Objects.hash(threeHourLevel);
}
@Override
public String toString() {
return "3-hour snow level: " +
threeHourSnowLevel + ' ' +
threeHourLevel + ' ' +
getUnit();
}
}
@@ -31,12 +31,9 @@ import java.util.Objects;
* Represents weather forecast information for a particular timestamp.
*/
public class WeatherForecast {
private String state;
private String description;
private String weatherIconId;
private LocalDateTime forecastTime;
private WeatherState weatherState;
private Temperature temperature;
private AtmosphericPressure atmosphericPressure;
private Humidity humidity;
@@ -49,100 +46,6 @@ public class WeatherForecast {
private String forecastTimeISO;
private DayTime dayTime;
private WeatherForecast(String state, String description) {
this.state = state;
this.description = description;
}
/**
* For value weather forecast.
*
* @param state the state
* @param description the description
* @return the weather forecast
*/
public static WeatherForecast forValue(String state, String description) {
if (state == null) {
throw new IllegalArgumentException("State must be set.");
}
if (description == null) {
throw new IllegalArgumentException("Description must be set.");
}
return new WeatherForecast(state, description);
}
/**
* Gets state.
*
* @return the state
*/
public String getState() {
return state;
}
/**
* Sets state.
*
* @param state the state
*/
public void setState(String state) {
if (state == null) {
throw new IllegalArgumentException("State must be not null.");
}
this.state = state;
}
/**
* Gets description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Sets description.
*
* @param description the description
*/
public void setDescription(String description) {
if (description == null) {
throw new IllegalArgumentException("Description must be not null.");
}
this.description = description;
}
/**
* Gets weather icon ID.
*
* @return the weather icon ID
*/
public String getWeatherIconId() {
return weatherIconId;
}
/**
* Sets weather icon ID.
*
* @param weatherIconId the weather icon ID
*/
public void setWeatherIconId(String weatherIconId) {
this.weatherIconId = weatherIconId;
}
/**
* Gets weather icon url.
*
* @return the weather icon url
*/
public String getWeatherIconUrl() {
if (weatherIconId != null) {
return "https://openweathermap.org/img/w/" + weatherIconId + ".png";
}
return null;
}
/**
* Gets forecast time.
*
@@ -161,6 +64,24 @@ public class WeatherForecast {
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.
*
@@ -328,10 +249,8 @@ public class WeatherForecast {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WeatherForecast that = (WeatherForecast) o;
return Objects.equals(state, that.state) &&
Objects.equals(description, that.description) &&
Objects.equals(weatherIconId, that.weatherIconId) &&
Objects.equals(forecastTime, that.forecastTime) &&
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) &&
@@ -345,7 +264,7 @@ public class WeatherForecast {
@Override
public int hashCode() {
return Objects.hash(state, description, weatherIconId, forecastTime, temperature, atmosphericPressure, humidity, wind, rain, snow, clouds, forecastTimeISO, dayTime);
return Objects.hash(forecastTime, weatherState, temperature, atmosphericPressure, humidity, wind, rain, snow, clouds, forecastTimeISO, dayTime);
}
@Override
@@ -353,8 +272,10 @@ public class WeatherForecast {
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Timestamp: ");
stringBuilder.append(forecastTimeISO);
stringBuilder.append(", Weather: ");
stringBuilder.append(description);
if (weatherState != null) {
stringBuilder.append(", Weather: ");
stringBuilder.append(weatherState.getDescription());
}
if (temperature != null) {
stringBuilder.append(", ");
stringBuilder.append(temperature.getValue());
@@ -373,13 +294,13 @@ public class WeatherForecast {
}
if (rain != null) {
stringBuilder.append(", Rain: ");
stringBuilder.append(rain.getThreeHourRainLevel());
stringBuilder.append(rain.getThreeHourLevel());
stringBuilder.append(' ');
stringBuilder.append(rain.getUnit());
}
if (snow != null) {
stringBuilder.append(", Snow: ");
stringBuilder.append(snow.getThreeHourSnowLevel());
stringBuilder.append(snow.getThreeHourLevel());
stringBuilder.append(' ');
stringBuilder.append(snow.getUnit());
}
@@ -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,438 @@
/*
* 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 LocalDateTime moonriseTime;
private LocalDateTime moonsetTime;
private MoonPhase moonPhase;
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 moonrise time.
*
* @return the moonrise time
*/
public LocalDateTime getMoonriseTime() {
return moonriseTime;
}
/**
* Sets moonrise time.
*
* @param moonriseTime the moonrise time
*/
public void setMoonriseTime(LocalDateTime moonriseTime) {
this.moonriseTime = moonriseTime;
}
/**
* Gets moonset time.
*
* @return the moonset time
*/
public LocalDateTime getMoonsetTime() {
return moonsetTime;
}
/**
* Sets moonset time.
*
* @param moonsetTime the moonset time
*/
public void setMoonsetTime(LocalDateTime moonsetTime) {
this.moonsetTime = moonsetTime;
}
/**
* Gets moon phase.
*
* @return the moon phase
*/
public MoonPhase getMoonPhase() {
return moonPhase;
}
/**
* Sets moon phase.
*
* @param moonPhase the moon phase
*/
public void setMoonPhase(MoonPhase moonPhase) {
this.moonPhase = moonPhase;
}
/**
* 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 probability of precipitation percentage.
*
* @return the probability of precipitation percentage
*/
public Byte getProbabilityOfPrecipitationPercentage() {
if (probabilityOfPrecipitation != null) {
return (byte)(probabilityOfPrecipitation * 100);
}
return null;
}
/**
* 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(moonriseTime, daily.moonriseTime) &&
Objects.equals(moonsetTime, daily.moonsetTime) &&
Objects.equals(moonPhase, daily.moonPhase) &&
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, moonriseTime, moonsetTime, moonPhase, 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);
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,311 @@
/*
* 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) {
if (probabilityOfPrecipitation != null && (probabilityOfPrecipitation < 0 || probabilityOfPrecipitation > 100)) {
throw new IllegalArgumentException("Probability of precipitation value must be in [0, 100] range.");
}
this.probabilityOfPrecipitation = probabilityOfPrecipitation;
}
/**
* Gets probability of precipitation percentage.
*
* @return the probability of precipitation percentage
*/
public Byte getProbabilityOfPrecipitationPercentage() {
if (probabilityOfPrecipitation != null) {
return (byte)(probabilityOfPrecipitation * 100);
}
return null;
}
/**
* 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;
}
}
@@ -0,0 +1,63 @@
/*
* Copyright (c) 2022 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.enums.MoonType;
import java.util.Objects;
public class MoonPhase {
private final double value;
private final MoonType type;
public MoonPhase(Double value) {
this.value = value;
this.type = MoonType.valueOf(value);
}
public Double getValue() {
return value;
}
public MoonType getType() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MoonPhase moonPhase = (MoonPhase) o;
return Double.compare(moonPhase.value, value) == 0 && type == moonPhase.type;
}
@Override
public int hashCode() {
return Objects.hash(value, type);
}
@Override
public String toString() {
return type.name() + "(" + value + ")";
}
}
@@ -20,15 +20,16 @@
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request;
package com.github.prominence.openweathermap.api.model.onecall.historical;
import java.util.concurrent.CompletableFuture;
import com.github.prominence.openweathermap.api.model.onecall.*;
/**
* The interface Async request terminator.
*
* @param <T> the type parameter
* @param <S> the type parameter
* The type Historical weather.
*/
public interface AsyncRequestTerminator<T, S> extends RequestTerminator<CompletableFuture<T>, CompletableFuture<S>> {
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 + ".";
}
}
@@ -36,8 +36,8 @@ public class Location {
private String name;
private String countryCode;
private LocalDateTime sunrise;
private LocalDateTime sunset;
private LocalDateTime sunriseTime;
private LocalDateTime sunsetTime;
private ZoneOffset zoneOffset;
private Coordinate coordinate;
@@ -112,32 +112,32 @@ public class Location {
* Returns location sunrise time.
* @return sunrise time
*/
public LocalDateTime getSunrise() {
return sunrise;
public LocalDateTime getSunriseTime() {
return sunriseTime;
}
/**
* Sets location sunrise time.
* @param sunrise sunrise time
* @param sunriseTime sunrise time
*/
public void setSunrise(LocalDateTime sunrise) {
this.sunrise = sunrise;
public void setSunriseTime(LocalDateTime sunriseTime) {
this.sunriseTime = sunriseTime;
}
/**
* Returns location sunset time.
* @return sunset time
*/
public LocalDateTime getSunset() {
return sunset;
public LocalDateTime getSunsetTime() {
return sunsetTime;
}
/**
* Sets location sunset time.
* @param sunset sunset time
* @param sunsetTime sunset time
*/
public void setSunset(LocalDateTime sunset) {
this.sunset = sunset;
public void setSunsetTime(LocalDateTime sunsetTime) {
this.sunsetTime = sunsetTime;
}
/**
@@ -180,15 +180,15 @@ public class Location {
return id == location.id &&
Objects.equals(name, location.name) &&
Objects.equals(countryCode, location.countryCode) &&
Objects.equals(sunrise, location.sunrise) &&
Objects.equals(sunset, location.sunset) &&
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, sunrise, sunset, zoneOffset, coordinate);
return Objects.hash(id, name, countryCode, sunriseTime, sunsetTime, zoneOffset, coordinate);
}
@Override
@@ -30,8 +30,8 @@ import java.util.Objects;
public class Rain {
private static final String DEFAULT_UNIT = "mm";
private Double oneHourRainLevel;
private Double threeHourRainLevel;
private Double oneHourLevel;
private Double threeHourLevel;
private Rain() {
}
@@ -39,38 +39,38 @@ public class Rain {
/**
* Creates {@link Rain} object with correctness check.
*
* @param oneHourRainLevel 1-hour rain level value
* @param oneHourLevel 1-hour rain level value
* @return rain object.
*/
public static Rain withOneHourLevelValue(double oneHourRainLevel) {
Rain rain = new Rain();
rain.setOneHourRainLevel(oneHourRainLevel);
public static Rain withOneHourLevelValue(double oneHourLevel) {
final Rain rain = new Rain();
rain.setOneHourLevel(oneHourLevel);
return rain;
}
/**
* Creates {@link Rain} object with correctness check.
*
* @param threeHourRainLevel 3-hour rain level value
* @param threeHourLevel 3-hour rain level value
* @return rain object.
*/
public static Rain withThreeHourLevelValue(double threeHourRainLevel) {
Rain rain = new Rain();
rain.setThreeHourRainLevel(threeHourRainLevel);
public static Rain withThreeHourLevelValue(double threeHourLevel) {
final Rain rain = new Rain();
rain.setThreeHourLevel(threeHourLevel);
return rain;
}
/**
* Creates {@link Rain} object with correctness check.
*
* @param oneHourRainLevel the one hour rain level
* @param threeHourRainLevel the three hour rain level
* @param oneHourLevel the one hour rain level
* @param threeHourLevel the three hour rain level
* @return the rain
*/
public static Rain withValues(double oneHourRainLevel, double threeHourRainLevel) {
Rain rain = new Rain();
rain.setOneHourRainLevel(oneHourRainLevel);
rain.setThreeHourRainLevel(threeHourRainLevel);
public static Rain withValues(double oneHourLevel, double threeHourLevel) {
final Rain rain = new Rain();
rain.setOneHourLevel(oneHourLevel);
rain.setThreeHourLevel(threeHourLevel);
return rain;
}
@@ -79,20 +79,20 @@ public class Rain {
*
* @return the one hour rain level
*/
public Double getOneHourRainLevel() {
return oneHourRainLevel;
public Double getOneHourLevel() {
return oneHourLevel;
}
/**
* Sets one hour rain level.
*
* @param oneHourRainLevel the one hour rain level
* @param oneHourLevel the one hour rain level
*/
public void setOneHourRainLevel(double oneHourRainLevel) {
if (oneHourRainLevel < 0) {
public void setOneHourLevel(double oneHourLevel) {
if (oneHourLevel < 0) {
throw new IllegalArgumentException("Rain level value cannot be negative.");
}
this.oneHourRainLevel = oneHourRainLevel;
this.oneHourLevel = oneHourLevel;
}
/**
@@ -100,20 +100,20 @@ public class Rain {
*
* @return the three hour rain level
*/
public Double getThreeHourRainLevel() {
return threeHourRainLevel;
public Double getThreeHourLevel() {
return threeHourLevel;
}
/**
* Sets three hour rain level.
*
* @param threeHourRainLevel the three hour rain level
* @param threeHourLevel the three hour rain level
*/
public void setThreeHourRainLevel(double threeHourRainLevel) {
if (threeHourRainLevel < 0) {
public void setThreeHourLevel(double threeHourLevel) {
if (threeHourLevel < 0) {
throw new IllegalArgumentException("Rain level value cannot be negative.");
}
this.threeHourRainLevel = threeHourRainLevel;
this.threeHourLevel = threeHourLevel;
}
/**
@@ -130,29 +130,29 @@ public class Rain {
if (this == o) return true;
if (!(o instanceof Rain)) return false;
Rain rain = (Rain) o;
return Objects.equals(oneHourRainLevel, rain.oneHourRainLevel) &&
Objects.equals(threeHourRainLevel, rain.threeHourRainLevel);
return Objects.equals(oneHourLevel, rain.oneHourLevel) &&
Objects.equals(threeHourLevel, rain.threeHourLevel);
}
@Override
public int hashCode() {
return Objects.hash(oneHourRainLevel, threeHourRainLevel);
return Objects.hash(oneHourLevel, threeHourLevel);
}
@Override
public String toString() {
StringBuilder snowString = new StringBuilder();
if (oneHourRainLevel != null) {
final StringBuilder snowString = new StringBuilder();
if (oneHourLevel != null) {
snowString.append("1-hour rain level: ");
snowString.append(oneHourRainLevel);
snowString.append(oneHourLevel);
snowString.append(getUnit());
}
if (threeHourRainLevel != null) {
if (oneHourRainLevel != null) {
if (threeHourLevel != null) {
if (oneHourLevel != null) {
snowString.append(", ");
}
snowString.append("3-hours rain level: ");
snowString.append(threeHourRainLevel);
snowString.append(threeHourLevel);
snowString.append(getUnit());
}
return snowString.toString();
@@ -30,8 +30,8 @@ import java.util.Objects;
public class Snow {
private static final String DEFAULT_UNIT = "mm";
private Double oneHourSnowLevel;
private Double threeHourSnowLevel;
private Double oneHourLevel;
private Double threeHourLevel;
private Snow() {
}
@@ -39,38 +39,38 @@ public class Snow {
/**
* Creates {@link Snow} object with correctness check.
*
* @param oneHourSnowLevel 1-hour snow level value
* @param oneHourLevel 1-hour snow level value
* @return snow object.
*/
public static Snow withOneHourLevelValue(double oneHourSnowLevel) {
Snow snow = new Snow();
snow.setOneHourSnowLevel(oneHourSnowLevel);
public static Snow withOneHourLevelValue(double oneHourLevel) {
final Snow snow = new Snow();
snow.setOneHourLevel(oneHourLevel);
return snow;
}
/**
* Creates {@link Snow} object with correctness check.
*
* @param threeHourSnowLevel 3-hour snow level value
* @param threeHourLevel 3-hour snow level value
* @return snow object.
*/
public static Snow withThreeHourLevelValue(double threeHourSnowLevel) {
Snow snow = new Snow();
snow.setThreeHourSnowLevel(threeHourSnowLevel);
public static Snow withThreeHourLevelValue(double threeHourLevel) {
final Snow snow = new Snow();
snow.setThreeHourLevel(threeHourLevel);
return snow;
}
/**
* Creates {@link Snow} object with correctness check.
*
* @param oneHourSnowLevel the one hour snow level
* @param threeHourSnowLevel the three hour snow level
* @param oneHourLevel the one hour snow level
* @param threeHourLevel the three hour snow level
* @return the snow
*/
public static Snow withValues(double oneHourSnowLevel, double threeHourSnowLevel) {
Snow snow = new Snow();
snow.setOneHourSnowLevel(oneHourSnowLevel);
snow.setThreeHourSnowLevel(threeHourSnowLevel);
public static Snow withValues(double oneHourLevel, double threeHourLevel) {
final Snow snow = new Snow();
snow.setOneHourLevel(oneHourLevel);
snow.setThreeHourLevel(threeHourLevel);
return snow;
}
@@ -79,20 +79,20 @@ public class Snow {
*
* @return the one hour snow level
*/
public Double getOneHourSnowLevel() {
return oneHourSnowLevel;
public Double getOneHourLevel() {
return oneHourLevel;
}
/**
* Sets one hour snow level.
*
* @param oneHourSnowLevel the one hour snow level
* @param oneHourLevel the one hour snow level
*/
public void setOneHourSnowLevel(double oneHourSnowLevel) {
if (oneHourSnowLevel < 0) {
public void setOneHourLevel(double oneHourLevel) {
if (oneHourLevel < 0) {
throw new IllegalArgumentException("Snow level value cannot be negative.");
}
this.oneHourSnowLevel = oneHourSnowLevel;
this.oneHourLevel = oneHourLevel;
}
/**
@@ -100,20 +100,20 @@ public class Snow {
*
* @return the three hour snow level
*/
public Double getThreeHourSnowLevel() {
return threeHourSnowLevel;
public Double getThreeHourLevel() {
return threeHourLevel;
}
/**
* Sets three hour snow level.
*
* @param threeHourSnowLevel the three hour snow level
* @param threeHourLevel the three hour snow level
*/
public void setThreeHourSnowLevel(double threeHourSnowLevel) {
if (threeHourSnowLevel < 0) {
public void setThreeHourLevel(double threeHourLevel) {
if (threeHourLevel < 0) {
throw new IllegalArgumentException("Snow level value cannot be negative.");
}
this.threeHourSnowLevel = threeHourSnowLevel;
this.threeHourLevel = threeHourLevel;
}
/**
@@ -130,29 +130,29 @@ public class Snow {
if (this == o) return true;
if (!(o instanceof Snow)) return false;
Snow snow = (Snow) o;
return Objects.equals(oneHourSnowLevel, snow.oneHourSnowLevel) &&
Objects.equals(threeHourSnowLevel, snow.threeHourSnowLevel);
return Objects.equals(oneHourLevel, snow.oneHourLevel) &&
Objects.equals(threeHourLevel, snow.threeHourLevel);
}
@Override
public int hashCode() {
return Objects.hash(oneHourSnowLevel, threeHourSnowLevel);
return Objects.hash(oneHourLevel, threeHourLevel);
}
@Override
public String toString() {
StringBuilder snowString = new StringBuilder();
if (oneHourSnowLevel != null) {
final StringBuilder snowString = new StringBuilder();
if (oneHourLevel != null) {
snowString.append("1-hour snow level: ");
snowString.append(oneHourSnowLevel);
snowString.append(oneHourLevel);
snowString.append(getUnit());
}
if (threeHourSnowLevel != null) {
if (oneHourSnowLevel != null) {
if (threeHourLevel != null) {
if (oneHourLevel != null) {
snowString.append(", ");
}
snowString.append("3-hours snow level: ");
snowString.append(threeHourSnowLevel);
snowString.append(threeHourLevel);
snowString.append(getUnit());
}
return snowString.toString();
@@ -31,12 +31,9 @@ import java.util.Objects;
* Represents weather information.
*/
public class Weather {
private String state;
private String description;
private String weatherIconId;
private LocalDateTime calculatedOn;
private LocalDateTime calculationTime;
private WeatherState weatherState;
private Temperature temperature;
private AtmosphericPressure atmosphericPressure;
private Humidity humidity;
@@ -48,116 +45,40 @@ public class Weather {
private Location location;
private Weather(String state, String description) {
this.state = state;
this.description = description;
}
/**
* For value weather.
*
* @param state the state
* @param description the description
* @return the weather
*/
public static Weather forValue(String state, String description) {
if (state == null) {
throw new IllegalArgumentException("State must be set.");
}
if (description == null) {
throw new IllegalArgumentException("Description must be set.");
}
return new Weather(state, description);
}
/**
* Gets state.
*
* @return the state
*/
public String getState() {
return state;
}
/**
* Sets state.
*
* @param state the state
*/
public void setState(String state) {
if (state == null) {
throw new IllegalArgumentException("State must be set.");
}
this.state = state;
}
/**
* Gets description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Sets description.
*
* @param description the description
*/
public void setDescription(String description) {
if (description == null) {
throw new IllegalArgumentException("Description must be set.");
}
this.description = description;
}
/**
* Gets weather icon ID.
*
* @return the weather icon ID
*/
public String getWeatherIconId() {
return weatherIconId;
}
/**
* Sets weather icon ID.
*
* @param weatherIconId the weather icon ID
*/
public void setWeatherIconId(String weatherIconId) {
this.weatherIconId = weatherIconId;
}
/**
* Gets weather icon url.
*
* @return the weather icon url
*/
public String getWeatherIconUrl() {
if (weatherIconId != null) {
return "http://openweathermap.org/img/w/" + weatherIconId + ".png";
}
return null;
}
/**
* Gets calculated on.
*
* @return the calculated on
*/
public LocalDateTime getCalculatedOn() {
return calculatedOn;
public LocalDateTime getCalculationTime() {
return calculationTime;
}
/**
* Sets calculated on.
*
* @param calculatedOn the calculated on
* @param calculationTime the calculated on
*/
public void setCalculatedOn(LocalDateTime calculatedOn) {
this.calculatedOn = calculatedOn;
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;
}
/**
@@ -309,10 +230,8 @@ public class Weather {
if (this == o) return true;
if (!(o instanceof Weather)) return false;
Weather weather = (Weather) o;
return Objects.equals(state, weather.state) &&
Objects.equals(description, weather.description) &&
Objects.equals(weatherIconId, weather.weatherIconId) &&
Objects.equals(calculatedOn, weather.calculatedOn) &&
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) &&
@@ -325,7 +244,7 @@ public class Weather {
@Override
public int hashCode() {
return Objects.hash(state, description, weatherIconId, calculatedOn, temperature, atmosphericPressure, humidity, wind, rain, snow, clouds, location);
return Objects.hash(calculationTime, weatherState, temperature, atmosphericPressure, humidity, wind, rain, snow, clouds, location);
}
@Override
@@ -342,8 +261,10 @@ public class Weather {
stringBuilder.append(')');
}
}
stringBuilder.append(", Weather: ");
stringBuilder.append(description);
if (weatherState != null) {
stringBuilder.append(", Weather: ");
stringBuilder.append(weatherState.getDescription());
}
if (temperature != null) {
stringBuilder.append(", ");
stringBuilder.append(temperature.getValue());
@@ -360,15 +281,15 @@ public class Weather {
stringBuilder.append(", ");
stringBuilder.append(clouds.toString());
}
if (rain != null && rain.getOneHourRainLevel() != null) {
if (rain != null && rain.getOneHourLevel() != null) {
stringBuilder.append(", Rain: ");
stringBuilder.append(rain.getOneHourRainLevel());
stringBuilder.append(rain.getOneHourLevel());
stringBuilder.append(' ');
stringBuilder.append(rain.getUnit());
}
if (snow != null && snow.getOneHourSnowLevel() != null) {
if (snow != null && snow.getOneHourLevel() != null) {
stringBuilder.append(", Snow: ");
stringBuilder.append(snow.getOneHourSnowLevel());
stringBuilder.append(snow.getOneHourLevel());
stringBuilder.append(' ');
stringBuilder.append(snow.getUnit());
}
@@ -0,0 +1,100 @@
/*
* Copyright (c) 2022 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.conf.TimeoutSettings;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.ResponseType;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import java.util.HashMap;
import java.util.Map;
public class RequestSettings {
private static final String LANG_PARAM = "lang";
private static final String UNITS_PARAM = "units";
private static final String MODE_PARAM = "mode";
private static final String API_KEY_PARAM_NAME = "appid";
private final TimeoutSettings timeoutSettings;
private final Map<String, String> requestParameters = new HashMap<>(8);
private final StringBuilder urlAppenderBuilder = new StringBuilder("");
private Language language = Language.ENGLISH;
private UnitSystem unitSystem = UnitSystem.STANDARD;
public RequestSettings(String apiKey, TimeoutSettings timeoutSettings) {
this.putRequestParameter(API_KEY_PARAM_NAME, apiKey);
// make a copy
this.timeoutSettings = new TimeoutSettings(timeoutSettings);
}
public TimeoutSettings getTimeoutSettings() {
return timeoutSettings;
}
public UnitSystem getUnitSystem() {
return unitSystem;
}
public void setUnitSystem(UnitSystem unitSystem) {
this.putRequestParameter(UNITS_PARAM, unitSystem.getValue());
this.unitSystem = unitSystem;
}
public Language getLanguage() {
return language;
}
public void setLanguage(Language language) {
this.putRequestParameter(LANG_PARAM, language.getValue());
this.language = language;
}
public void setResponseType(ResponseType responseType) {
this.putRequestParameter(MODE_PARAM, responseType.getValue());
}
public void putRequestParameter(String key, String value) {
this.requestParameters.put(key, value);
}
public void removeRequestParameter(String key) {
this.requestParameters.remove(key);
}
public Map<String, String> getRequestParameters() {
return requestParameters;
}
public void appendToURL(String appendix) {
urlAppenderBuilder.append(appendix);
}
public StringBuilder getUrlAppender() {
return urlAppenderBuilder;
}
}
@@ -1,98 +0,0 @@
/*
* 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,60 @@
/*
*
* * 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.air.pollution;
import com.github.prominence.openweathermap.api.mapper.AirPollutionResponseMapper;
import com.github.prominence.openweathermap.api.model.air.pollution.AirPollutionDetails;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.concurrent.CompletableFuture;
/**
* The type Air pollution async request terminator.
*/
public class AirPollutionAsyncRequestTerminator {
private final RequestSettings requestSettings;
/**
* Instantiates a new Air pollution async request terminator.
*
* @param requestSettings request settings object.
*/
public AirPollutionAsyncRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public CompletableFuture<AirPollutionDetails> asJava() {
return CompletableFuture.supplyAsync(() -> new AirPollutionResponseMapper().mapToAirPollution(getRawResponse()));
}
public CompletableFuture<String> asJSON() {
return CompletableFuture.supplyAsync(this::getRawResponse);
}
private String getRawResponse() {
return RequestUtils.getResponse(requestSettings);
}
}
@@ -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.air.pollution;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* The Air Pollution request customizer.
*/
public class AirPollutionRequestCustomizer {
private final RequestSettings requestSettings;
/**
* Instantiates a new Air pollution request customizer.
*
* @param requestSettings request settings object.
*/
public AirPollutionRequestCustomizer(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public AirPollutionRequestTerminator retrieve() {
return new AirPollutionRequestTerminator(requestSettings);
}
public AirPollutionAsyncRequestTerminator retrieveAsync() {
return new AirPollutionAsyncRequestTerminator(requestSettings);
}
}
@@ -0,0 +1,58 @@
/*
*
* * 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.air.pollution;
import com.github.prominence.openweathermap.api.mapper.AirPollutionResponseMapper;
import com.github.prominence.openweathermap.api.model.air.pollution.AirPollutionDetails;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
/**
* The type Air pollution request terminator.
*/
public class AirPollutionRequestTerminator {
private final RequestSettings requestSettings;
/**
* Instantiates a new Air pollution request terminator.
*
* @param requestSettings request settings object.
*/
public AirPollutionRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public AirPollutionDetails asJava() {
return new AirPollutionResponseMapper().mapToAirPollution(getRawResponse());
}
public String asJSON() {
return getRawResponse();
}
private String getRawResponse() {
return RequestUtils.getResponse(requestSettings);
}
}
@@ -0,0 +1,58 @@
/*
*
* * 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.air.pollution;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* The type Air pollution requester.
*/
public class AirPollutionRequester {
private final RequestSettings requestSettings;
/**
* Instantiates a new Air pollution requester.
*
* @param requestSettings request settings object.
*/
public AirPollutionRequester(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public CurrentAirPollutionRequester current() {
requestSettings.appendToURL("air_pollution");
return new CurrentAirPollutionRequester(requestSettings);
}
public ForecastAirPollutionRequester forecast() {
requestSettings.appendToURL("air_pollution/forecast");
return new ForecastAirPollutionRequester(requestSettings);
}
public HistoricalAirPollutionRequester historical() {
requestSettings.appendToURL("air_pollution/history");
return new HistoricalAirPollutionRequester(requestSettings);
}
}
@@ -0,0 +1,48 @@
/*
* Copyright (c) 2022 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.air.pollution;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* The type Current air pollution requester.
*/
public class CurrentAirPollutionRequester {
private final RequestSettings requestSettings;
/**
* Instantiates a new Current air pollution requester.
*
* @param requestSettings request settings object.
*/
public CurrentAirPollutionRequester(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public AirPollutionRequestCustomizer byCoordinate(Coordinate coordinate) {
requestSettings.putRequestParameter("lat", String.valueOf(coordinate.getLatitude()));
requestSettings.putRequestParameter("lon", String.valueOf(coordinate.getLongitude()));
return new AirPollutionRequestCustomizer(requestSettings);
}
}
@@ -0,0 +1,48 @@
/*
* Copyright (c) 2022 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.air.pollution;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* The type Forecast air pollution requester.
*/
public class ForecastAirPollutionRequester {
private final RequestSettings requestSettings;
/**
* Instantiates a new Forecast air pollution requester.
*
* @param requestSettings request settings object.
*/
public ForecastAirPollutionRequester(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public AirPollutionRequestCustomizer byCoordinate(Coordinate coordinate) {
requestSettings.putRequestParameter("lat", String.valueOf(coordinate.getLatitude()));
requestSettings.putRequestParameter("lon", String.valueOf(coordinate.getLongitude()));
return new AirPollutionRequestCustomizer(requestSettings);
}
}
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2022 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.air.pollution;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* The type Historical air pollution requester.
*/
public class HistoricalAirPollutionRequester {
private final RequestSettings requestSettings;
/**
* Instantiates a new Historical air pollution requester.
*
* @param requestSettings request settings object.
*/
public HistoricalAirPollutionRequester(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public AirPollutionRequestCustomizer byCoordinateAndPeriod(Coordinate coordinate, long startUnixTime, long endUnixTime) {
requestSettings.putRequestParameter("lat", String.valueOf(coordinate.getLatitude()));
requestSettings.putRequestParameter("lon", String.valueOf(coordinate.getLongitude()));
requestSettings.putRequestParameter("start", String.valueOf(startUnixTime));
requestSettings.putRequestParameter("end", String.valueOf(endUnixTime));
return new AirPollutionRequestCustomizer(requestSettings);
}
}
@@ -22,21 +22,43 @@
package com.github.prominence.openweathermap.api.request.forecast.free;
import com.github.prominence.openweathermap.api.enums.ResponseType;
import com.github.prominence.openweathermap.api.mapper.FiveDayThreeHourStepForecastResponseMapper;
import com.github.prominence.openweathermap.api.model.forecast.Forecast;
import com.github.prominence.openweathermap.api.request.AsyncRequestTerminator;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.concurrent.CompletableFuture;
/**
* The forecast async request terminator interface.
* Async request terminator.
*/
public interface FiveDayThreeHourStepForecastAsyncRequestTerminator extends AsyncRequestTerminator<Forecast, String> {
public class FiveDayThreeHourStepForecastAsyncRequestTerminator {
private final RequestSettings requestSettings;
/**
* XML response format.
* Instantiates a new async request terminator.
*
* @return the completable future
* @param requestSettings request settings object.
*/
CompletableFuture<String> asXML();
FiveDayThreeHourStepForecastAsyncRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public CompletableFuture<Forecast> asJava() {
return CompletableFuture.supplyAsync(() -> new FiveDayThreeHourStepForecastResponseMapper(requestSettings.getUnitSystem()).mapToForecast(getRawResponse()));
}
public CompletableFuture<String> asJSON() {
return CompletableFuture.supplyAsync(this::getRawResponse);
}
public CompletableFuture<String> asXML() {
requestSettings.setResponseType(ResponseType.XML);
return CompletableFuture.supplyAsync(this::getRawResponse);
}
private String getRawResponse() {
return RequestUtils.getResponse(requestSettings);
}
}
@@ -22,32 +22,45 @@
package com.github.prominence.openweathermap.api.request.forecast.free;
import com.github.prominence.openweathermap.api.request.RequestCustomizer;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* The forecast request customizer interface.
* The forecast request customizer.
*/
public interface FiveDayThreeHourStepForecastRequestCustomizer extends RequestCustomizer<FiveDayThreeHourStepForecastRequestCustomizer> {
public class FiveDayThreeHourStepForecastRequestCustomizer {
private final RequestSettings requestSettings;
/**
* Count customizer.
* Instantiates a new forecast request customizer.
*
* @param numberOfTimestamps the number of timestamps
* @return forecast request customizer
* @param requestSettings request settings object.
*/
FiveDayThreeHourStepForecastRequestCustomizer count(int numberOfTimestamps);
FiveDayThreeHourStepForecastRequestCustomizer(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
/**
* Retrieve forecast request terminator.
*
* @return forecast request terminator
*/
FiveDayThreeHourStepForecastRequestTerminator retrieve();
public FiveDayThreeHourStepForecastRequestCustomizer language(Language language) {
requestSettings.setLanguage(language);
return this;
}
/**
* Retrieve forecast async request terminator.
*
* @return forecast async request terminator
*/
FiveDayThreeHourStepForecastAsyncRequestTerminator retrieveAsync();
public FiveDayThreeHourStepForecastRequestCustomizer unitSystem(UnitSystem unitSystem) {
requestSettings.setUnitSystem(unitSystem);
return this;
}
public FiveDayThreeHourStepForecastRequestCustomizer count(int numberOfTimestamps) {
requestSettings.putRequestParameter("cnt", Integer.toString(numberOfTimestamps));
return this;
}
public FiveDayThreeHourStepForecastRequestTerminator retrieve() {
return new FiveDayThreeHourStepForecastRequestTerminator(requestSettings);
}
public FiveDayThreeHourStepForecastAsyncRequestTerminator retrieveAsync() {
return new FiveDayThreeHourStepForecastAsyncRequestTerminator(requestSettings);
}
}
@@ -1,80 +0,0 @@
/*
* 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() {
urlBuilder.applyCustomization(language, unitSystem);
urlBuilder.addRequestParameter("cnt", count);
return new FiveDayThreeHourStepForecastRequestTerminatorImpl(urlBuilder, unitSystem);
}
@Override
public FiveDayThreeHourStepForecastAsyncRequestTerminator retrieveAsync() {
urlBuilder.applyCustomization(language, unitSystem);
urlBuilder.addRequestParameter("cnt", count);
return new FiveDayThreeHourStepForecastAsyncRequestTerminatorImpl(urlBuilder, unitSystem);
}
}
@@ -22,19 +22,41 @@
package com.github.prominence.openweathermap.api.request.forecast.free;
import com.github.prominence.openweathermap.api.enums.ResponseType;
import com.github.prominence.openweathermap.api.mapper.FiveDayThreeHourStepForecastResponseMapper;
import com.github.prominence.openweathermap.api.model.forecast.Forecast;
import com.github.prominence.openweathermap.api.request.RequestTerminator;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
/**
* The forecast request terminator interface.
* The forecast request terminator.
*/
public interface FiveDayThreeHourStepForecastRequestTerminator extends RequestTerminator<Forecast, String> {
public class FiveDayThreeHourStepForecastRequestTerminator {
private final RequestSettings requestSettings;
/**
* XML response format.
* Instantiates a new forecast request terminator.
*
* @return the XML string
* @param requestSettings request settings object.
*/
String asXML();
FiveDayThreeHourStepForecastRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public Forecast asJava() {
return new FiveDayThreeHourStepForecastResponseMapper(requestSettings.getUnitSystem()).mapToForecast(getRawResponse());
}
public String asJSON() {
return getRawResponse();
}
public String asXML() {
requestSettings.setResponseType(ResponseType.XML);
return getRawResponse();
}
private String getRawResponse() {
return RequestUtils.getResponse(requestSettings);
}
}
@@ -23,69 +23,57 @@
package com.github.prominence.openweathermap.api.request.forecast.free;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* An interface for <a href="https://openweathermap.org/forecast5">API</a> methods.
* The forecast requester.
*/
public interface FiveDayThreeHourStepForecastRequester {
public class FiveDayThreeHourStepForecastRequester {
private final RequestSettings requestSettings;
/**
* By city name forecast request customizer.
* Instantiates a new forecast requester.
*
* @param cityName the city name
* @return the forecast request customizer
* @param requestSettings request settings object.
*/
FiveDayThreeHourStepForecastRequestCustomizer byCityName(String cityName);
public FiveDayThreeHourStepForecastRequester(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
this.requestSettings.appendToURL("forecast");
}
/**
* 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);
public FiveDayThreeHourStepForecastRequestCustomizer byCityName(String cityName) {
requestSettings.putRequestParameter("q", cityName);
return new FiveDayThreeHourStepForecastRequestCustomizer(requestSettings);
}
/**
* 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);
public FiveDayThreeHourStepForecastRequestCustomizer byCityName(String cityName, String stateCode) {
requestSettings.putRequestParameter("q", cityName + "," + stateCode);
return new FiveDayThreeHourStepForecastRequestCustomizer(requestSettings);
}
/**
* By city id forecast request customizer.
*
* @param cityId the city id
* @return the forecast request customizer
*/
FiveDayThreeHourStepForecastRequestCustomizer byCityId(long cityId);
public FiveDayThreeHourStepForecastRequestCustomizer byCityName(String cityName, String stateCode, String countryCode) {
requestSettings.putRequestParameter("q", cityName + "," + stateCode + "," + countryCode);
return new FiveDayThreeHourStepForecastRequestCustomizer(requestSettings);
}
/**
* By coordinate forecast request customizer.
*
* @param coordinate the coordinate
* @return the forecast request customizer
*/
FiveDayThreeHourStepForecastRequestCustomizer byCoordinate(Coordinate coordinate);
public FiveDayThreeHourStepForecastRequestCustomizer byCityId(long cityId) {
requestSettings.putRequestParameter("id", Long.toString(cityId));
return new FiveDayThreeHourStepForecastRequestCustomizer(requestSettings);
}
/**
* 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);
public FiveDayThreeHourStepForecastRequestCustomizer byCoordinate(Coordinate coordinate) {
requestSettings.putRequestParameter("lat", String.valueOf(coordinate.getLatitude()));
requestSettings.putRequestParameter("lon", String.valueOf(coordinate.getLongitude()));
return new FiveDayThreeHourStepForecastRequestCustomizer(requestSettings);
}
/**
* By zip code in USA forecast request customizer.
*
* @param zipCode the zip code
* @return the forecast request customizer
*/
FiveDayThreeHourStepForecastRequestCustomizer byZipCodeInUSA(String zipCode);
public FiveDayThreeHourStepForecastRequestCustomizer byZipCodeAndCountry(String zipCode, String countryCode) {
requestSettings.putRequestParameter("zip", zipCode + "," + countryCode);
return new FiveDayThreeHourStepForecastRequestCustomizer(requestSettings);
}
public FiveDayThreeHourStepForecastRequestCustomizer byZipCodeInUSA(String zipCode) {
requestSettings.putRequestParameter("zip", zipCode);
return new FiveDayThreeHourStepForecastRequestCustomizer(requestSettings);
}
}
@@ -1,87 +0,0 @@
/*
* 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,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;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.request.onecall.current.OneCallCurrentWeatherRequester;
import com.github.prominence.openweathermap.api.request.onecall.historical.OneCallHistoricalWeatherRequester;
/**
* The type One call weather requester.
*/
public class OneCallWeatherRequester {
private final RequestSettings requestSettings;
/**
* Instantiates a new One call weather requester.
*
* @param requestSettings request settings object.
*/
public OneCallWeatherRequester(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public OneCallCurrentWeatherRequester current() {
return new OneCallCurrentWeatherRequester(requestSettings);
}
public OneCallHistoricalWeatherRequester historical() {
return new OneCallHistoricalWeatherRequester(requestSettings);
}
}
@@ -20,47 +20,39 @@
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.weather.multiple;
package com.github.prominence.openweathermap.api.request.onecall.current;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.request.weather.CurrentWeatherResponseMapper;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.weather.Weather;
import com.github.prominence.openweathermap.api.mapper.OneCallWeatherResponseMapper;
import com.github.prominence.openweathermap.api.model.onecall.current.CurrentWeatherData;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* The type Multiple result current weather async request terminator.
* The type One call current weather async request terminator.
*/
public class MultipleResultCurrentWeatherAsyncRequestTerminatorImpl implements MultipleResultCurrentWeatherAsyncRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
public class OneCallCurrentWeatherAsyncRequestTerminator {
private final RequestSettings requestSettings;
/**
* Instantiates a new Multiple result current weather async request terminator.
* Instantiates a new One call current weather async request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
* @param requestSettings request settings object.
*/
MultipleResultCurrentWeatherAsyncRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
OneCallCurrentWeatherAsyncRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
@Override
public CompletableFuture<List<Weather>> asJava() {
return CompletableFuture.supplyAsync(() -> new CurrentWeatherResponseMapper(unitSystem).getList(getRawResponse()));
public CompletableFuture<CurrentWeatherData> asJava() {
return CompletableFuture.supplyAsync(() -> new OneCallWeatherResponseMapper(requestSettings.getUnitSystem()).mapToCurrent(getRawResponse()));
}
@Override
public CompletableFuture<String> asJSON() {
return CompletableFuture.supplyAsync(this::getRawResponse);
}
private String getRawResponse() {
return RequestUtils.getResponse(urlBuilder.buildUrl());
return RequestUtils.getResponse(requestSettings);
}
}
@@ -0,0 +1,74 @@
/*
* 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.RequestSettings;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* The type One call current weather request customizer.
*/
public class OneCallCurrentWeatherRequestCustomizer {
private final RequestSettings requestSettings;
/**
* Instantiates a new One call current weather request customizer.
*
* @param requestSettings request settings object.
*/
OneCallCurrentWeatherRequestCustomizer(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public OneCallCurrentWeatherRequestCustomizer language(Language language) {
requestSettings.setLanguage(language);
return this;
}
public OneCallCurrentWeatherRequestCustomizer unitSystem(UnitSystem unitSystem) {
this.requestSettings.setUnitSystem(unitSystem);
return this;
}
public OneCallCurrentWeatherRequestCustomizer exclude(OneCallResultOptions... excludeOptions) {
if (excludeOptions != null && excludeOptions.length > 0) {
requestSettings.putRequestParameter("exclude", Stream.of(excludeOptions).map(OneCallResultOptions::getValue).collect(Collectors.joining(",")));
} else {
requestSettings.removeRequestParameter("exclude");
}
return this;
}
public OneCallCurrentWeatherRequestTerminator retrieve() {
return new OneCallCurrentWeatherRequestTerminator(requestSettings);
}
public OneCallCurrentWeatherAsyncRequestTerminator retrieveAsync() {
return new OneCallCurrentWeatherAsyncRequestTerminator(requestSettings);
}
}
@@ -20,49 +20,37 @@
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.forecast.free;
package com.github.prominence.openweathermap.api.request.onecall.current;
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.mapper.OneCallWeatherResponseMapper;
import com.github.prominence.openweathermap.api.model.onecall.current.CurrentWeatherData;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
/**
* The forecast request terminator.
* The type One call current weather request terminator.
*/
public class FiveDayThreeHourStepForecastRequestTerminatorImpl implements FiveDayThreeHourStepForecastRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
public class OneCallCurrentWeatherRequestTerminator {
private final RequestSettings requestSettings;
/**
* Instantiates a new forecast request terminator.
* Instantiates a new One call current weather request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
* @param requestSettings request settings object.
*/
FiveDayThreeHourStepForecastRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
OneCallCurrentWeatherRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
@Override
public Forecast asJava() {
return new FiveDayThreeHourStepForecastResponseMapper(unitSystem).mapToForecast(getRawResponse());
public CurrentWeatherData asJava() {
return new OneCallWeatherResponseMapper(requestSettings.getUnitSystem()).mapToCurrent(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());
return RequestUtils.getResponse(requestSettings);
}
}
@@ -0,0 +1,49 @@
/*
* 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;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* The type One call current weather requester.
*/
public class OneCallCurrentWeatherRequester {
private final RequestSettings requestSettings;
/**
* Instantiates a new One call current weather requester.
*
* @param requestSettings request settings object.
*/
public OneCallCurrentWeatherRequester(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
this.requestSettings.appendToURL("onecall");
}
public OneCallCurrentWeatherRequestCustomizer byCoordinate(Coordinate coordinate) {
requestSettings.putRequestParameter("lat", String.valueOf(coordinate.getLatitude()));
requestSettings.putRequestParameter("lon", String.valueOf(coordinate.getLongitude()));
return new OneCallCurrentWeatherRequestCustomizer(requestSettings);
}
}
@@ -20,51 +20,39 @@
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.forecast.free;
package com.github.prominence.openweathermap.api.request.onecall.historical;
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.mapper.OneCallWeatherResponseMapper;
import com.github.prominence.openweathermap.api.model.onecall.historical.HistoricalWeatherData;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.concurrent.CompletableFuture;
/**
* Async request terminator.
* The type One call historical weather async request terminator.
*/
public class FiveDayThreeHourStepForecastAsyncRequestTerminatorImpl implements FiveDayThreeHourStepForecastAsyncRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
public class OneCallHistoricalWeatherAsyncRequestTerminator {
private final RequestSettings requestSettings;
/**
* Instantiates a new async request terminator.
* Instantiates a new One call historical weather async request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
* @param requestSettings request settings object.
*/
FiveDayThreeHourStepForecastAsyncRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
public OneCallHistoricalWeatherAsyncRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
@Override
public CompletableFuture<Forecast> asJava() {
return CompletableFuture.supplyAsync(() -> new FiveDayThreeHourStepForecastResponseMapper(unitSystem).mapToForecast(getRawResponse()));
public CompletableFuture<HistoricalWeatherData> asJava() {
return CompletableFuture.supplyAsync(() -> new OneCallWeatherResponseMapper(requestSettings.getUnitSystem()).mapToHistorical(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());
return RequestUtils.getResponse(requestSettings);
}
}
@@ -0,0 +1,61 @@
/*
* 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.RequestSettings;
/**
* The type One call historical weather request customizer.
*/
public class OneCallHistoricalWeatherRequestCustomizer {
private final RequestSettings requestSettings;
/**
* Instantiates a new One call historical weather request customizer.
*
* @param requestSettings request settings object.
*/
public OneCallHistoricalWeatherRequestCustomizer(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public OneCallHistoricalWeatherRequestCustomizer language(Language language) {
requestSettings.setLanguage(language);
return this;
}
public OneCallHistoricalWeatherRequestCustomizer unitSystem(UnitSystem unitSystem) {
requestSettings.setUnitSystem(unitSystem);
return this;
}
public OneCallHistoricalWeatherRequestTerminator retrieve() {
return new OneCallHistoricalWeatherRequestTerminator(requestSettings);
}
public OneCallHistoricalWeatherAsyncRequestTerminator retrieveAsync() {
return new OneCallHistoricalWeatherAsyncRequestTerminator(requestSettings);
}
}
@@ -20,46 +20,37 @@
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.weather.multiple;
package com.github.prominence.openweathermap.api.request.onecall.historical;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.request.weather.CurrentWeatherResponseMapper;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.weather.Weather;
import com.github.prominence.openweathermap.api.mapper.OneCallWeatherResponseMapper;
import com.github.prominence.openweathermap.api.model.onecall.historical.HistoricalWeatherData;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.List;
/**
* The type Multiple result current weather request terminator.
* The type One call historical weather request terminator.
*/
public class MultipleResultCurrentWeatherRequestTerminatorImpl implements MultipleResultCurrentWeatherRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
public class OneCallHistoricalWeatherRequestTerminator {
private final RequestSettings requestSettings;
/**
* Instantiates a new Multiple result current weather request terminator.
* Instantiates a new One call historical weather request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
* @param requestSettings request settings object.
*/
MultipleResultCurrentWeatherRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
public OneCallHistoricalWeatherRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
@Override
public List<Weather> asJava() {
return new CurrentWeatherResponseMapper(unitSystem).getList(getRawResponse());
public HistoricalWeatherData asJava() {
return new OneCallWeatherResponseMapper(requestSettings.getUnitSystem()).mapToHistorical(getRawResponse());
}
@Override
public String asJSON() {
return getRawResponse();
}
private String getRawResponse() {
return RequestUtils.getResponse(urlBuilder.buildUrl());
return RequestUtils.getResponse(requestSettings);
}
}
@@ -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.onecall.historical;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* The type One call historical weather requester.
*/
public class OneCallHistoricalWeatherRequester {
private final RequestSettings requestSettings;
/**
* Instantiates a new One call historical weather requester.
*
* @param requestSettings request settings object.
*/
public OneCallHistoricalWeatherRequester(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
this.requestSettings.appendToURL("onecall/timemachine");
}
public OneCallHistoricalWeatherRequestCustomizer byCoordinateAndTimestamp(Coordinate coordinate, long unixTime) {
requestSettings.putRequestParameter("lat", Double.toString(coordinate.getLatitude()));
requestSettings.putRequestParameter("lon", Double.toString(coordinate.getLongitude()));
requestSettings.putRequestParameter("dt", Long.toString(unixTime));
return new OneCallHistoricalWeatherRequestCustomizer(requestSettings);
}
}
@@ -22,25 +22,30 @@
package com.github.prominence.openweathermap.api.request.weather;
import com.github.prominence.openweathermap.api.request.RequestSettings;
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.
* The type Current weather requester.
*/
public interface CurrentWeatherRequester {
public class CurrentWeatherRequester {
private final RequestSettings requestSettings;
/**
* Single location current weather requester.
* Instantiates a new Current weather requester.
*
* @return the single location current weather requester
* @param requestSettings request settings object.
*/
SingleLocationCurrentWeatherRequester single();
public CurrentWeatherRequester(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
/**
* Multiple locations current weather requester.
*
* @return the multiple locations current weather requester
*/
MultipleLocationsCurrentWeatherRequester multiple();
public SingleLocationCurrentWeatherRequester single() {
return new SingleLocationCurrentWeatherRequester(requestSettings);
}
public MultipleLocationsCurrentWeatherRequester multiple() {
return new MultipleLocationsCurrentWeatherRequester(requestSettings);
}
}
@@ -1,54 +0,0 @@
/*
* 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.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.request.weather.multiple.MultipleLocationsCurrentWeatherRequesterImpl;
import com.github.prominence.openweathermap.api.request.weather.multiple.MultipleLocationsCurrentWeatherRequester;
import com.github.prominence.openweathermap.api.request.weather.single.SingleLocationCurrentWeatherRequesterImpl;
import com.github.prominence.openweathermap.api.request.weather.single.SingleLocationCurrentWeatherRequester;
/**
* The type Current weather requester.
*/
public class CurrentWeatherRequesterImpl implements CurrentWeatherRequester {
private final RequestUrlBuilder urlBuilder;
/**
* Instantiates a new Current weather requester.
*
* @param apiKey the api key
*/
public CurrentWeatherRequesterImpl(String apiKey) {
urlBuilder = new RequestUrlBuilder(apiKey);
}
public SingleLocationCurrentWeatherRequester single() {
return new SingleLocationCurrentWeatherRequesterImpl(urlBuilder);
}
public MultipleLocationsCurrentWeatherRequester multiple() {
return new MultipleLocationsCurrentWeatherRequesterImpl(urlBuilder);
}
}
@@ -24,36 +24,45 @@ package com.github.prominence.openweathermap.api.request.weather.multiple;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.model.CoordinateRectangle;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* The interface Multiple locations current weather requester.
* The type Multiple locations current weather requester.
*/
public interface MultipleLocationsCurrentWeatherRequester {
public class MultipleLocationsCurrentWeatherRequester {
private final RequestSettings requestSettings;
/**
* By rectangle multiple result current weather request customizer.
* Instantiates a new Multiple locations current weather requester.
*
* @param rectangle the rectangle
* @param zoom the zoom
* @return the multiple result current weather request customizer
* @param requestSettings request settings object.
*/
MultipleResultCurrentWeatherRequestCustomizer byRectangle(CoordinateRectangle rectangle, int zoom);
public MultipleLocationsCurrentWeatherRequester(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
/**
* By cities in cycle multiple result current weather request customizer.
*
* @param point the point
* @return the multiple result cities in circle current weather request customizer
*/
MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer byCitiesInCycle(Coordinate point);
public MultipleResultCurrentWeatherRequestCustomizer byRectangle(CoordinateRectangle rectangle, int zoom) {
String coordinates = rectangle.getFormattedRequestString() + "," + zoom;
requestSettings.appendToURL("box/city");
requestSettings.putRequestParameter("bbox", coordinates);
/**
* By cities in cycle multiple result current weather request customizer.
*
* @param point the point
* @param citiesCount the cities count
* @return the multiple result cities in circle current weather request customizer
*/
MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer byCitiesInCycle(Coordinate point, int citiesCount);
return new MultipleResultCurrentWeatherRequestCustomizer(requestSettings);
}
public MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer byCitiesInCycle(Coordinate point, int citiesCount) {
requestSettings.appendToURL("find");
requestSettings.putRequestParameter("lat", Double.toString(point.getLatitude()));
requestSettings.putRequestParameter("lon", Double.toString(point.getLongitude()));
requestSettings.putRequestParameter("cnt", Integer.toString(citiesCount));
return new MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer(requestSettings);
}
public MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer byCitiesInCycle(Coordinate point) {
requestSettings.appendToURL("find");
requestSettings.putRequestParameter("lat", Double.toString(point.getLatitude()));
requestSettings.putRequestParameter("lon", Double.toString(point.getLongitude()));
return new MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer(requestSettings);
}
}
@@ -1,72 +0,0 @@
/*
* 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.multiple;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.model.CoordinateRectangle;
/**
* The type Multiple locations current weather requester.
*/
public class MultipleLocationsCurrentWeatherRequesterImpl implements MultipleLocationsCurrentWeatherRequester {
private final RequestUrlBuilder urlBuilder;
/**
* Instantiates a new Multiple locations current weather requester.
*
* @param urlBuilder the url builder
*/
public MultipleLocationsCurrentWeatherRequesterImpl(RequestUrlBuilder urlBuilder) {
this.urlBuilder = urlBuilder;
}
@Override
public MultipleResultCurrentWeatherRequestCustomizer byRectangle(CoordinateRectangle rectangle, int zoom) {
String coordinates = rectangle.getFormattedRequestString() + "," + zoom;
urlBuilder.append("box/city");
urlBuilder.addRequestParameter("bbox", coordinates);
return new MultipleResultCurrentWeatherRequestCustomizerImpl(urlBuilder);
}
@Override
public MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer byCitiesInCycle(Coordinate point, int citiesCount) {
urlBuilder.append("find");
urlBuilder.addRequestParameter("lat", Double.toString(point.getLatitude()));
urlBuilder.addRequestParameter("lon", Double.toString(point.getLongitude()));
urlBuilder.addRequestParameter("cnt", Integer.toString(citiesCount));
return new MultipleResultCitiesInCircleCurrentWeatherRequestCustomizerImpl(urlBuilder);
}
@Override
public MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer byCitiesInCycle(Coordinate point) {
urlBuilder.append("find");
urlBuilder.addRequestParameter("lat", Double.toString(point.getLatitude()));
urlBuilder.addRequestParameter("lon", Double.toString(point.getLongitude()));
return new MultipleResultCitiesInCircleCurrentWeatherRequestCustomizerImpl(urlBuilder);
}
}
@@ -22,20 +22,44 @@
package com.github.prominence.openweathermap.api.request.weather.multiple;
import com.github.prominence.openweathermap.api.enums.ResponseType;
import com.github.prominence.openweathermap.api.model.weather.Weather;
import com.github.prominence.openweathermap.api.request.AsyncRequestTerminator;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.mapper.CurrentWeatherResponseMapper;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* The interface Multiple result current weather async request terminator.
* The type Multiple result current weather async request terminator.
*/
public interface MultipleResultCitiesInCircleCurrentWeatherAsyncRequestTerminator extends AsyncRequestTerminator<List<Weather>, String> {
public class MultipleResultCitiesInCircleCurrentWeatherAsyncRequestTerminator {
private final RequestSettings requestSettings;
/**
* XML response format.
* Instantiates a new Multiple result current weather async request terminator.
*
* @return the completable future
* @param requestSettings request settings object.
*/
CompletableFuture<String> asXML();
MultipleResultCitiesInCircleCurrentWeatherAsyncRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public CompletableFuture<List<Weather>> asJava() {
return CompletableFuture.supplyAsync(() -> new CurrentWeatherResponseMapper(requestSettings.getUnitSystem()).getList(getRawResponse()));
}
public CompletableFuture<String> asJSON() {
return CompletableFuture.supplyAsync(this::getRawResponse);
}
public CompletableFuture<String> asXML() {
requestSettings.setResponseType(ResponseType.XML);
return CompletableFuture.supplyAsync(this::getRawResponse);
}
private String getRawResponse() {
return RequestUtils.getResponse(requestSettings);
}
}
@@ -1,72 +0,0 @@
/*
* 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.multiple;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.weather.Weather;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.request.weather.CurrentWeatherResponseMapper;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* The type Multiple result current weather async request terminator.
*/
public class MultipleResultCitiesInCircleCurrentWeatherAsyncRequestTerminatorImpl implements MultipleResultCitiesInCircleCurrentWeatherAsyncRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
/**
* Instantiates a new Multiple result current weather async request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
*/
MultipleResultCitiesInCircleCurrentWeatherAsyncRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
}
@Override
public CompletableFuture<List<Weather>> asJava() {
return CompletableFuture.supplyAsync(() -> new CurrentWeatherResponseMapper(unitSystem).getList(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());
}
}
@@ -22,24 +22,40 @@
package com.github.prominence.openweathermap.api.request.weather.multiple;
import com.github.prominence.openweathermap.api.request.RequestCustomizer;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* The interface Multiple result current weather request customizer.
* The type Multiple result current weather request customizer.
*/
public interface MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer extends RequestCustomizer<MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer> {
public class MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer {
private final RequestSettings requestSettings;
/**
* Retrieve multiple result current weather request terminator.
* Instantiates a new Multiple result current weather request customizer.
*
* @return the multiple result current weather request terminator
* @param requestSettings request settings object.
*/
MultipleResultCitiesInCircleCurrentWeatherRequestTerminator retrieve();
MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
/**
* Retrieve async multiple result current weather async request terminator.
*
* @return the multiple result current weather async request terminator
*/
MultipleResultCitiesInCircleCurrentWeatherAsyncRequestTerminator retrieveAsync();
public MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer language(Language language) {
requestSettings.setLanguage(language);
return this;
}
public MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer unitSystem(UnitSystem unitSystem) {
requestSettings.setUnitSystem(unitSystem);
return this;
}
public MultipleResultCitiesInCircleCurrentWeatherRequestTerminator retrieve() {
return new MultipleResultCitiesInCircleCurrentWeatherRequestTerminator(requestSettings);
}
public MultipleResultCitiesInCircleCurrentWeatherAsyncRequestTerminator retrieveAsync() {
return new MultipleResultCitiesInCircleCurrentWeatherAsyncRequestTerminator(requestSettings);
}
}
@@ -1,71 +0,0 @@
/*
* 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.multiple;
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 Multiple result current weather request customizer.
*/
public class MultipleResultCitiesInCircleCurrentWeatherRequestCustomizerImpl implements MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer {
private final RequestUrlBuilder urlBuilder;
private Language language;
private UnitSystem unitSystem = UnitSystem.STANDARD;
/**
* Instantiates a new Multiple result current weather request customizer.
*
* @param urlBuilder the url builder
*/
MultipleResultCitiesInCircleCurrentWeatherRequestCustomizerImpl(RequestUrlBuilder urlBuilder) {
this.urlBuilder = urlBuilder;
}
@Override
public MultipleResultCitiesInCircleCurrentWeatherRequestTerminator retrieve() {
urlBuilder.applyCustomization(language, unitSystem);
return new MultipleResultCitiesInCircleCurrentWeatherRequestTerminatorImpl(urlBuilder, unitSystem);
}
@Override
public MultipleResultCitiesInCircleCurrentWeatherAsyncRequestTerminator retrieveAsync() {
urlBuilder.applyCustomization(language, unitSystem);
return new MultipleResultCitiesInCircleCurrentWeatherAsyncRequestTerminatorImpl(urlBuilder, unitSystem);
}
@Override
public MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer language(Language language) {
this.language = language;
return this;
}
@Override
public MultipleResultCitiesInCircleCurrentWeatherRequestCustomizer unitSystem(UnitSystem unitSystem) {
this.unitSystem = unitSystem;
return this;
}
}
@@ -22,19 +22,43 @@
package com.github.prominence.openweathermap.api.request.weather.multiple;
import com.github.prominence.openweathermap.api.enums.ResponseType;
import com.github.prominence.openweathermap.api.model.weather.Weather;
import com.github.prominence.openweathermap.api.request.RequestTerminator;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.mapper.CurrentWeatherResponseMapper;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.List;
/**
* The interface Multiple result current weather request terminator.
* The type Multiple result current weather request terminator.
*/
public interface MultipleResultCitiesInCircleCurrentWeatherRequestTerminator extends RequestTerminator<List<Weather>, String> {
public class MultipleResultCitiesInCircleCurrentWeatherRequestTerminator {
private final RequestSettings requestSettings;
/**
* XML response format.
* Instantiates a new Multiple result current weather request terminator.
*
* @return the XML string
* @param requestSettings request settings object.
*/
String asXML();
MultipleResultCitiesInCircleCurrentWeatherRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public List<Weather> asJava() {
return new CurrentWeatherResponseMapper(requestSettings.getUnitSystem()).getList(getRawResponse());
}
public String asJSON() {
return getRawResponse();
}
public String asXML() {
requestSettings.setResponseType(ResponseType.XML);
return getRawResponse();
}
private String getRawResponse() {
return RequestUtils.getResponse(requestSettings);
}
}
@@ -1,71 +0,0 @@
/*
* 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.multiple;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.weather.Weather;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.request.weather.CurrentWeatherResponseMapper;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.List;
/**
* The type Multiple result current weather request terminator.
*/
public class MultipleResultCitiesInCircleCurrentWeatherRequestTerminatorImpl implements MultipleResultCitiesInCircleCurrentWeatherRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
/**
* Instantiates a new Multiple result current weather request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
*/
MultipleResultCitiesInCircleCurrentWeatherRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
}
@Override
public List<Weather> asJava() {
return new CurrentWeatherResponseMapper(unitSystem).getList(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());
}
}
@@ -23,12 +23,37 @@
package com.github.prominence.openweathermap.api.request.weather.multiple;
import com.github.prominence.openweathermap.api.model.weather.Weather;
import com.github.prominence.openweathermap.api.request.AsyncRequestTerminator;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.mapper.CurrentWeatherResponseMapper;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* The interface Multiple result current weather async request terminator.
* The type Multiple result current weather async request terminator.
*/
public interface MultipleResultCurrentWeatherAsyncRequestTerminator extends AsyncRequestTerminator<List<Weather>, String> {
public class MultipleResultCurrentWeatherAsyncRequestTerminator {
private final RequestSettings requestSettings;
/**
* Instantiates a new Multiple result current weather async request terminator.
*
* @param requestSettings request settings object.
*/
MultipleResultCurrentWeatherAsyncRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public CompletableFuture<List<Weather>> asJava() {
return CompletableFuture.supplyAsync(() -> new CurrentWeatherResponseMapper(requestSettings.getUnitSystem()).getList(getRawResponse()));
}
public CompletableFuture<String> asJSON() {
return CompletableFuture.supplyAsync(this::getRawResponse);
}
private String getRawResponse() {
return RequestUtils.getResponse(requestSettings);
}
}
@@ -22,24 +22,40 @@
package com.github.prominence.openweathermap.api.request.weather.multiple;
import com.github.prominence.openweathermap.api.request.RequestCustomizer;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* The interface Multiple result current weather request customizer.
* The type Multiple result current weather request customizer.
*/
public interface MultipleResultCurrentWeatherRequestCustomizer extends RequestCustomizer<MultipleResultCurrentWeatherRequestCustomizer> {
public class MultipleResultCurrentWeatherRequestCustomizer {
private final RequestSettings requestSettings;
/**
* Retrieve multiple result current weather request terminator.
* Instantiates a new Multiple result current weather request customizer.
*
* @return the multiple result current weather request terminator
* @param requestSettings request settings object.
*/
MultipleResultCurrentWeatherRequestTerminator retrieve();
MultipleResultCurrentWeatherRequestCustomizer(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
/**
* Retrieve async multiple result current weather async request terminator.
*
* @return the multiple result current weather async request terminator
*/
MultipleResultCurrentWeatherAsyncRequestTerminator retrieveAsync();
public MultipleResultCurrentWeatherRequestCustomizer language(Language language) {
requestSettings.setLanguage(language);
return this;
}
public MultipleResultCurrentWeatherRequestCustomizer unitSystem(UnitSystem unitSystem) {
requestSettings.setUnitSystem(unitSystem);
return this;
}
public MultipleResultCurrentWeatherRequestTerminator retrieve() {
return new MultipleResultCurrentWeatherRequestTerminator(requestSettings);
}
public MultipleResultCurrentWeatherAsyncRequestTerminator retrieveAsync() {
return new MultipleResultCurrentWeatherAsyncRequestTerminator(requestSettings);
}
}
@@ -1,71 +0,0 @@
/*
* 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.multiple;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
/**
* The type Multiple result current weather request customizer.
*/
public class MultipleResultCurrentWeatherRequestCustomizerImpl implements MultipleResultCurrentWeatherRequestCustomizer {
private final RequestUrlBuilder urlBuilder;
private Language language;
private UnitSystem unitSystem = UnitSystem.STANDARD;
/**
* Instantiates a new Multiple result current weather request customizer.
*
* @param urlBuilder the url builder
*/
MultipleResultCurrentWeatherRequestCustomizerImpl(RequestUrlBuilder urlBuilder) {
this.urlBuilder = urlBuilder;
}
@Override
public MultipleResultCurrentWeatherRequestTerminator retrieve() {
urlBuilder.applyCustomization(language, unitSystem);
return new MultipleResultCurrentWeatherRequestTerminatorImpl(urlBuilder, unitSystem);
}
@Override
public MultipleResultCurrentWeatherAsyncRequestTerminator retrieveAsync() {
urlBuilder.applyCustomization(language, unitSystem);
return new MultipleResultCurrentWeatherAsyncRequestTerminatorImpl(urlBuilder, unitSystem);
}
@Override
public MultipleResultCurrentWeatherRequestCustomizer language(Language language) {
this.language = language;
return this;
}
@Override
public MultipleResultCurrentWeatherRequestCustomizer unitSystem(UnitSystem unitSystem) {
this.unitSystem = unitSystem;
return this;
}
}
@@ -23,12 +23,36 @@
package com.github.prominence.openweathermap.api.request.weather.multiple;
import com.github.prominence.openweathermap.api.model.weather.Weather;
import com.github.prominence.openweathermap.api.request.RequestTerminator;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.mapper.CurrentWeatherResponseMapper;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.List;
/**
* The interface Multiple result current weather request terminator.
* The type Multiple result current weather request terminator.
*/
public interface MultipleResultCurrentWeatherRequestTerminator extends RequestTerminator<List<Weather>, String> {
public class MultipleResultCurrentWeatherRequestTerminator {
private final RequestSettings requestSettings;
/**
* Instantiates a new Multiple result current weather request terminator.
*
* @param requestSettings request settings object.
*/
MultipleResultCurrentWeatherRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public List<Weather> asJava() {
return new CurrentWeatherResponseMapper(requestSettings.getUnitSystem()).getList(getRawResponse());
}
public String asJSON() {
return getRawResponse();
}
private String getRawResponse() {
return RequestUtils.getResponse(requestSettings);
}
}
@@ -23,69 +23,57 @@
package com.github.prominence.openweathermap.api.request.weather.single;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* The interface Single location current weather requester.
* The type Single location current weather requester.
*/
public interface SingleLocationCurrentWeatherRequester {
public class SingleLocationCurrentWeatherRequester {
private final RequestSettings requestSettings;
/**
* By city name current weather request customizer.
* Instantiates a new Single location current weather requester.
*
* @param cityName the city name
* @return the single result current weather request customizer
* @param requestSettings request settings object.
*/
SingleResultCurrentWeatherRequestCustomizer byCityName(String cityName);
public SingleLocationCurrentWeatherRequester(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
this.requestSettings.appendToURL("weather");
}
/**
* By city name current weather request customizer.
*
* @param cityName the city name
* @param countryCode the country code
* @return the single result current weather request customizer
*/
SingleResultCurrentWeatherRequestCustomizer byCityName(String cityName, String countryCode);
public SingleResultCurrentWeatherRequestCustomizer byCityName(String cityName) {
requestSettings.putRequestParameter("q", cityName);
return new SingleResultCurrentWeatherRequestCustomizer(requestSettings);
}
/**
* By city name current weather request customizer.
*
* @param cityName the city name
* @param stateCode the state code
* @param countryCode the country code
* @return the single result current weather request customizer
*/
SingleResultCurrentWeatherRequestCustomizer byCityName(String cityName, String stateCode, String countryCode);
public SingleResultCurrentWeatherRequestCustomizer byCityName(String cityName, String countryCode) {
requestSettings.putRequestParameter("q", cityName + "," + countryCode);
return new SingleResultCurrentWeatherRequestCustomizer(requestSettings);
}
/**
* By city id current weather request customizer.
*
* @param cityId the city id
* @return the single result current weather request customizer
*/
SingleResultCurrentWeatherRequestCustomizer byCityId(long cityId);
public SingleResultCurrentWeatherRequestCustomizer byCityName(String cityName, String stateCode, String countryCode) {
requestSettings.putRequestParameter("q", cityName + "," + stateCode + "," + countryCode);
return new SingleResultCurrentWeatherRequestCustomizer(requestSettings);
}
/**
* By coordinate current weather request customizer.
*
* @param coordinate the coordinate
* @return the single result current weather request customizer
*/
SingleResultCurrentWeatherRequestCustomizer byCoordinate(Coordinate coordinate);
public SingleResultCurrentWeatherRequestCustomizer byCityId(long cityId) {
requestSettings.putRequestParameter("id", String.valueOf(cityId));
return new SingleResultCurrentWeatherRequestCustomizer(requestSettings);
}
/**
* By zip code and country current weather request customizer.
*
* @param zipCode the zip code
* @param countryCode the country code
* @return the single result current weather request customizer
*/
SingleResultCurrentWeatherRequestCustomizer byZipCodeAndCountry(String zipCode, String countryCode);
public SingleResultCurrentWeatherRequestCustomizer byCoordinate(Coordinate coordinate) {
requestSettings.putRequestParameter("lat", String.valueOf(coordinate.getLatitude()));
requestSettings.putRequestParameter("lon", String.valueOf(coordinate.getLongitude()));
return new SingleResultCurrentWeatherRequestCustomizer(requestSettings);
}
/**
* By zip code in usa current weather request customizer.
*
* @param zipCode the zip code
* @return the single result current weather request customizer
*/
SingleResultCurrentWeatherRequestCustomizer byZipCodeInUSA(String zipCode);
public SingleResultCurrentWeatherRequestCustomizer byZipCodeAndCountry(String zipCode, String countryCode) {
requestSettings.putRequestParameter("zip", zipCode + "," + countryCode);
return new SingleResultCurrentWeatherRequestCustomizer(requestSettings);
}
public SingleResultCurrentWeatherRequestCustomizer byZipCodeInUSA(String zipCode) {
requestSettings.putRequestParameter("zip", zipCode);
return new SingleResultCurrentWeatherRequestCustomizer(requestSettings);
}
}
@@ -1,82 +0,0 @@
/*
* 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.single;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.model.Coordinate;
/**
* The type Single location current weather requester.
*/
public class SingleLocationCurrentWeatherRequesterImpl implements SingleLocationCurrentWeatherRequester {
private final RequestUrlBuilder urlBuilder;
/**
* Instantiates a new Single location current weather requester.
*
* @param urlBuilder the url builder
*/
public SingleLocationCurrentWeatherRequesterImpl(RequestUrlBuilder urlBuilder) {
this.urlBuilder = urlBuilder;
urlBuilder.append("weather");
}
public SingleResultCurrentWeatherRequestCustomizer byCityName(String cityName) {
urlBuilder.addRequestParameter("q", cityName);
return new SingleResultCurrentWeatherRequestCustomizerImpl(urlBuilder);
}
public SingleResultCurrentWeatherRequestCustomizer byCityName(String cityName, String countryCode) {
urlBuilder.addRequestParameter("q", cityName + "," + countryCode);
return new SingleResultCurrentWeatherRequestCustomizerImpl(urlBuilder);
}
@Override
public SingleResultCurrentWeatherRequestCustomizer byCityName(String cityName, String stateCode, String countryCode) {
urlBuilder.addRequestParameter("q", cityName + "," + stateCode + "," + countryCode);
return new SingleResultCurrentWeatherRequestCustomizerImpl(urlBuilder);
}
public SingleResultCurrentWeatherRequestCustomizer byCityId(long cityId) {
urlBuilder.addRequestParameter("id", cityId);
return new SingleResultCurrentWeatherRequestCustomizerImpl(urlBuilder);
}
public SingleResultCurrentWeatherRequestCustomizer byCoordinate(Coordinate coordinate) {
urlBuilder.addRequestParameter("lat", String.valueOf(coordinate.getLatitude()));
urlBuilder.addRequestParameter("lon", String.valueOf(coordinate.getLongitude()));
return new SingleResultCurrentWeatherRequestCustomizerImpl(urlBuilder);
}
public SingleResultCurrentWeatherRequestCustomizer byZipCodeAndCountry(String zipCode, String countryCode) {
urlBuilder.addRequestParameter("zip", zipCode + "," + countryCode);
return new SingleResultCurrentWeatherRequestCustomizerImpl(urlBuilder);
}
@Override
public SingleResultCurrentWeatherRequestCustomizer byZipCodeInUSA(String zipCode) {
urlBuilder.addRequestParameter("zip", zipCode);
return new SingleResultCurrentWeatherRequestCustomizerImpl(urlBuilder);
}
}
@@ -22,26 +22,48 @@
package com.github.prominence.openweathermap.api.request.weather.single;
import com.github.prominence.openweathermap.api.enums.ResponseType;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.mapper.CurrentWeatherResponseMapper;
import com.github.prominence.openweathermap.api.model.weather.Weather;
import com.github.prominence.openweathermap.api.request.AsyncRequestTerminator;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.concurrent.CompletableFuture;
/**
* The current weather async request terminator interface.
* The type Single result current weather async request terminator.
*/
public interface SingleResultCurrentWeatherAsyncRequestTerminator extends AsyncRequestTerminator<Weather, String> {
/**
* XML response format.
*
* @return the completable future
*/
CompletableFuture<String> asXML();
public class SingleResultCurrentWeatherAsyncRequestTerminator {
private final RequestSettings requestSettings;
/**
* HTML response format.
* Instantiates a new Single result current weather async request terminator.
*
* @return the completable future
* @param requestSettings request settings object.
*/
CompletableFuture<String> asHTML();
SingleResultCurrentWeatherAsyncRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public CompletableFuture<Weather> asJava() {
return CompletableFuture.supplyAsync(() -> new CurrentWeatherResponseMapper(requestSettings.getUnitSystem()).getSingle(getRawResponse()));
}
public CompletableFuture<String> asJSON() {
return CompletableFuture.supplyAsync(this::getRawResponse);
}
public CompletableFuture<String> asXML() {
requestSettings.setResponseType(ResponseType.XML);
return CompletableFuture.supplyAsync(this::getRawResponse);
}
public CompletableFuture<String> asHTML() {
requestSettings.setResponseType(ResponseType.HTML);
return CompletableFuture.supplyAsync(this::getRawResponse);
}
private String getRawResponse() {
return RequestUtils.getResponse(requestSettings);
}
}
@@ -1,77 +0,0 @@
/*
* 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.single;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.request.weather.CurrentWeatherResponseMapper;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.weather.Weather;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.concurrent.CompletableFuture;
/**
* The type Single result current weather async request terminator.
*/
public class SingleResultCurrentWeatherAsyncRequestTerminatorImpl implements SingleResultCurrentWeatherAsyncRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
/**
* Instantiates a new Single result current weather async request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
*/
SingleResultCurrentWeatherAsyncRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
}
@Override
public CompletableFuture<Weather> asJava() {
return CompletableFuture.supplyAsync(() -> new CurrentWeatherResponseMapper(unitSystem).getSingle(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);
}
@Override
public CompletableFuture<String> asHTML() {
urlBuilder.addRequestParameter("mode", "html");
return CompletableFuture.supplyAsync(this::getRawResponse);
}
private String getRawResponse() {
return RequestUtils.getResponse(urlBuilder.buildUrl());
}
}
@@ -22,25 +22,40 @@
package com.github.prominence.openweathermap.api.request.weather.single;
import com.github.prominence.openweathermap.api.request.RequestCustomizer;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.request.RequestSettings;
/**
* The current weather request customizer interface.
* The type Single result current weather request customizer.
*/
public interface SingleResultCurrentWeatherRequestCustomizer extends RequestCustomizer<SingleResultCurrentWeatherRequestCustomizer> {
public class SingleResultCurrentWeatherRequestCustomizer {
private final RequestSettings requestSettings;
/**
* Retrieve current weather request terminator.
* Instantiates a new Single result current weather request customizer.
*
* @return the single result current weather request terminator
* @param requestSettings request settings object.
*/
SingleResultCurrentWeatherRequestTerminator retrieve();
SingleResultCurrentWeatherRequestCustomizer(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
/**
* Retrieve current weather async request terminator.
*
* @return the single result current weather async request terminator
*/
SingleResultCurrentWeatherAsyncRequestTerminator retrieveAsync();
public SingleResultCurrentWeatherRequestCustomizer language(Language language) {
requestSettings.setLanguage(language);
return this;
}
public SingleResultCurrentWeatherRequestCustomizer unitSystem(UnitSystem unitSystem) {
requestSettings.setUnitSystem(unitSystem);
return this;
}
public SingleResultCurrentWeatherRequestTerminator retrieve() {
return new SingleResultCurrentWeatherRequestTerminator(requestSettings);
}
public SingleResultCurrentWeatherAsyncRequestTerminator retrieveAsync() {
return new SingleResultCurrentWeatherAsyncRequestTerminator(requestSettings);
}
}
@@ -1,71 +0,0 @@
/*
* 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.single;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
/**
* The type Single result current weather request customizer.
*/
public class SingleResultCurrentWeatherRequestCustomizerImpl implements SingleResultCurrentWeatherRequestCustomizer {
private final RequestUrlBuilder urlBuilder;
private Language language;
private UnitSystem unitSystem = UnitSystem.STANDARD;
/**
* Instantiates a new Single result current weather request customizer.
*
* @param urlBuilder the url builder
*/
SingleResultCurrentWeatherRequestCustomizerImpl(RequestUrlBuilder urlBuilder) {
this.urlBuilder = urlBuilder;
}
@Override
public SingleResultCurrentWeatherRequestTerminator retrieve() {
urlBuilder.applyCustomization(language, unitSystem);
return new SingleResultCurrentWeatherRequestTerminatorImpl(urlBuilder, unitSystem);
}
@Override
public SingleResultCurrentWeatherAsyncRequestTerminator retrieveAsync() {
urlBuilder.applyCustomization(language, unitSystem);
return new SingleResultCurrentWeatherAsyncRequestTerminatorImpl(urlBuilder, unitSystem);
}
@Override
public SingleResultCurrentWeatherRequestCustomizer language(Language language) {
this.language = language;
return this;
}
@Override
public SingleResultCurrentWeatherRequestCustomizer unitSystem(UnitSystem unitSystem) {
this.unitSystem = unitSystem;
return this;
}
}
@@ -22,24 +22,46 @@
package com.github.prominence.openweathermap.api.request.weather.single;
import com.github.prominence.openweathermap.api.enums.ResponseType;
import com.github.prominence.openweathermap.api.model.weather.Weather;
import com.github.prominence.openweathermap.api.request.RequestTerminator;
import com.github.prominence.openweathermap.api.request.RequestSettings;
import com.github.prominence.openweathermap.api.mapper.CurrentWeatherResponseMapper;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
/**
* The current weather request terminator interface.
* The type Single result current weather request terminator.
*/
public interface SingleResultCurrentWeatherRequestTerminator extends RequestTerminator<Weather, String> {
/**
* XML response format.
*
* @return the XML string
*/
String asXML();
public class SingleResultCurrentWeatherRequestTerminator {
private final RequestSettings requestSettings;
/**
* HTML response format.
* Instantiates a new Single result current weather request terminator.
*
* @return the HTML string
* @param requestSettings request settings object.
*/
String asHTML();
SingleResultCurrentWeatherRequestTerminator(RequestSettings requestSettings) {
this.requestSettings = requestSettings;
}
public Weather asJava() {
return new CurrentWeatherResponseMapper(requestSettings.getUnitSystem()).getSingle(asJSON());
}
public String asJSON() {
return getRawResponse();
}
public String asXML() {
requestSettings.setResponseType(ResponseType.XML);
return getRawResponse();
}
public String asHTML() {
requestSettings.setResponseType(ResponseType.HTML);
return getRawResponse();
}
private String getRawResponse() {
return RequestUtils.getResponse(requestSettings);
}
}
@@ -1,75 +0,0 @@
/*
* 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.single;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.request.weather.CurrentWeatherResponseMapper;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.weather.Weather;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
/**
* The type Single result current weather request terminator.
*/
public class SingleResultCurrentWeatherRequestTerminatorImpl implements SingleResultCurrentWeatherRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
/**
* Instantiates a new Single result current weather request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
*/
SingleResultCurrentWeatherRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
}
@Override
public Weather asJava() {
return new CurrentWeatherResponseMapper(unitSystem).getSingle(asJSON());
}
@Override
public String asJSON() {
return getRawResponse();
}
@Override
public String asXML() {
urlBuilder.addRequestParameter("mode", "xml");
return getRawResponse();
}
@Override
public String asHTML() {
urlBuilder.addRequestParameter("mode", "html");
return getRawResponse();
}
private String getRawResponse() {
return RequestUtils.getResponse(urlBuilder.buildUrl());
}
}

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