1
0
Fork 0
mirror of https://bitbucket.org/ethauvin/owm-japis.git synced 2025-04-24 09:27:12 -07:00

2.5.1.0: Rewrote the lib. in Kotlin

This commit is contained in:
Ashutosh Kumar Singh 2017-11-09 03:06:02 +05:30
parent 9b2c26b7c4
commit 1a09f739ae
45 changed files with 5376 additions and 3016 deletions

10
.editorconfig Normal file
View file

@ -0,0 +1,10 @@
# editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

21
.gitignore vendored
View file

@ -1,9 +1,18 @@
# NetBeans
lib/nblibraries.properties
nbproject/
/build/
build/
build.xml
/lib/CopyLibs/
/dist/
/.gradle/
/.idea/
owm-japis.iml
# Gradle
.gradle/
# IntelliJ IDEA
.idea/
owm-japis.iml
lib/CopyLibs/
dist/
out/
# Custom
src/main/kotlin/net/aksingh/owmjapis/demo/

View file

@ -1,4 +1,4 @@
Copyright (c) 2013-2015 Ashutosh Kumar Singh <me@aksingh.net>
Copyright (c) 2013- Ashutosh Kumar Singh <ashutosh@aksingh.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

194
README.md
View file

@ -2,27 +2,31 @@
####Java Library for OpenWeatherMap.org Weather APIs
OWM JAPIs lets you develop weather-aware applications for **Java and Android platforms** in minimum time using OWM JAPIs, an easy-to-use, detailed and documented weather APIs' wrapper library for retrieving weather data from OpenWeatherMap.org. You can easily **retrieve and use weather data** in your applications using this library.
OWM JAPIs lets you develop weather-aware applications for **Java, Android, and Kotlin** platforms in minimum time. It is an easy-to-use, well-documented wrapper library for OpenWeatherMap.org's Weather APIs. You can easily **retrieve and use weather data** in your applications using this library.
OWM JAPIs allows you to **fetch weather data in only 3-5 lines of code** (excluding any other/skeleton code, of course). You can develop applications and services for multiple platforms using this library, such as Windows, Mac OS X, Linux, and Android.
OWM JAPIs allows you to **fetch weather data in only 3-5 lines of code**. You can develop applications and services for multiple platforms using this library, such as Windows, Mac OS X, Linux, and Android.
Homepage: http://code.aksingh.net/owm-japis
*Homepage:* [http://go.aksingh.net/owm-japis](http://go.aksingh.net/owm-japis)
###Why to use OWM JAPIs?
1. Free
2. Easy to use
3. Minimizes your code
3. Supports re-use
4. Minimizes the code
5. Developer-friendly
OWM JAPIs lets you **focus just on your application's logic** and **weather retrieval code is provided** by this library. Additionally, weather retrieval code becomes very short using this library as less as 3-5 lines of code can get you weather data from OpenWeatherMap.org in your Java or Android application. **Surprising, right? Have a look on the example(s) below.**
With OWM JAPIs, you can **focus just on your application's logic** and **delegate weather retrieval** to this library. As a bonus, weather retrieval code becomes very short using this library - as less as 3-5 lines of code can get you weather data from OpenWeatherMap.org in your Java, Android, or Kotlin application.
**Surprised? Have a look on the example(s) below.**
##How to use OWM JAPIs?
Download the library's source and binaries from [OWM JAPIs Downloads][1].
Do you use Maven, Gradle, or some another build tool? [OWM JAPIs is available in Maven Central repository](http://search.maven.org/#search%7Cga%7C1%7Cowm-japis).
Do use Maven, Gradle or an build tool? [OWM JAPIs is available in Maven Central repository][10].
No? Not an issue. You can download the releases (source and binaries) from [OWM JAPIs Downloads](http://go.aksingh.net/owm-japis-dloads).
@ -30,92 +34,28 @@ Do use Maven, Gradle or an build tool? [OWM JAPIs is available in Maven Central
###2.5 (Compatible with OpenWeatherMap.org's API v2.5)
####2.5.0.5 (latest)
####2.5.1.0
**Bug-fix version:**
**Major version:**
1. Fixed 1h and 3h parameter in Rain and Snow.
2. Added Snow in CurrentWeather.
3. Added proxy support to fetch data via a proxy server.
####2.5.0.4
**Bug-fix version:**
1. Fixed lang parameter bug.
2. Library supports serialization and parcelization.
3. Uploaded the library to Maven Central repository.
####2.5.0.3
**Implemented:**
1. Current Weather
2. Daily Forecasts
3. Hourly Forecasts
**New Features:**
1. Faster than ever before
2. Raw Response for Caching purposes
3. APIs' URL building using StringBuilder
4. Multi-lingual (multiple languages) support
5. Support for external/third-party HTTP libraries (like Apache's HttpComponents)
6. Units and Language enums for setting configuration easily and correctly
7. Better maintain-able source code (for developers)
8. Ported the project to Gradle (for developers)
**Changed:**
1. Package's name from net.aksingh.java.api.owm to net.aksingh.owmjapis
2. Class's name from CurrentWeatherData to CurrentWeather
3. Class's name from DailyForecastData to DailyForecast
4. Class's name from ForecastWeatherData to HourlyForecast
5. Some functions' name and signature
**Apologies for making such changes, but it was required to make things simpler. Don't worry, they're not going to change again. :)**
####2.5.0.2
**Bug-fix version:**
1. Fixed bugs which caused wrong parsing of date and time.
2. Improved code formatting and readability (for developers).
####2.5.0.1
**Implemented:**
1. Current Weather
2. Weather Forecasts
3. Daily Forecasts
4. Wind degree to direction converter
**Not implemented but planned:**
1. Searching of City
2. Weather Maps
3. Country code to name converter
4. Direction code to name converter
1. Re-wrote whole lib. in Kotlin
2. Supports retrieving Current Weather, Hourly Forecast, and Daily Forecast
3. Requires min. Java 1.7 platform and supports Java, Kotlin, and Android now
##How to use OWM JAPIs?
Anyone with little coding knowledge of Java will feel at home while using this library. **Identifiers are written to be self-explanatory and APIs' documentation** is also provided. It makes the coding process very easy, even for beginners.
Anyone with little coding knowledge of Java or Kotlin will feel at home while using this library. **Identifiers are written to be self-explanatory and APIs' documentation** (java docs) is also provided along with OWM JAPIs.
1. Add this JAR file in your project's libraries:
1. owm-japis.jar
1. owm-japis-{VERSION}.jar
2. Write your code as such:
1. Create and initialize object {obj1} of "OpenWeatherMap" class
1. Create and initialize object {obj1} of "OWM" class
2. Call this object's {obj1} functions to get the desired weather data (such as current weather, daily forecast, etc.).
3. The data is returned as a new object {obj2} of a compatible class based on the type of asked/retrieved weather data (current weather data comes in a different class's object than daily forecast data).
3. Call this returned object's {obj2} functions to get the required information from the collective weather data (such as temperature, pressure, wind speed, etc.).
Kindly have a look on the example(s) below for clear understanding.
Is it hard to understand the English of programming? Well, you are not the only one. I feel the same. Kindly have a look on the example(s) below for a clear understanding.
@ -123,19 +63,17 @@ Kindly have a look on the example(s) below for clear understanding.
### Basic Example
####Sample Code
import java.io.IOException;
import java.net.MalformedURLException;
import net.aksingh.owmjapis.CurrentWeather;
import net.aksingh.owmjapis.OpenWeatherMap;
import org.json.JSONException;
import net.aksingh.owmjapis.core.OpenWeatherMap;
import net.aksingh.owmjapis.api.APIException;
import net.aksingh.owmjapis.model.CurrentWeather;
public class OwmJapisExample1 {
public static void main(String[] args)
throws IOException, MalformedURLException, JSONException {
throws APIException {
// declaring object of "OpenWeatherMap" class
OpenWeatherMap owm = new OpenWeatherMap("");
// declaring object of "OWM" class
OWM owm = new OWM("YOUR-API-KEY-HERE");
// getting current weather data for the "London" city
CurrentWeather cwd = owm.currentWeatherByCityName("London");
@ -144,57 +82,55 @@ Kindly have a look on the example(s) below for clear understanding.
System.out.println("City: " + cwd.getCityName());
// printing the max./min. temperature
System.out.println("Temperature: " + cwd.getMainInstance().getMaxTemperature()
+ "/" + cwd.getMainInstance().getMinTemperature() + "\'F");
System.out.println("Temperature: " + cwd.getMainData().getTempMax()
+ "/" + cwd.getMainData().getTempMin() + "\'K");
}
}
####Output
City: London
Temperature: 73.4/68.72 'F
Temperature: 73.4/68.72 'K
###Advance Example
You can simply use the APIs (as given in basic example) for learning, testing or experimenting with the functions provided in this library. But it may not be good enough for production or deployment environment.
You can simply use the APIs (as given in the basic example) for learning, testing or experimenting with the functions provided in this library. But it may not be good enough for production or deployment environment. Don't you agree?
Professionally, you should always **write code which can handle errors/exceptions** at the runtime. OWM JAPIs also helps here by providing checker functions which allows you to **check if a data is available or not**, i.e., that particular data is retrieved and parsed properly or not. Of course, exception handling can still be used, but these functions are really useful and make the retrieved-data-error-handling task very simple.
Professionally, you should always **write code which can handle errors** as best as possible. OWM JAPIs helps here too by providing checker functions which allows you to **check if a data is available or not**, i.e., that particular data is retrieved and parsed properly or not. Of course, exception handling can still be used, but these functions are really useful and make the retrieved-data-error-handling task very simple.
Using OWM JAPIs, you can always check if a particular data is available or not. This is done by using the **has<DataName>()** functions. For example, **hasResponseCode()** function checks if the retrieved data has a response code or not; and if available, response code can be used to check if the whole data was downloaded and parsed correctly or not.
Using OWM JAPIs, you can always check if a particular data is available or not. This is done by using the **has{DATA-NAME}()** functions. For example, **hasRespCode()** function checks if the retrieved data has a response code or not. And if available, response code can be used to check if the whole data was downloaded and parsed correctly or not, as you can see in the example below.
####Sample Code
import java.io.IOException;
import java.net.MalformedURLException;
import net.aksingh.owmjapis.CurrentWeather;
import net.aksingh.owmjapis.OpenWeatherMap;
import org.json.JSONException;
import net.aksingh.owmjapis.core.OpenWeatherMap;
import net.aksingh.owmjapis.api.APIException;
import net.aksingh.owmjapis.model.CurrentWeather;
public class OwmJapisExample2 {
public static void main(String[] args)
throws IOException, MalformedURLException, JSONException {
// declaring object of "OpenWeatherMap" class
OpenWeatherMap owm = new OpenWeatherMap("");
throws APIException {
// declaring object of "OWM" class
OWM owm = new OWM("YOUR-API-KEY-HERE");
// getting current weather data for the "London" city
CurrentWeather cwd = owm.currentWeatherByCityName("London");
// checking data retrieval was successful or not
if (cwd.isValid()) {
if (cwd.hasRespCode() && cwd.getRespCode() == 200) {
// checking if city name is available
if (cwd.hasCityName()) {
//printing city name from the retrieved data
System.out.println("City: " + cwd.getCityName());
}
// checking if max. temp. and min. temp. is available
if (cwd.getMainInstance().hasMaxTemperature() && cwd.getMainInstance().hasMinTemperature()) {
if (cwd.hasMainData() && cwd.getMainData().hasTempMax() && cwd.getMainData().hasTempMin()) {
// printing the max./min. temperature
System.out.println("Temperature: " + cwd.getMainInstance().getMaxTemperature()
+ "/" + cwd.getMainInstance().getMinTemperature() + "\'F");
System.out.println("Temperature: " + cwd.getMainData().getTempMax()
+ "/" + cwd.getMainData().getTempMin() + "\'K");
}
}
}
@ -203,55 +139,41 @@ Using OWM JAPIs, you can always check if a particular data is available or not.
####Output
City: London
Temperature: 73.4/68.72 'F
Temperature: 73.4/68.72 'K
##Source code
Download the library's source code from [OWM JAPIs Source][2].
Download the library's source code from [OWM JAPIs Source](https://code.aksingh.net/owm-japis/src).
##Bugs / Requests
Got a problem, error or bug in the library? Or want a new feature that's not already available in OWM JAPIs?
Kindly post bugs or feature requests at [OWM JAPIs Issues][3] and I will try to solve/add it in the next release.
Kindly post bugs or feature requests at [OWM JAPIs Issues](https://code.aksingh.net/owm-japis/issues) and I will try to solve/add it in the next release.
##Developer
**Ashutosh Kumar Singh** | [AKSingh.net][4] | [me@aksingh.net][9]
**Ashutosh Kumar Singh** | [www.aksingh.net](https://www.aksingh.net/) | [ashutosh@aksingh.net](mailto:ashutosh@aksingh.net)
and contributors. Do you wish to contribute? Just fork this repo on GitHub or BitBucket and send a pull request.
##Credits
1. [OpenWeatherMap.org][5]
for providing free weather data and creating easy-to-use web APIs.
1. [OpenWeatherMap.org](https://openweathermap.org/)
for providing free weather data and creating easy-to-use APIs.
2. [JSON.org][6]
for providing such a great data interchange language and its library in Java.
3. [ForecastIO-Lib-Java][8]
2. [ForecastIO-Lib-Java](https://github.com/dvdme/forecastio-lib-java)
for providing ideas like support for third-party Http libraries.
4. [Bug Reporters][3]
for reporting bugs, and even finding and sharing possible solutions for them.
3. [You, for supporting OWM JAPIs](https://code.aksingh.net/owm-japis/issues)
and for reporting bugs, and even finding and sharing possible solutions for them.
##License
Copyright (c) 2013-2014 Ashutosh Kumar Singh `<me@aksingh.net>`
Copyright (c) 2013-2017 Ashutosh Kumar Singh `<ashutosh@aksingh.net>`
Released under the terms of the [MIT license][7]. It's open source and developer-friendly.
[1]: http://code.aksingh.net/owm-japis/downloads
[2]: http://code.aksingh.net/owm-japis/src
[3]: http://code.aksingh.net/owm-japis/issues
[4]: http://www.aksingh.net/
[5]: http://openweathermap.org/
[6]: http://www.json.org/java/index.html
[7]: http://opensource.org/licenses/MIT
[8]: https://github.com/dvdme/forecastio-lib-java
[9]: mailto:me@aksingh.net
[10]: http://search.maven.org/#search%7Cga%7C1%7Cowm-japis
Released under the terms of the [MIT license](https://opensource.org/licenses/MIT). It's open source and developer-friendly.

84
VERSIONS.md Normal file
View file

@ -0,0 +1,84 @@
##Versions
###2.5 (Compatible with OpenWeatherMap.org's API v2.5)
####2.5.1.0
**Major version:**
1. Re-wrote whole lib. in Kotlin
2. Supports retrieving Current Weather, Hourly Forecast, and Daily Forecast
3. Requires min. Java 1.7 platform and supports Java, Kotlin, and Android now
####2.5.0.5
**Bug-fix version:**
1. Fixed 1h and 3h parameter in Rain and Snow.
2. Added Snow in CurrentWeather.
3. Added proxy support to fetch data via a proxy server.
####2.5.0.4
**Bug-fix version:**
1. Fixed lang parameter bug.
2. Library supports serialization and parcelization.
3. Uploaded the library to Maven Central repository.
####2.5.0.3
**Implemented:**
1. Current Weather
2. Daily Forecasts
3. Hourly Forecasts
**New Features:**
1. Faster than ever before
2. Raw Response for Caching purposes
3. APIs' URL building using StringBuilder
4. Multi-lingual (multiple languages) support
5. Support for external/third-party HTTP libraries (like Apache's HttpComponents)
6. Units and Language enums for setting configuration easily and correctly
7. Better maintain-able source code (for developers)
8. Ported the project to Gradle (for developers)
**Changed:**
1. Package's name from net.aksingh.java.api.owm to net.aksingh.owmjapis
2. Class's name from CurrentWeatherData to CurrentWeather
3. Class's name from DailyForecastData to DailyForecast
4. Class's name from ForecastWeatherData to HourlyForecast
5. Some functions' name and signature
**Apologies for making such changes, but it was required to make things simpler. Don't worry, they're not going to change again. :)**
####2.5.0.2
**Bug-fix version:**
1. Fixed bugs which caused wrong parsing of date and time.
2. Improved code formatting and readability (for developers).
####2.5.0.1
**Implemented:**
1. Current Weather
2. Weather Forecasts
3. Daily Forecasts
4. Wind degree to direction converter
**Not implemented but planned:**
1. Searching of City
2. Weather Maps
3. Country code to name converter
4. Direction code to name converter

View file

@ -1,80 +1,133 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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. *
**************************************************************************************************/
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'org.jetbrains.dokka'
apply plugin: 'maven'
apply plugin: 'signing'
sourceCompatibility = 1.5
sourceCompatibility = 1.7
group = 'net.aksingh'
archivesBaseName = "owm-japis"
version = '2.5.0.5'
version = '2.5.1.0'
repositories {
mavenCentral()
mavenCentral()
}
dependencies {
compile group: 'org.json', name: 'json', version: '20140107'
testCompile group: 'junit', name: 'junit', version: '4.12'
compile 'org.json:json:20171018'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile "org.jetbrains.kotlin:kotlin-stdlib"
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
testCompile 'junit:junit:4.12'
}
task javadocJar(type: Jar) {
classifier = 'javadoc'
from javadoc
classifier = 'javadoc'
from javadoc
}
task sourcesJar(type: Jar) {
classifier = 'sources'
from sourceSets.main.allSource
classifier = 'sources'
from sourceSets.main.allSource
}
artifacts {
archives javadocJar, sourcesJar
archives javadocJar, sourcesJar
}
signing {
sign configurations.archives
sign configurations.archives
}
uploadArchives {
repositories {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
repositories {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
authentication(userName: ossrhUsername, password: ossrhPassword)
}
repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
authentication(userName: ossrhUsername, password: ossrhPassword)
}
snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") {
authentication(userName: ossrhUsername, password: ossrhPassword)
}
snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") {
authentication(userName: ossrhUsername, password: ossrhPassword)
}
pom.project {
name 'OWM JAPIs'
packaging 'jar'
description 'Java Wrapper Library for OpenWeatherMap.org Web APIs'
url 'http://code.aksingh.net/owm-japis'
pom.project {
name 'OWM JAPIs'
packaging 'jar'
description 'Java Wrapper Library for OpenWeatherMap.org Web APIs'
url 'http://go.aksingh.net/owm-japis'
scm {
connection 'scm:svn:http://foo.googlecode.com/svn/trunk/'
developerConnection 'scm:svn:https://foo.googlecode.com/svn/trunk/'
url 'http://foo.googlecode.com/svn/trunk/'
}
licenses {
license {
name 'The MIT License (MIT)'
url 'http://opensource.org/licenses/MIT'
}
}
developers {
developer {
id 'akapribot'
name 'Ashutosh Kumar Singh'
email 'me@aksingh.net'
}
}
}
scm {
connection 'scm:svn:http://foo.googlecode.com/svn/trunk/'
developerConnection 'scm:svn:https://foo.googlecode.com/svn/trunk/'
url 'http://foo.googlecode.com/svn/trunk/'
}
licenses {
license {
name 'The MIT License (MIT)'
url 'http://opensource.org/licenses/MIT'
}
}
developers {
developer {
id 'aksinghnet'
name 'Ashutosh Kumar Singh'
email 'ashutosh@aksingh.net'
}
}
}
}
}
}
dokka {
outputFormat = 'javadoc'
outputDirectory = "$buildDir/javadoc"
jdkVersion = 7
impliedPlatforms = ["JVM"]
}
buildscript {
ext.kotlin_version = '1.1.51'
ext.dokka_version = '0.9.15'
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.dokka:dokka-gradle-plugin:${dokka_version}"
}
}

Binary file not shown.

View file

@ -1,28 +1,23 @@
#
# Copyright (c) 2013-2015 Ashutosh Kumar Singh <me@aksingh.net>
#
# 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.
#
#Fri Dec 19 05:07:43 IST 2014
####################################################################################################
# Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> #
# #
# 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. #
####################################################################################################
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-4.3-all.zip

74
gradlew vendored
View file

@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/usr/bin/env sh
##############################################################################
##
@ -6,12 +6,30 @@
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
@ -30,6 +48,7 @@ die ( ) {
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
@ -40,31 +59,11 @@ case "`uname`" in
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@ -90,7 +89,7 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
@ -114,6 +113,7 @@ fi
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
@ -154,11 +154,19 @@ if $cygwin ; then
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
# Escape application args
save ( ) {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
APP_ARGS=$(save "$@")
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

14
gradlew.bat vendored
View file

@ -8,14 +8,14 @@
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
@ -46,10 +46,9 @@ echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
@ -60,11 +59,6 @@ set _SKIP=2
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line

View file

@ -1,2 +1,20 @@
rootProject.name = 'owm-japis'
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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. *
**************************************************************************************************/
rootProject.name = 'owm-japis'

View file

@ -1,24 +1,21 @@
/*
* Copyright (c) 2013-2015 Ashutosh Kumar Singh <me@aksingh.net>
*
* 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.
*/
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis;
@ -39,211 +36,211 @@ import java.io.Serializable;
* @since 2.5.0.3
*/
public abstract class AbstractForecast extends AbstractResponse {
/*
JSON Keys
*/
static final String JSON_FORECAST_LIST = "list";
static final String JSON_MESSAGE = "message";
static final String JSON_CITY = "city";
static final String JSON_FORECAST_COUNT = "cnt";
/*
JSON Keys
*/
static final String JSON_FORECAST_LIST = "list";
static final String JSON_MESSAGE = "message";
static final String JSON_CITY = "city";
static final String JSON_FORECAST_COUNT = "cnt";
/*
Instance variables
*/
private final double message;
/*
Instance variables
*/
private final double message;
private final City city;
private final int forecastCount;
private final City city;
private final int forecastCount;
/*
Constructors
/*
Constructors
*/
AbstractForecast() {
super();
this.message = Double.NaN;
this.forecastCount = 0;
this.city = null;
}
AbstractForecast(JSONObject jsonObj) {
super(jsonObj);
this.message = (jsonObj != null) ? jsonObj.optDouble(JSON_MESSAGE, Double.NaN) : Double.NaN;
this.city = (jsonObj != null) ? new City(jsonObj.optJSONObject(JSON_CITY)) : null;
this.forecastCount = (jsonObj != null) ? jsonObj.optInt(JSON_FORECAST_COUNT, 0) : 0;
}
/**
* @return <code>true</code> if message is available, otherwise <code>false</code>.
*/
public boolean hasMessage() {
return (this.message != Double.NaN);
}
/**
* @return <code>true</code> if count of forecasts is available, otherwise <code>false</code>.
*/
public boolean hasForecastCount() {
return (this.forecastCount != 0);
}
/**
* @return <code>true</code> if message is available, otherwise <code>false</code>.
*/
public boolean hasCityInstance() {
return (this.city != null);
}
/**
* @return Message if available, otherwise <code>Double.NaN</code>.
*/
public double getMessage() {
return this.message;
}
/**
* @return Count of forecasts if available, otherwise <code>0</code>.
*/
public int getForecastCount() {
return this.forecastCount;
}
/**
* @return City's instance if available, otherwise <code>null</code>.
*/
public City getCityInstance() {
return this.city;
}
/**
* <p>
* Provides default behaviours for City
* </p>
*
* @author Ashutosh Kumar Singh
*/
public static class City implements Serializable {
private static final String JSON_CITY_ID = "id";
private static final String JSON_CITY_NAME = "name";
private static final String JSON_CITY_COUNTRY_CODE = "country";
private static final String JSON_CITY_POPULATION = "population";
private static final String JSON_CITY_COORD = "coord";
private final long cityID;
private final String cityName;
private final String countryCode;
private final long population;
private final Coord coord;
City() {
this.cityID = Long.MIN_VALUE;
this.cityName = null;
this.countryCode = null;
this.population = Long.MIN_VALUE;
this.coord = new Coord();
}
City(JSONObject jsonObj) {
this.cityID = (jsonObj != null) ? jsonObj.optLong(JSON_CITY_ID, Long.MIN_VALUE) : Long.MIN_VALUE;
this.cityName = (jsonObj != null) ? jsonObj.optString(JSON_CITY_NAME, null) : null;
this.countryCode = (jsonObj != null) ? jsonObj.optString(JSON_CITY_COUNTRY_CODE, null) : null;
this.population = (jsonObj != null) ? jsonObj.optLong(JSON_CITY_POPULATION, Long.MIN_VALUE) : Long.MIN_VALUE;
JSONObject jsonObjCoord = (jsonObj != null) ? jsonObj.optJSONObject(JSON_CITY_COORD) : null;
this.coord = (jsonObjCoord != null) ? new Coord(jsonObjCoord) : null;
}
public boolean hasCityCode() {
return this.cityID != Long.MIN_VALUE;
}
public boolean hasCityName() {
return this.cityName != null;
}
public boolean hasCountryCode() {
return this.countryCode != null;
}
public boolean hasCityPopulation() {
return this.population != Long.MIN_VALUE;
}
/**
* @return <code>true</code> if Coord instance is available, otherwise <code>false</code>.
*/
AbstractForecast() {
public boolean hasCoordInstance() {
return coord != null;
}
public long getCityCode() {
return this.cityID;
}
public String getCityName() {
return this.cityName;
}
public String getCountryCode() {
return this.countryCode;
}
public long getCityPopulation() {
return this.population;
}
/**
* @return Coord instance if available, otherwise <code>null</code>.
*/
public Coord getCoordInstance() {
return this.coord;
}
public static class Coord extends AbstractWeather.Coord {
Coord() {
super();
}
this.message = Double.NaN;
this.forecastCount = 0;
this.city = null;
}
AbstractForecast(JSONObject jsonObj) {
Coord(JSONObject jsonObj) {
super(jsonObj);
}
}
}
this.message = (jsonObj != null) ? jsonObj.optDouble(JSON_MESSAGE, Double.NaN) : Double.NaN;
this.city = (jsonObj != null) ? new City(jsonObj.optJSONObject(JSON_CITY)) : null;
this.forecastCount = (jsonObj != null) ? jsonObj.optInt(JSON_FORECAST_COUNT, 0) : 0;
/**
* <p>
* Parses forecast data (one element in the forecastList) and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2014/12/27
* @since 2.5.0.3
*/
public abstract static class Forecast extends AbstractWeather {
Forecast() {
super();
}
/**
* @return <code>true</code> if message is available, otherwise <code>false</code>.
*/
public boolean hasMessage() {
return (this.message != Double.NaN);
}
/**
* @return <code>true</code> if count of forecasts is available, otherwise <code>false</code>.
*/
public boolean hasForecastCount() {
return (this.forecastCount != 0);
}
/**
* @return <code>true</code> if message is available, otherwise <code>false</code>.
*/
public boolean hasCityInstance() {
return (this.city != null);
}
/**
* @return Message if available, otherwise <code>Double.NaN</code>.
*/
public double getMessage() {
return this.message;
}
/**
* @return Count of forecasts if available, otherwise <code>0</code>.
*/
public int getForecastCount() {
return this.forecastCount;
}
/**
* @return City's instance if available, otherwise <code>null</code>.
*/
public City getCityInstance() {
return this.city;
}
/**
* <p>
* Provides default behaviours for City
* </p>
*
* @author Ashutosh Kumar Singh
*/
public static class City implements Serializable {
private static final String JSON_CITY_ID = "id";
private static final String JSON_CITY_NAME = "name";
private static final String JSON_CITY_COUNTRY_CODE = "country";
private static final String JSON_CITY_POPULATION = "population";
private static final String JSON_CITY_COORD = "coord";
private final long cityID;
private final String cityName;
private final String countryCode;
private final long population;
private final Coord coord;
City() {
this.cityID = Long.MIN_VALUE;
this.cityName = null;
this.countryCode = null;
this.population = Long.MIN_VALUE;
this.coord = new Coord();
}
City(JSONObject jsonObj) {
this.cityID = (jsonObj != null) ? jsonObj.optLong(JSON_CITY_ID, Long.MIN_VALUE) : Long.MIN_VALUE;
this.cityName = (jsonObj != null) ? jsonObj.optString(JSON_CITY_NAME, null) : null;
this.countryCode = (jsonObj != null) ? jsonObj.optString(JSON_CITY_COUNTRY_CODE, null) : null;
this.population = (jsonObj != null) ? jsonObj.optLong(JSON_CITY_POPULATION, Long.MIN_VALUE) : Long.MIN_VALUE;
JSONObject jsonObjCoord = (jsonObj != null) ? jsonObj.optJSONObject(JSON_CITY_COORD) : null;
this.coord = (jsonObjCoord != null) ? new Coord(jsonObjCoord) : null;
}
public boolean hasCityCode() {
return this.cityID != Long.MIN_VALUE;
}
public boolean hasCityName() {
return this.cityName != null;
}
public boolean hasCountryCode() {
return this.countryCode != null;
}
public boolean hasCityPopulation() {
return this.population != Long.MIN_VALUE;
}
/**
* @return <code>true</code> if Coord instance is available, otherwise <code>false</code>.
*/
public boolean hasCoordInstance() {
return coord != null;
}
public long getCityCode() {
return this.cityID;
}
public String getCityName() {
return this.cityName;
}
public String getCountryCode() {
return this.countryCode;
}
public long getCityPopulation() {
return this.population;
}
/**
* @return Coord instance if available, otherwise <code>null</code>.
*/
public Coord getCoordInstance() {
return this.coord;
}
public static class Coord extends AbstractWeather.Coord {
Coord() {
super();
}
Coord(JSONObject jsonObj) {
super(jsonObj);
}
}
}
/**
* <p>
* Parses forecast data (one element in the forecastList) and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2014/12/27
* @since 2.5.0.3
*/
public abstract static class Forecast extends AbstractWeather {
Forecast() {
super();
}
Forecast(JSONObject jsonObj) {
super(jsonObj);
}
Forecast(JSONObject jsonObj) {
super(jsonObj);
}
}
}

View file

@ -1,24 +1,21 @@
/*
* Copyright (c) 2013-2015 Ashutosh Kumar Singh <me@aksingh.net>
*
* 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.
*/
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis;
@ -28,7 +25,7 @@ import java.io.Serializable;
/**
* <p>
* Provides default behaviours and implementations for the response from OWM.org
* Provides default behaviours and implementations for the response from OpenWeatherMap.org
* </p>
*
* @author Ashutosh Kumar Singh
@ -36,62 +33,62 @@ import java.io.Serializable;
* @since 2.5.0.3
*/
abstract class AbstractResponse implements Serializable {
/*
JSON Keys
*/
private static final String JSON_RESPONSE_CODE = "cod";
/*
JSON Keys
*/
private static final String JSON_RESPONSE_CODE = "code";
/*
Instance variables
*/
private final int responseCode;
private final String rawResponse;
/*
Instance variables
*/
private final int responseCode;
private final String rawResponse;
/*
Constructors
*/
AbstractResponse() {
this.rawResponse = null;
this.responseCode = Integer.MIN_VALUE;
}
/*
Constructors
*/
AbstractResponse() {
this.rawResponse = null;
this.responseCode = Integer.MIN_VALUE;
}
AbstractResponse(JSONObject jsonObj) {
this.rawResponse = (jsonObj != null) ? jsonObj.toString() : null;
this.responseCode = (jsonObj != null) ? jsonObj.optInt(JSON_RESPONSE_CODE, Integer.MIN_VALUE) : Integer.MIN_VALUE;
}
AbstractResponse(JSONObject jsonObj) {
this.rawResponse = (jsonObj != null) ? jsonObj.toString() : null;
this.responseCode = (jsonObj != null) ? jsonObj.optInt(JSON_RESPONSE_CODE, Integer.MIN_VALUE) : Integer.MIN_VALUE;
}
/**
* @return <code>true</code> if response is valid (downloaded and parsed correctly), otherwise <code>false</code>.
*/
public boolean isValid() {
return this.responseCode == 200;
}
/**
* @return <code>true</code> if response is valid (downloaded and parsed correctly), otherwise <code>false</code>.
*/
public boolean isValid() {
return this.responseCode == 200;
}
/**
* @return <code>true</code> if response code is available, otherwise <code>false</code>.
*/
public boolean hasResponseCode() {
return this.responseCode != Integer.MIN_VALUE;
}
/**
* @return <code>true</code> if response code is available, otherwise <code>false</code>.
*/
public boolean hasResponseCode() {
return this.responseCode != Integer.MIN_VALUE;
}
/**
* @return <code>true</code> if raw response is available, otherwise <code>false</code>.
*/
public boolean hasRawResponse() {
return this.rawResponse != null;
}
/**
* @return <code>true</code> if raw response is available, otherwise <code>false</code>.
*/
public boolean hasRawResponse() {
return this.rawResponse != null;
}
/**
* @return Response code if available, otherwise <code>Integer.MIN_VALUE</code>.
*/
public int getResponseCode() {
return this.responseCode;
}
/**
* @return Response code if available, otherwise <code>Integer.MIN_VALUE</code>.
*/
public int getResponseCode() {
return this.responseCode;
}
/**
* @return Raw response if available, otherwise <code>null</code>.
*/
public String getRawResponse() {
return this.rawResponse;
}
/**
* @return Raw response if available, otherwise <code>null</code>.
*/
public String getRawResponse() {
return this.rawResponse;
}
}

View file

@ -1,24 +1,21 @@
/*
* Copyright (c) 2013-2015 Ashutosh Kumar Singh <me@aksingh.net>
*
* 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.
*/
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis;
@ -43,478 +40,478 @@ import java.util.List;
* @since 2.5.0.1
*/
public abstract class AbstractWeather extends AbstractResponse {
/*
JSON Keys
*/
static final String JSON_CLOUDS = "clouds";
static final String JSON_COORD = "coord";
static final String JSON_MAIN = "main";
static final String JSON_WIND = "wind";
private static final String JSON_WEATHER = "weather";
private static final String JSON_DATE_TIME = "dt";
/*
JSON Keys
*/
static final String JSON_CLOUDS = "clouds";
static final String JSON_COORD = "coord";
static final String JSON_MAIN = "main";
static final String JSON_WIND = "windData";
private static final String JSON_WEATHER = "weather";
private static final String JSON_DATE_TIME = "dt";
/*
Instance variables
*/
private final Date dateTime;
/*
Instance variables
*/
private final Date dateTime;
private final int weatherCount;
private final List<Weather> weatherList;
private final int weatherCount;
private final List<Weather> weatherList;
/*
Constructors
*/
AbstractWeather() {
super();
/*
Constructors
*/
AbstractWeather() {
super();
this.weatherCount = 0;
this.weatherList = null;
this.dateTime = null;
this.weatherCount = 0;
this.weatherList = null;
this.dateTime = null;
}
AbstractWeather(JSONObject jsonObj) {
super(jsonObj);
long sec = (jsonObj != null) ? jsonObj.optLong(JSON_DATE_TIME, Long.MIN_VALUE) : Long.MIN_VALUE;
if (sec != Long.MIN_VALUE) { // converting seconds to Date object
this.dateTime = new Date(sec * 1000);
} else {
this.dateTime = null;
}
AbstractWeather(JSONObject jsonObj) {
super(jsonObj);
long sec = (jsonObj != null) ? jsonObj.optLong(JSON_DATE_TIME, Long.MIN_VALUE) : Long.MIN_VALUE;
if (sec != Long.MIN_VALUE) { // converting seconds to Date object
this.dateTime = new Date(sec * 1000);
} else {
this.dateTime = null;
JSONArray weatherArray = (jsonObj != null) ? jsonObj.optJSONArray(JSON_WEATHER) : new JSONArray();
this.weatherList = (weatherArray != null) ? new ArrayList<Weather>(weatherArray.length()) : Collections.EMPTY_LIST;
if (weatherArray != null && this.weatherList != Collections.EMPTY_LIST) {
for (int i = 0; i < weatherArray.length(); i++) {
JSONObject weatherObj = weatherArray.optJSONObject(i);
if (weatherObj != null) {
this.weatherList.add(new Weather(weatherObj));
}
}
}
this.weatherCount = this.weatherList.size();
}
JSONArray weatherArray = (jsonObj != null) ? jsonObj.optJSONArray(JSON_WEATHER) : new JSONArray();
this.weatherList = (weatherArray != null) ? new ArrayList<Weather>(weatherArray.length()) : Collections.EMPTY_LIST;
if (weatherArray != null && this.weatherList != Collections.EMPTY_LIST) {
for (int i = 0; i < weatherArray.length(); i++) {
JSONObject weatherObj = weatherArray.optJSONObject(i);
if (weatherObj != null) {
this.weatherList.add(new Weather(weatherObj));
}
}
}
this.weatherCount = this.weatherList.size();
/**
* @return <code>true</code> if date/time is available, otherwise <code>false</code>.
*/
public boolean hasDateTime() {
return this.dateTime != null;
}
/**
* @return <code>true</code> if Weather instance(s) is available, otherwise <code>false</code>.
*/
public boolean hasWeatherInstance() {
return weatherCount != 0;
}
/**
* @return Date and time if available, otherwise <code>null</code>.
*/
public Date getDateTime() {
return this.dateTime;
}
/**
* @return Count of Weather instance(s) if available, otherwise 0.
*/
public int getWeatherCount() {
return this.weatherCount;
}
/**
* @param index Index of Weather instance in the list.
* @return Weather instance if available, otherwise <code>null</code>.
*/
public Weather getWeatherInstance(int index) {
return this.weatherList.get(index);
}
/**
* <p>
* Provides default behaviours for Cloud
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2013/12/23
* @since 2.5.0.1
*/
abstract public static class Clouds implements Serializable {
private static final String JSON_CLOUDS_ALL = "all";
private final float percentOfClouds;
Clouds() {
this.percentOfClouds = Float.NaN;
}
Clouds(JSONObject jsonObj) {
this.percentOfClouds = (float) jsonObj.optDouble(JSON_CLOUDS_ALL, Double.NaN);
}
/**
* @return <code>true</code> if date/time is available, otherwise <code>false</code>.
*/
public boolean hasDateTime() {
return this.dateTime != null;
}
/**
* @return <code>true</code> if Weather instance(s) is available, otherwise <code>false</code>.
*/
public boolean hasWeatherInstance() {
return weatherCount != 0;
}
/**
* @return Date and time if available, otherwise <code>null</code>.
*/
public Date getDateTime() {
return this.dateTime;
}
/**
* @return Count of Weather instance(s) if available, otherwise 0.
*/
public int getWeatherCount() {
return this.weatherCount;
}
/**
* @param index Index of Weather instance in the list.
* @return Weather instance if available, otherwise <code>null</code>.
*/
public Weather getWeatherInstance(int index) {
return this.weatherList.get(index);
}
/**
* <p>
* Provides default behaviours for Cloud
* </p>
* Tells if percentage of clouds is available or not.
*
* @author Ashutosh Kumar Singh
* @version 2013/12/23
* @since 2.5.0.1
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
abstract public static class Clouds implements Serializable {
private static final String JSON_CLOUDS_ALL = "all";
private final float percentOfClouds;
Clouds() {
this.percentOfClouds = Float.NaN;
}
Clouds(JSONObject jsonObj) {
this.percentOfClouds = (float) jsonObj.optDouble(JSON_CLOUDS_ALL, Double.NaN);
}
/**
* Tells if percentage of clouds is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public boolean hasPercentageOfClouds() {
return !Float.isNaN(this.percentOfClouds);
}
/**
* @return Percentage of all clouds if available, otherwise <code>Float.NaN</code>.
*/
public float getPercentageOfClouds() {
return this.percentOfClouds;
}
public boolean hasPercentageOfClouds() {
return !Float.isNaN(this.percentOfClouds);
}
/**
* <p>
* Provides default behaviours for Coord, i.e., coordinates.
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2013/12/23
* @since 2.5.0.1
* @return Percentage of all clouds if available, otherwise <code>Float.NaN</code>.
*/
abstract public static class Coord implements Serializable {
private static final String JSON_COORD_LATITUDE = "lat";
private static final String JSON_COORD_LONGITUDE = "lon";
public float getPercentageOfClouds() {
return this.percentOfClouds;
}
}
private final float lat;
private final float lon;
/**
* <p>
* Provides default behaviours for Coord, i.e., coordinates.
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2013/12/23
* @since 2.5.0.1
*/
abstract public static class Coord implements Serializable {
private static final String JSON_COORD_LATITUDE = "lat";
private static final String JSON_COORD_LONGITUDE = "lon";
Coord() {
this.lat = Float.NaN;
this.lon = Float.NaN;
}
private final float lat;
private final float lon;
Coord(JSONObject jsonObj) {
this.lat = (float) jsonObj.optDouble(JSON_COORD_LATITUDE, Double.NaN);
this.lon = (float) jsonObj.optDouble(JSON_COORD_LONGITUDE, Double.NaN);
}
Coord() {
this.lat = Float.NaN;
this.lon = Float.NaN;
}
/**
* Tells if the latitude of the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public boolean hasLatitude() {
return !Float.isNaN(this.lat);
}
/**
* Tells if the longitude of the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public boolean hasLongitude() {
return !Float.isNaN(this.lon);
}
/**
* @return Latitude of the city if available, otherwise <code>Float.NaN</code>.
*/
public float getLatitude() {
return this.lat;
}
/**
* @return Longitude of the city if available, otherwise <code>Float.NaN</code>.
*/
public float getLongitude() {
return this.lon;
}
Coord(JSONObject jsonObj) {
this.lat = (float) jsonObj.optDouble(JSON_COORD_LATITUDE, Double.NaN);
this.lon = (float) jsonObj.optDouble(JSON_COORD_LONGITUDE, Double.NaN);
}
/**
* <p>
* Provides default behaviours for Main, i.e., main weather elements like temperature, humidity, etc.
* </p>
* Tells if the latitude of the city is available or not.
*
* @author Ashutosh Kumar Singh
* @version 2013/12/23
* @since 2.5.0.1
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
abstract public static class Main implements Serializable {
private static final String JSON_MAIN_TEMP = "temp";
private static final String JSON_MAIN_TEMP_MIN = "temp_min";
private static final String JSON_MAIN_TEMP_MAX = "temp_max";
private static final String JSON_MAIN_PRESSURE = "pressure";
private static final String JSON_MAIN_HUMIDITY = "humidity";
private final float temp;
private final float minTemp;
private final float maxTemp;
private final float pressure;
private final float humidity;
Main() {
this.temp = Float.NaN;
this.minTemp = Float.NaN;
this.maxTemp = Float.NaN;
this.pressure = Float.NaN;
this.humidity = Float.NaN;
}
Main(JSONObject jsonObj) {
this.temp = (float) jsonObj.optDouble(JSON_MAIN_TEMP, Double.NaN);
this.minTemp = (float) jsonObj.optDouble(JSON_MAIN_TEMP_MIN, Double.NaN);
this.maxTemp = (float) jsonObj.optDouble(JSON_MAIN_TEMP_MAX, Double.NaN);
this.pressure = (float) jsonObj.optDouble(JSON_MAIN_PRESSURE, Double.NaN);
this.humidity = (float) jsonObj.optDouble(JSON_MAIN_HUMIDITY, Double.NaN);
}
/**
* Tells if the temperature of the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public boolean hasTemperature() {
return !Float.isNaN(this.temp);
}
/**
* Tells if the minimum temperature of the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public boolean hasMinTemperature() {
return !Float.isNaN(this.minTemp);
}
/**
* Tells if the maximum temperature of the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public boolean hasMaxTemperature() {
return !Float.isNaN(this.maxTemp);
}
/**
* Tells if pressure of the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public boolean hasPressure() {
return !Float.isNaN(this.pressure);
}
/**
* Tells if humidity of the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public boolean hasHumidity() {
return !Float.isNaN(this.humidity);
}
/**
* @return Temperature of the city if available, otherwise <code>Float.NaN</code>.
*/
public float getTemperature() {
return this.temp;
}
/**
* @return Minimum temperature of the city if available, otherwise <code>Float.NaN</code>.
*/
public float getMinTemperature() {
return this.minTemp;
}
/**
* @return Maximum temperature of the city if available, otherwise <code>Float.NaN</code>.
*/
public float getMaxTemperature() {
return this.maxTemp;
}
/**
* @return Pressure of the city if available, otherwise <code>Float.NaN</code>.
*/
public float getPressure() {
return this.pressure;
}
/**
* @return Humidity of the city if available, otherwise <code>Float.NaN</code>.
*/
public float getHumidity() {
return this.humidity;
}
public boolean hasLatitude() {
return !Float.isNaN(this.lat);
}
/**
* <p>
* Parses weather data and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
* Tells if the longitude of the city is available or not.
*
* @author Ashutosh Kumar Singh
* @version 2014/12/27
* @since 2.5.0.3
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public static class Weather implements Serializable {
private static final String JSON_WEATHER_ID = "id";
private static final String JSON_WEATHER_MAIN = "main";
private static final String JSON_WEATHER_DESCRIPTION = "description";
private static final String JSON_WEATHER_ICON = "icon";
private final int id;
private final String name;
private final String description;
private final String icon;
Weather() {
this.id = Integer.MIN_VALUE;
this.name = null;
this.description = null;
this.icon = null;
}
Weather(JSONObject jsonObj) {
this.id = jsonObj.optInt(JSON_WEATHER_ID, Integer.MIN_VALUE);
this.name = jsonObj.optString(JSON_WEATHER_MAIN, null);
this.description = jsonObj.optString(JSON_WEATHER_DESCRIPTION, null);
this.icon = jsonObj.optString(JSON_WEATHER_ICON, null);
}
/**
* Tells if weather's code is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>.
*/
public boolean hasWeatherCode() {
return this.id != Integer.MIN_VALUE;
}
/**
* Tells if weather's name is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>.
*/
public boolean hasWeatherName() {
return this.name != null && (! "".equals(this.name));
}
/**
* Tells if weather's description is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>.
*/
public boolean hasWeatherDescription() {
return this.description != null && (! "".equals(this.description));
}
/**
* Tells if name of weather's icon is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>.
*/
public boolean hasWeatherIconName() {
return this.icon != null && (! "".equals(this.icon));
}
/**
* @return Code for weather of the city if available, otherwise <code>Integer.MIN_VALUE</code>.
*/
public int getWeatherCode() {
return this.id;
}
/**
* @return Name for weather of the city if available, otherwise <code>null</code>.
*/
public String getWeatherName() {
return this.name;
}
/**
* @return Description for weather of the city if available, otherwise <code>null</code>.
*/
public String getWeatherDescription() {
return this.description;
}
/**
* @return Name of icon for weather of the city if available, otherwise <code>null</code>.
*/
public String getWeatherIconName() {
return this.icon;
}
public boolean hasLongitude() {
return !Float.isNaN(this.lon);
}
/**
* <p>
* Provides default behaviours for Wind.
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2013/12/23
* @since 2.5.0.1
* @return Latitude of the city if available, otherwise <code>Float.NaN</code>.
*/
abstract public static class Wind implements Serializable {
private static final String JSON_WIND_SPEED = "speed";
private static final String JSON_WIND_DEGREE = "deg";
private final float speed;
private final float degree;
Wind() {
this.speed = Float.NaN;
this.degree = Float.NaN;
}
Wind(JSONObject jsonObj) {
this.speed = (float) jsonObj.optDouble(JSON_WIND_SPEED, Double.NaN);
this.degree = (float) jsonObj.optDouble(JSON_WIND_DEGREE, Double.NaN);
}
/**
* Tells if speed of wind in the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>.
*/
public boolean hasWindSpeed() {
return !Float.isNaN(this.speed);
}
/**
* Tells if degree (degree gives direction) of wind in the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>.
*/
public boolean hasWindDegree() {
return this.hasWindSpeed() && (! Float.isNaN(this.degree));
}
/**
* @return Speed of wind in the city if available, otherwise <code>Float.NaN</code>.
*/
public float getWindSpeed() {
return this.speed;
}
/**
* @return Degree of wind in the city if available, otherwise <code>Float.NaN</code>.
*/
public float getWindDegree() {
return this.degree;
}
public float getLatitude() {
return this.lat;
}
/**
* @return Longitude of the city if available, otherwise <code>Float.NaN</code>.
*/
public float getLongitude() {
return this.lon;
}
}
/**
* <p>
* Provides default behaviours for Main, i.e., main weather elements like temperature, humidity, etc.
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2013/12/23
* @since 2.5.0.1
*/
abstract public static class Main implements Serializable {
private static final String JSON_MAIN_TEMP = "temp";
private static final String JSON_MAIN_TEMP_MIN = "temp_min";
private static final String JSON_MAIN_TEMP_MAX = "temp_max";
private static final String JSON_MAIN_PRESSURE = "pressure";
private static final String JSON_MAIN_HUMIDITY = "humidity";
private final float temp;
private final float minTemp;
private final float maxTemp;
private final float pressure;
private final float humidity;
Main() {
this.temp = Float.NaN;
this.minTemp = Float.NaN;
this.maxTemp = Float.NaN;
this.pressure = Float.NaN;
this.humidity = Float.NaN;
}
Main(JSONObject jsonObj) {
this.temp = (float) jsonObj.optDouble(JSON_MAIN_TEMP, Double.NaN);
this.minTemp = (float) jsonObj.optDouble(JSON_MAIN_TEMP_MIN, Double.NaN);
this.maxTemp = (float) jsonObj.optDouble(JSON_MAIN_TEMP_MAX, Double.NaN);
this.pressure = (float) jsonObj.optDouble(JSON_MAIN_PRESSURE, Double.NaN);
this.humidity = (float) jsonObj.optDouble(JSON_MAIN_HUMIDITY, Double.NaN);
}
/**
* Tells if the temperature of the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public boolean hasTemperature() {
return !Float.isNaN(this.temp);
}
/**
* Tells if the minimum temperature of the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public boolean hasMinTemperature() {
return !Float.isNaN(this.minTemp);
}
/**
* Tells if the maximum temperature of the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public boolean hasMaxTemperature() {
return !Float.isNaN(this.maxTemp);
}
/**
* Tells if pressure of the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public boolean hasPressure() {
return !Float.isNaN(this.pressure);
}
/**
* Tells if humidity of the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>
*/
public boolean hasHumidity() {
return !Float.isNaN(this.humidity);
}
/**
* @return Temperature of the city if available, otherwise <code>Float.NaN</code>.
*/
public float getTemperature() {
return this.temp;
}
/**
* @return Minimum temperature of the city if available, otherwise <code>Float.NaN</code>.
*/
public float getMinTemperature() {
return this.minTemp;
}
/**
* @return Maximum temperature of the city if available, otherwise <code>Float.NaN</code>.
*/
public float getMaxTemperature() {
return this.maxTemp;
}
/**
* @return Pressure of the city if available, otherwise <code>Float.NaN</code>.
*/
public float getPressure() {
return this.pressure;
}
/**
* @return Humidity of the city if available, otherwise <code>Float.NaN</code>.
*/
public float getHumidity() {
return this.humidity;
}
}
/**
* <p>
* Parses weather data and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2014/12/27
* @since 2.5.0.3
*/
public static class Weather implements Serializable {
private static final String JSON_WEATHER_ID = "id";
private static final String JSON_WEATHER_MAIN = "main";
private static final String JSON_WEATHER_DESCRIPTION = "description";
private static final String JSON_WEATHER_ICON = "icon";
private final int id;
private final String name;
private final String description;
private final String icon;
Weather() {
this.id = Integer.MIN_VALUE;
this.name = null;
this.description = null;
this.icon = null;
}
Weather(JSONObject jsonObj) {
this.id = jsonObj.optInt(JSON_WEATHER_ID, Integer.MIN_VALUE);
this.name = jsonObj.optString(JSON_WEATHER_MAIN, null);
this.description = jsonObj.optString(JSON_WEATHER_DESCRIPTION, null);
this.icon = jsonObj.optString(JSON_WEATHER_ICON, null);
}
/**
* Tells if weather's code is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>.
*/
public boolean hasWeatherCode() {
return this.id != Integer.MIN_VALUE;
}
/**
* Tells if weather's name is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>.
*/
public boolean hasWeatherName() {
return this.name != null && (!"".equals(this.name));
}
/**
* Tells if weather's description is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>.
*/
public boolean hasWeatherDescription() {
return this.description != null && (!"".equals(this.description));
}
/**
* Tells if name of weather's icon is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>.
*/
public boolean hasWeatherIconName() {
return this.icon != null && (!"".equals(this.icon));
}
/**
* @return Code for weather of the city if available, otherwise <code>Integer.MIN_VALUE</code>.
*/
public int getWeatherCode() {
return this.id;
}
/**
* @return Name for weather of the city if available, otherwise <code>null</code>.
*/
public String getWeatherName() {
return this.name;
}
/**
* @return Description for weather of the city if available, otherwise <code>null</code>.
*/
public String getWeatherDescription() {
return this.description;
}
/**
* @return Name of icon for weather of the city if available, otherwise <code>null</code>.
*/
public String getWeatherIconName() {
return this.icon;
}
}
/**
* <p>
* Provides default behaviours for Wind.
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2013/12/23
* @since 2.5.0.1
*/
abstract public static class Wind implements Serializable {
private static final String JSON_WIND_SPEED = "speed";
private static final String JSON_WIND_DEGREE = "deg";
private final float speed;
private final float degree;
Wind() {
this.speed = Float.NaN;
this.degree = Float.NaN;
}
Wind(JSONObject jsonObj) {
this.speed = (float) jsonObj.optDouble(JSON_WIND_SPEED, Double.NaN);
this.degree = (float) jsonObj.optDouble(JSON_WIND_DEGREE, Double.NaN);
}
/**
* Tells if speed of windData in the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>.
*/
public boolean hasWindSpeed() {
return !Float.isNaN(this.speed);
}
/**
* Tells if degree (degree gives direction) of windData in the city is available or not.
*
* @return <code>true</code> if data available, otherwise <code>false</code>.
*/
public boolean hasWindDegree() {
return this.hasWindSpeed() && (!Float.isNaN(this.degree));
}
/**
* @return Speed of windData in the city if available, otherwise <code>Float.NaN</code>.
*/
public float getWindSpeed() {
return this.speed;
}
/**
* @return Degree of windData in the city if available, otherwise <code>Float.NaN</code>.
*/
public float getWindDegree() {
return this.degree;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,24 +1,21 @@
/*
* Copyright (c) 2013-2015 Ashutosh Kumar Singh <me@aksingh.net>
*
* 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.
*/
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis;
@ -48,44 +45,179 @@ import java.util.List;
*
* @author Ashutosh Kumar Singh
* @version 2014/12/27
* @see <a href="http://openweathermap.org/forecast">OWM's Weather Forecast API</a>
* @see <a href="https://openweathermap.org/forecast">OWM's Weather Data API</a>
* @since 2.5.0.3
*/
public class DailyForecast extends AbstractForecast {
/*
Instance variables
*/
private final List<Forecast> forecastList;
/*
Constructors
*/
DailyForecast(JSONObject jsonObj) {
super(jsonObj);
JSONArray dataArray = (jsonObj != null) ? jsonObj.optJSONArray(JSON_FORECAST_LIST) : new JSONArray();
this.forecastList = (dataArray != null) ? new ArrayList<Forecast>(dataArray.length()) : Collections.EMPTY_LIST;
if (dataArray != null && this.forecastList != Collections.EMPTY_LIST) {
for (int i = 0; i < dataArray.length(); i++) {
JSONObject forecastObj = dataArray.optJSONObject(i);
if (forecastObj != null) {
this.forecastList.add(new Forecast(forecastObj));
}
}
}
}
/**
* @param index Index of Data instance in the list.
* @return Data instance if available, otherwise <code>null</code>.
*/
public Forecast getForecastInstance(int index) {
return this.forecastList.get(index);
}
/**
* <p>
* Parses forecast data (one element in the forecastList) and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*/
public static class Forecast extends AbstractForecast.Forecast {
/*
Instance variables
JSON Keys
*/
private final List<Forecast> forecastList;
public static final String JSON_TEMP = "temp";
private static final String JSON_FORECAST_PRESSURE = "pressure";
private static final String JSON_FORECAST_HUMIDITY = "humidity";
private static final String JSON_FORECAST_WIND_SPEED = "speed";
private static final String JSON_FORECAST_WIND_DEGREE = "deg";
private static final String JSON_FORECAST_CLOUDS = "clouds";
private static final String JSON_FORECAST_RAIN = "rain";
private static final String JSON_FORECAST_SNOW = "snow";
/*
Instance Variables
*/
private final float pressure;
private final float humidity;
private final float windSpeed;
private final float windDegree;
private final float cloudsPercent;
private final float rain;
private final float snow;
private final Temperature temp;
/*
Constructors
*/
DailyForecast(JSONObject jsonObj) {
super(jsonObj);
Forecast() {
super();
JSONArray dataArray = (jsonObj != null) ? jsonObj.optJSONArray(JSON_FORECAST_LIST) : new JSONArray();
this.forecastList = (dataArray != null) ? new ArrayList<Forecast>(dataArray.length()) : Collections.EMPTY_LIST;
if (dataArray != null && this.forecastList != Collections.EMPTY_LIST) {
for (int i = 0; i < dataArray.length(); i++) {
JSONObject forecastObj = dataArray.optJSONObject(i);
if (forecastObj != null) {
this.forecastList.add(new Forecast(forecastObj));
}
}
}
this.pressure = Float.NaN;
this.humidity = Float.NaN;
this.windSpeed = Float.NaN;
this.windDegree = Float.NaN;
this.cloudsPercent = Float.NaN;
this.rain = Float.NaN;
this.snow = Float.NaN;
this.temp = new Temperature();
}
/**
* @param index Index of Forecast instance in the list.
* @return Forecast instance if available, otherwise <code>null</code>.
*/
public Forecast getForecastInstance(int index) {
return this.forecastList.get(index);
Forecast(JSONObject jsonObj) {
super(jsonObj);
JSONObject jsonObjTemp = (jsonObj != null) ? jsonObj.optJSONObject(JSON_TEMP) : null;
this.temp = (jsonObjTemp != null) ? new Temperature(jsonObjTemp) : new Temperature();
this.humidity = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_HUMIDITY, Double.NaN) : Float.NaN;
this.pressure = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_PRESSURE, Double.NaN) : Float.NaN;
this.windSpeed = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_WIND_SPEED, Double.NaN) : Float.NaN;
this.windDegree = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_WIND_DEGREE, Double.NaN) : Float.NaN;
this.cloudsPercent = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_CLOUDS, Double.NaN) : Float.NaN;
this.rain = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_RAIN, Double.NaN) : Float.NaN;
this.snow = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_SNOW, Double.NaN) : Float.NaN;
}
public boolean hasHumidity() {
return !Float.isNaN(this.humidity);
}
public boolean hasPressure() {
return !Float.isNaN(this.pressure);
}
public boolean hasWindSpeed() {
return !Float.isNaN(this.windSpeed);
}
public boolean hasWindDegree() {
return !Float.isNaN(this.windDegree);
}
public boolean hasPercentageOfClouds() {
return !Float.isNaN(this.cloudsPercent);
}
public boolean hasRain() {
return !Float.isNaN(this.rain);
}
public boolean hasSnow() {
return !Float.isNaN(this.snow);
}
public float getHumidity() {
return this.humidity;
}
public float getPressure() {
return this.pressure;
}
public float getWindSpeed() {
return this.windSpeed;
}
public float getWindDegree() {
return this.windDegree;
}
public float getPercentageOfClouds() {
return this.cloudsPercent;
}
public float getRain() {
return this.rain;
}
public float getSnow() {
return this.snow;
}
public Temperature getTemperatureInstance() {
return this.temp;
}
/**
* <p>
* Parses forecast data (one element in the forecastList) and provides methods to get/access the same information.
* Parses temperature data and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
@ -99,221 +231,86 @@ public class DailyForecast extends AbstractForecast {
* Others: <code>null</code>
* </p>
*/
public static class Forecast extends AbstractForecast.Forecast {
/*
JSON Keys
*/
public static final String JSON_TEMP = "temp";
public static class Temperature implements Serializable {
private static final String JSON_TEMP_DAY = "day";
private static final String JSON_TEMP_MIN = "min";
private static final String JSON_TEMP_MAX = "max";
private static final String JSON_TEMP_NIGHT = "night";
private static final String JSON_TEMP_EVENING = "eve";
private static final String JSON_TEMP_MORNING = "morn";
private static final String JSON_FORECAST_PRESSURE = "pressure";
private static final String JSON_FORECAST_HUMIDITY = "humidity";
private static final String JSON_FORECAST_WIND_SPEED = "speed";
private static final String JSON_FORECAST_WIND_DEGREE = "deg";
private static final String JSON_FORECAST_CLOUDS = "clouds";
private static final String JSON_FORECAST_RAIN = "rain";
private static final String JSON_FORECAST_SNOW = "snow";
private final float dayTemp;
private final float minTemp;
private final float maxTemp;
private final float nightTemp;
private final float eveTemp;
private final float mornTemp;
/*
Instance Variables
*/
private final float pressure;
private final float humidity;
private final float windSpeed;
private final float windDegree;
private final float cloudsPercent;
private final float rain;
private final float snow;
Temperature() {
this.dayTemp = Float.NaN;
this.minTemp = Float.NaN;
this.maxTemp = Float.NaN;
this.nightTemp = Float.NaN;
this.eveTemp = Float.NaN;
this.mornTemp = Float.NaN;
}
private final Temperature temp;
Temperature(JSONObject jsonObj) {
this.dayTemp = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_TEMP_DAY, Double.NaN) : Float.NaN;
this.minTemp = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_TEMP_MIN, Double.NaN) : Float.NaN;
this.maxTemp = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_TEMP_MAX, Double.NaN) : Float.NaN;
this.nightTemp = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_TEMP_NIGHT, Double.NaN) : Float.NaN;
this.eveTemp = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_TEMP_EVENING, Double.NaN) : Float.NaN;
this.mornTemp = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_TEMP_MORNING, Double.NaN) : Float.NaN;
}
/*
Constructors
*/
Forecast() {
super();
public boolean hasDayTemperature() {
return !Float.isNaN(this.dayTemp);
}
this.pressure = Float.NaN;
this.humidity = Float.NaN;
this.windSpeed = Float.NaN;
this.windDegree = Float.NaN;
this.cloudsPercent = Float.NaN;
this.rain = Float.NaN;
this.snow = Float.NaN;
public boolean hasMinimumTemperature() {
return !Float.isNaN(this.minTemp);
}
this.temp = new Temperature();
}
public boolean hasMaximumTemperature() {
return !Float.isNaN(this.maxTemp);
}
Forecast(JSONObject jsonObj) {
super(jsonObj);
public boolean hasNightTemperature() {
return !Float.isNaN(this.nightTemp);
}
JSONObject jsonObjTemp = (jsonObj != null) ? jsonObj.optJSONObject(JSON_TEMP) : null;
this.temp = (jsonObjTemp != null) ? new Temperature(jsonObjTemp) : new Temperature();
public boolean hasEveningTemperature() {
return !Float.isNaN(this.eveTemp);
}
this.humidity = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_HUMIDITY, Double.NaN) : Float.NaN;
this.pressure = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_PRESSURE, Double.NaN) : Float.NaN;
this.windSpeed = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_WIND_SPEED, Double.NaN) : Float.NaN;
this.windDegree = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_WIND_DEGREE, Double.NaN) : Float.NaN;
this.cloudsPercent = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_CLOUDS, Double.NaN) : Float.NaN;
this.rain = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_RAIN, Double.NaN) : Float.NaN;
this.snow = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_FORECAST_SNOW, Double.NaN) : Float.NaN;
}
public boolean hasMorningTemperature() {
return !Float.isNaN(this.mornTemp);
}
public boolean hasHumidity() {
return !Float.isNaN(this.humidity);
}
public float getDayTemperature() {
return this.dayTemp;
}
public boolean hasPressure() {
return !Float.isNaN(this.pressure);
}
public float getMinimumTemperature() {
return this.minTemp;
}
public boolean hasWindSpeed() {
return !Float.isNaN(this.windSpeed);
}
public float getMaximumTemperature() {
return this.maxTemp;
}
public boolean hasWindDegree() {
return !Float.isNaN(this.windDegree);
}
public float getNightTemperature() {
return this.nightTemp;
}
public boolean hasPercentageOfClouds() {
return !Float.isNaN(this.cloudsPercent);
}
public float getEveningTemperature() {
return this.eveTemp;
}
public boolean hasRain() {
return !Float.isNaN(this.rain);
}
public boolean hasSnow() {
return !Float.isNaN(this.snow);
}
public float getHumidity() {
return this.humidity;
}
public float getPressure() {
return this.pressure;
}
public float getWindSpeed() {
return this.windSpeed;
}
public float getWindDegree() {
return this.windDegree;
}
public float getPercentageOfClouds() {
return this.cloudsPercent;
}
public float getRain() {
return this.rain;
}
public float getSnow() {
return this.snow;
}
public Temperature getTemperatureInstance() {
return this.temp;
}
/**
* <p>
* Parses temperature data and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*/
public static class Temperature implements Serializable {
private static final String JSON_TEMP_DAY = "day";
private static final String JSON_TEMP_MIN = "min";
private static final String JSON_TEMP_MAX = "max";
private static final String JSON_TEMP_NIGHT = "night";
private static final String JSON_TEMP_EVENING = "eve";
private static final String JSON_TEMP_MORNING = "morn";
private final float dayTemp;
private final float minTemp;
private final float maxTemp;
private final float nightTemp;
private final float eveTemp;
private final float mornTemp;
Temperature() {
this.dayTemp = Float.NaN;
this.minTemp = Float.NaN;
this.maxTemp = Float.NaN;
this.nightTemp = Float.NaN;
this.eveTemp = Float.NaN;
this.mornTemp = Float.NaN;
}
Temperature(JSONObject jsonObj) {
this.dayTemp = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_TEMP_DAY, Double.NaN) : Float.NaN;
this.minTemp = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_TEMP_MIN, Double.NaN) : Float.NaN;
this.maxTemp = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_TEMP_MAX, Double.NaN) : Float.NaN;
this.nightTemp = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_TEMP_NIGHT, Double.NaN) : Float.NaN;
this.eveTemp = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_TEMP_EVENING, Double.NaN) : Float.NaN;
this.mornTemp = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_TEMP_MORNING, Double.NaN) : Float.NaN;
}
public boolean hasDayTemperature() {
return !Float.isNaN(this.dayTemp);
}
public boolean hasMinimumTemperature() {
return !Float.isNaN(this.minTemp);
}
public boolean hasMaximumTemperature() {
return !Float.isNaN(this.maxTemp);
}
public boolean hasNightTemperature() {
return !Float.isNaN(this.nightTemp);
}
public boolean hasEveningTemperature() {
return !Float.isNaN(this.eveTemp);
}
public boolean hasMorningTemperature() {
return !Float.isNaN(this.mornTemp);
}
public float getDayTemperature() {
return this.dayTemp;
}
public float getMinimumTemperature() {
return this.minTemp;
}
public float getMaximumTemperature() {
return this.maxTemp;
}
public float getNightTemperature() {
return this.nightTemp;
}
public float getEveningTemperature() {
return this.eveTemp;
}
public float getMorningTemperature() {
return this.mornTemp;
}
}
public float getMorningTemperature() {
return this.mornTemp;
}
}
}
}

View file

@ -1,24 +1,21 @@
/*
* Copyright (c) 2013-2015 Ashutosh Kumar Singh <me@aksingh.net>
*
* 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.
*/
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis;
@ -48,44 +45,162 @@ import java.util.List;
*
* @author Ashutosh Kumar Singh
* @version 2014/12/27
* @see <a href="http://openweathermap.org/forecast">OWM's Weather Forecast API</a>
* @see <a href="https://openweathermap.org/forecast">OWM's Weather Data API</a>
* @since 2.5.0.3
*/
public class HourlyForecast extends AbstractForecast {
/*
Instance variables
*/
private final List<Forecast> forecastList;
/*
Constructor
*/
HourlyForecast(JSONObject jsonObj) {
super(jsonObj);
JSONArray forecastArr = (jsonObj != null) ? jsonObj.optJSONArray(this.JSON_FORECAST_LIST) : new JSONArray();
this.forecastList = (forecastArr != null) ? new ArrayList<Forecast>(forecastArr.length()) : Collections.EMPTY_LIST;
if (forecastArr != null && this.forecastList != Collections.EMPTY_LIST) {
for (int i = 0; i < forecastArr.length(); i++) {
JSONObject forecastObj = forecastArr.optJSONObject(i);
if (forecastObj != null) {
this.forecastList.add(new Forecast(forecastObj));
}
}
}
}
/**
* @param index Index of Data instance in the list.
* @return Data instance if available, otherwise <code>null</code>.
*/
public Forecast getForecastInstance(int index) {
return this.forecastList.get(index);
}
/**
* <p>
* Parses forecast data (one element in the forecastList) and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*/
public static class Forecast extends AbstractForecast.Forecast {
/*
Instance variables
JSON Keys
*/
private final List<Forecast> forecastList;
private static final String JSON_SYS = "sys";
private static final String JSON_DT_TEXT = "dt_txt";
/*
Instance Variables
*/
private final String dateTimeText;
private final Clouds clouds;
private final Main main;
private final Sys sys;
private final Wind wind;
/*
Constructor
*/
HourlyForecast(JSONObject jsonObj) {
super(jsonObj);
Forecast(JSONObject jsonObj) {
super(jsonObj);
JSONArray forecastArr = (jsonObj != null) ? jsonObj.optJSONArray(this.JSON_FORECAST_LIST) : new JSONArray();
this.forecastList = (forecastArr != null) ? new ArrayList<Forecast>(forecastArr.length()) : Collections.EMPTY_LIST;
if (forecastArr != null && this.forecastList != Collections.EMPTY_LIST) {
for (int i = 0; i < forecastArr.length(); i++) {
JSONObject forecastObj = forecastArr.optJSONObject(i);
if (forecastObj != null) {
this.forecastList.add(new Forecast(forecastObj));
}
}
}
this.dateTimeText = (jsonObj != null) ? jsonObj.optString(JSON_DT_TEXT, null) : null;
JSONObject jsonObjClouds = (jsonObj != null) ? jsonObj.optJSONObject(JSON_CLOUDS) : null;
this.clouds = (jsonObjClouds != null) ? new Clouds(jsonObjClouds) : null;
JSONObject jsonObjMain = (jsonObj != null) ? jsonObj.optJSONObject(JSON_MAIN) : null;
this.main = (jsonObjMain != null) ? new Main(jsonObjMain) : null;
JSONObject jsonObjSys = (jsonObj != null) ? jsonObj.optJSONObject(JSON_SYS) : null;
this.sys = (jsonObjSys != null) ? new Sys(jsonObjSys) : null;
JSONObject jsonObjWind = (jsonObj != null) ? jsonObj.optJSONObject(JSON_WIND) : null;
this.wind = (jsonObjWind != null) ? new Wind(jsonObjWind) : null;
}
public boolean hasDateTimeText() {
return this.dateTimeText != null;
}
/**
* @param index Index of Forecast instance in the list.
* @return Forecast instance if available, otherwise <code>null</code>.
* @return <code>true</code> if Cloud instance is available, otherwise <code>false</code>.
*/
public Forecast getForecastInstance(int index) {
return this.forecastList.get(index);
public boolean hasCloudsInstance() {
return clouds != null;
}
/**
* @return <code>true</code> if Main instance is available, otherwise <code>false</code>.
*/
public boolean hasMainInstance() {
return main != null;
}
/**
* @return <code>true</code> if System instance is available, otherwise <code>false</code>.
*/
public boolean hasSysInstance() {
return sys != null;
}
/**
* @return <code>true</code> if Wind instance is available, otherwise <code>false</code>.
*/
public boolean hasWindInstance() {
return wind != null;
}
public String getDateTimeText() {
return this.dateTimeText;
}
/**
* @return Cloud instance if available, otherwise <code>null</code>.
*/
public Clouds getCloudsInstance() {
return this.clouds;
}
/**
* @return Main instance if available, otherwise <code>null</code>.
*/
public Main getMainInstance() {
return this.main;
}
/**
* @return System instance if available, otherwise <code>null</code>.
*/
public Sys getSysInstance() {
return this.sys;
}
/**
* @return Wind instance if available, otherwise <code>null</code>.
*/
public Wind getWindInstance() {
return this.wind;
}
/**
* <p>
* Parses forecast data (one element in the forecastList) and provides methods to get/access the same information.
* Parses clouds data and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
@ -98,281 +213,163 @@ public class HourlyForecast extends AbstractForecast {
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2014/12/26
* @since 2.5.0.1
*/
public static class Forecast extends AbstractForecast.Forecast {
/*
JSON Keys
*/
private static final String JSON_SYS = "sys";
private static final String JSON_DT_TEXT = "dt_txt";
public static class Clouds extends AbstractForecast.Forecast.Clouds {
/*
Instance Variables
*/
private final String dateTimeText;
Clouds() {
super();
}
private final Clouds clouds;
private final Main main;
private final Sys sys;
private final Wind wind;
/*
Constructor
*/
Forecast(JSONObject jsonObj) {
super(jsonObj);
this.dateTimeText = (jsonObj != null) ? jsonObj.optString(JSON_DT_TEXT, null) : null;
JSONObject jsonObjClouds = (jsonObj != null) ? jsonObj.optJSONObject(JSON_CLOUDS) : null;
this.clouds = (jsonObjClouds != null) ? new Clouds(jsonObjClouds) : null;
JSONObject jsonObjMain = (jsonObj != null) ? jsonObj.optJSONObject(JSON_MAIN) : null;
this.main = (jsonObjMain != null) ? new Main(jsonObjMain) : null;
JSONObject jsonObjSys = (jsonObj != null) ? jsonObj.optJSONObject(JSON_SYS) : null;
this.sys = (jsonObjSys != null) ? new Sys(jsonObjSys) : null;
JSONObject jsonObjWind = (jsonObj != null) ? jsonObj.optJSONObject(JSON_WIND) : null;
this.wind = (jsonObjWind != null) ? new Wind(jsonObjWind) : null;
}
public boolean hasDateTimeText() {
return this.dateTimeText != null;
}
/**
* @return <code>true</code> if Clouds instance is available, otherwise <code>false</code>.
*/
public boolean hasCloudsInstance() {
return clouds != null;
}
/**
* @return <code>true</code> if Main instance is available, otherwise <code>false</code>.
*/
public boolean hasMainInstance() {
return main != null;
}
/**
* @return <code>true</code> if Sys instance is available, otherwise <code>false</code>.
*/
public boolean hasSysInstance() {
return sys != null;
}
/**
* @return <code>true</code> if Wind instance is available, otherwise <code>false</code>.
*/
public boolean hasWindInstance() {
return wind != null;
}
public String getDateTimeText() {
return this.dateTimeText;
}
/**
* @return Clouds instance if available, otherwise <code>null</code>.
*/
public Clouds getCloudsInstance() {
return this.clouds;
}
/**
* @return Main instance if available, otherwise <code>null</code>.
*/
public Main getMainInstance() {
return this.main;
}
/**
* @return Sys instance if available, otherwise <code>null</code>.
*/
public Sys getSysInstance() {
return this.sys;
}
/**
* @return Wind instance if available, otherwise <code>null</code>.
*/
public Wind getWindInstance() {
return this.wind;
}
/**
* <p>
* Parses clouds data and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2014/12/26
* @since 2.5.0.1
*/
public static class Clouds extends AbstractForecast.Forecast.Clouds {
Clouds() {
super();
}
Clouds(JSONObject jsonObj) {
super(jsonObj);
}
}
/**
* <p>
* Parses main data and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2014/12/26
* @since 2.5.0.1
*/
public static class Main extends AbstractForecast.Forecast.Main {
private static final String JSON_MAIN_SEA_LEVEL = "sea_level";
private static final String JSON_MAIN_GRND_LEVEL = "grnd_level";
private static final String JSON_MAIN_TMP_KF = "temp_kf";
private final float seaLevel;
private final float groundLevel;
private final float tempKF;
Main() {
super();
this.seaLevel = Float.NaN;
this.groundLevel = Float.NaN;
this.tempKF = Float.NaN;
}
Main(JSONObject jsonObj) {
super(jsonObj);
this.seaLevel = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_MAIN_SEA_LEVEL, Float.NaN) : Float.NaN;
this.groundLevel = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_MAIN_GRND_LEVEL, Float.NaN) : Float.NaN;
this.tempKF = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_MAIN_TMP_KF, Float.NaN) : Float.NaN;
}
public boolean hasSeaLevel() {
return !Float.isNaN(this.seaLevel);
}
public boolean hasGroundLevel() {
return !Float.isNaN(this.groundLevel);
}
public boolean hasTempKF() {
return !Float.isNaN(this.tempKF);
}
public float getSeaLevel() {
return this.seaLevel;
}
public float getGroundLevel() {
return this.groundLevel;
}
public float getTempKF() {
return this.tempKF;
}
}
/**
* <p>
* Parses sys data and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2014/12/26
* @since 2.5.0.1
*/
public static class Sys implements Serializable {
private static final String JSON_SYS_POD = "pod";
private final String pod;
Sys() {
this.pod = null;
}
Sys(JSONObject jsonObj) {
this.pod = (jsonObj != null) ? jsonObj.optString(JSON_SYS_POD, null) : null;
}
public boolean hasPod() {
return this.pod != null && (! "".equals(this.pod));
}
public String getPod() {
return this.pod;
}
}
/**
* <p>
* Parses wind data and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2014/12/26
* @since 2.5.0.1
*/
public static class Wind extends AbstractWeather.Wind {
Wind() {
super();
}
Wind(JSONObject jsonObj) {
super(jsonObj);
}
}
Clouds(JSONObject jsonObj) {
super(jsonObj);
}
}
/**
* <p>
* Parses main data and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2014/12/26
* @since 2.5.0.1
*/
public static class Main extends AbstractForecast.Forecast.Main {
private static final String JSON_MAIN_SEA_LEVEL = "sea_level";
private static final String JSON_MAIN_GRND_LEVEL = "grnd_level";
private static final String JSON_MAIN_TMP_KF = "temp_kf";
private final float seaLevel;
private final float groundLevel;
private final float tempKF;
Main() {
super();
this.seaLevel = Float.NaN;
this.groundLevel = Float.NaN;
this.tempKF = Float.NaN;
}
Main(JSONObject jsonObj) {
super(jsonObj);
this.seaLevel = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_MAIN_SEA_LEVEL, Float.NaN) : Float.NaN;
this.groundLevel = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_MAIN_GRND_LEVEL, Float.NaN) : Float.NaN;
this.tempKF = (jsonObj != null) ? (float) jsonObj.optDouble(JSON_MAIN_TMP_KF, Float.NaN) : Float.NaN;
}
public boolean hasSeaLevel() {
return !Float.isNaN(this.seaLevel);
}
public boolean hasGroundLevel() {
return !Float.isNaN(this.groundLevel);
}
public boolean hasTempKF() {
return !Float.isNaN(this.tempKF);
}
public float getSeaLevel() {
return this.seaLevel;
}
public float getGroundLevel() {
return this.groundLevel;
}
public float getTempKF() {
return this.tempKF;
}
}
/**
* <p>
* Parses sys data and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2014/12/26
* @since 2.5.0.1
*/
public static class Sys implements Serializable {
private static final String JSON_SYS_POD = "pod";
private final String pod;
Sys() {
this.pod = null;
}
Sys(JSONObject jsonObj) {
this.pod = (jsonObj != null) ? jsonObj.optString(JSON_SYS_POD, null) : null;
}
public boolean hasPod() {
return this.pod != null && (!"".equals(this.pod));
}
public String getPod() {
return this.pod;
}
}
/**
* <p>
* Parses windData data and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Boolean: <code>false</code>
* Integral: Minimum value (MIN_VALUE)
* Floating point: Not a number (NaN)
* Others: <code>null</code>
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2014/12/26
* @since 2.5.0.1
*/
public static class Wind extends AbstractWeather.Wind {
Wind() {
super();
}
Wind(JSONObject jsonObj) {
super(jsonObj);
}
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,24 +1,21 @@
/*
* Copyright (c) 2013-2015 Ashutosh Kumar Singh <me@aksingh.net>
*
* 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.
*/
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis;
@ -32,60 +29,63 @@ package net.aksingh.owmjapis;
* @since 2.5.0.1
*/
public class Tools {
/**
* <p>
* Converts degree to direction.
* </p>
*
* @param degree Degree of wind as received from OWM.org
* @return Direction
* @throws IllegalArgumentException Degree should be between 0 and 360.
*/
public String convertDegree2Direction(float degree)
throws IllegalArgumentException {
String direction;
/**
* <p>
* Converts degree to direction.
* </p>
*
* @param degree Degree of wind as received from OpenWeatherMap.org
* @return Direction
* @throws IllegalArgumentException Degree should be between 0 and 360.
* @deprecated As of version 2.5.1 and will be removed in version 2.5.2,
* use {@link net.aksingh.owmjapis.util.ConversionTools.convertDegree2DirectionCode} instead.
*/
@Deprecated
public String convertDegree2Direction(float degree)
throws IllegalArgumentException {
String direction;
// degree should be between 0 and 360
if ((degree < 0.0f) || (degree > 360.0f)) {
throw new IllegalArgumentException("Degree cannot be less than 0 or more than 360.");
}
if (degree <= 11.25f) {
direction = "N";
} else if (degree <= 33.75f) {
direction = "NNE";
} else if (degree <= 56.25f) {
direction = "NE";
} else if (degree <= 78.75f) {
direction = "ENE";
} else if (degree <= 101.25f) {
direction = "E";
} else if (degree <= 123.75f) {
direction = "ESE";
} else if (degree <= 146.25f) {
direction = "SE";
} else if (degree <= 168.75f) {
direction = "SSE";
} else if (degree <= 191.25f) {
direction = "S";
} else if (degree <= 213.75f) {
direction = "SSW";
} else if (degree <= 236.25f) {
direction = "SW";
} else if (degree <= 258.75f) {
direction = "WSW";
} else if (degree <= 281.25f) {
direction = "W";
} else if (degree <= 303.75f) {
direction = "WNW";
} else if (degree <= 326.25f) {
direction = "NW";
} else if (degree <= 348.75f) {
direction = "NNW";
} else {
direction = "N";
}
return direction;
// degree should be between 0 and 360
if ((degree < 0.0f) || (degree > 360.0f)) {
throw new IllegalArgumentException("Degree cannot be less than 0 or more than 360.");
}
if (degree <= 11.25f) {
direction = "N";
} else if (degree <= 33.75f) {
direction = "NNE";
} else if (degree <= 56.25f) {
direction = "NE";
} else if (degree <= 78.75f) {
direction = "ENE";
} else if (degree <= 101.25f) {
direction = "E";
} else if (degree <= 123.75f) {
direction = "ESE";
} else if (degree <= 146.25f) {
direction = "SE";
} else if (degree <= 168.75f) {
direction = "SSE";
} else if (degree <= 191.25f) {
direction = "S";
} else if (degree <= 213.75f) {
direction = "SSW";
} else if (degree <= 236.25f) {
direction = "SW";
} else if (degree <= 258.75f) {
direction = "WSW";
} else if (degree <= 281.25f) {
direction = "W";
} else if (degree <= 303.75f) {
direction = "WNW";
} else if (degree <= 326.25f) {
direction = "NW";
} else if (degree <= 348.75f) {
direction = "NNW";
} else {
direction = "N";
}
return direction;
}
}

View file

@ -0,0 +1,30 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.api
class APIException(val code: Int, val info: String) : Exception() {
override val message: String?
get() = createMessage()
fun createMessage(): String {
return "API call gave error: " + code + " - " + info
}
}

View file

@ -0,0 +1,67 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.api
import net.aksingh.owmjapis.model.CurrentWeather
import net.aksingh.owmjapis.model.CurrentWeatherList
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface CurrentWeatherAPI {
@GET("weather")
fun getCurrentWeatherByCityName(
@Query("q") name: String
): Call<CurrentWeather>
@GET("weather")
fun getCurrentWeatherByCityId(
@Query("id") id: Int
): Call<CurrentWeather>
@GET("weather")
fun getCurrentWeatherByCoords(
@Query("lat") lat: Float,
@Query("lon") lon: Float
): Call<CurrentWeather>
@GET("weather")
fun getCurrentWeatherByZipCode(
@Query("zip") zip: String
): Call<CurrentWeather>
@GET("weather")
fun getCurrentWeatherListInZone(
@Query("bbox") box: String
): Call<CurrentWeatherList>
@GET("weather")
fun getCurrentWeatherListInCycle(
@Query("lat") lat: Float,
@Query("lon") lon: Float,
@Query("cnt") count: Short
): Call<CurrentWeatherList>
@GET("weather")
fun getCurrentWeatherListByCityId(
@Query("id") ids: String
): Call<CurrentWeatherList>
}

View file

@ -0,0 +1,53 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.api
import net.aksingh.owmjapis.model.DailyForecast
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface DailyForecastAPI {
@GET("forecast/daily")
fun getDailyForecastByCityName(
@Query("q") name: String,
@Query("cnt") count: Byte
): Call<DailyForecast>
@GET("forecast/daily")
fun getDailyForecastByCityId(
@Query("id") id: Int,
@Query("cnt") count: Byte
): Call<DailyForecast>
@GET("forecast/daily")
fun getDailyForecastByCoords(
@Query("lat") lat: Float,
@Query("lon") lon: Float,
@Query("cnt") count: Byte
): Call<DailyForecast>
@GET("forecast/daily")
fun getDailyForecastByZipCode(
@Query("zip") zip: String,
@Query("cnt") count: Byte
): Call<DailyForecast>
}

View file

@ -0,0 +1,49 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.api
import net.aksingh.owmjapis.model.HourlyForecast
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface HourlyForecastAPI {
@GET("forecast")
fun getHourlyForecastByCityName(
@Query("q") name: String
): Call<HourlyForecast>
@GET("forecast")
fun getHourlyForecastByCityId(
@Query("id") id: Int
): Call<HourlyForecast>
@GET("forecast")
fun getHourlyForecastByCoords(
@Query("lat") lat: Float,
@Query("lon") lon: Float
): Call<HourlyForecast>
@GET("forecast")
fun getHourlyForecastByZipCode(
@Query("zip") zip: String
): Call<HourlyForecast>
}

View file

@ -0,0 +1,873 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.core
import com.google.gson.GsonBuilder
import net.aksingh.owmjapis.api.APIException
import net.aksingh.owmjapis.api.CurrentWeatherAPI
import net.aksingh.owmjapis.api.DailyForecastAPI
import net.aksingh.owmjapis.api.HourlyForecastAPI
import net.aksingh.owmjapis.model.CurrentWeather
import net.aksingh.owmjapis.model.DailyForecast
import net.aksingh.owmjapis.model.HourlyForecast
import net.aksingh.owmjapis.util.OkHttpTools
import net.aksingh.owmjapis.util.SystemTools
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.net.InetSocketAddress
import java.net.Proxy
/**
* **Starting point for this lib.** If you're new to this API, start from this class.
*
* Lets you access data from OpenWeatherMap.org using its Weather APIs.
*
* **Sample code in Java:**
* `OWM owm = new OWM("your-api-key");`
*
* **Sample code in Kotlin:**
* `owm: OWM = OWM("your-api-key")`
*
* [OpenWeatherMap.org](https://openweathermap.org/)
* [OpenWeatherMap.org APIs](https://openweathermap.org/api/)
*
* @author Ashutosh Kumar Singh
* @version 2017-11-07
*
* @since 2.5.1.0
*/
class OWM {
private val OWM_25_BASE_URL: String = "https://api.openweathermap.org/data/2.5/"
private val OWM_25_DAILY_FORECAST_MAX_COUNT: Byte = 16
private var apiKey: String
set(value) {
if (value.isEmpty() || value.isBlank()) {
throw IllegalArgumentException("API key can't be empty/blank. Kindly get an API key from OpenWeatherMap.org")
}
field = value
}
private var accuracy: OWM.Accuracy
private var unit: OWM.Unit
private var lang: OWM.Language
private var proxy: Proxy
private var retrofit: Retrofit
/**
* Constructor
*
* Defaults: Search accuracy is set to like
* Defaults: Unit is set to standard
* Defaults: Language is set to English
* Defaults: Proxy is set to system's proxy
*
* [OpenWeatherMap.org API key](https://openweathermap.org/appid)
*
* @param apiKey API key from OpenWeatherMap.org
*/
constructor(apiKey: String) {
this.apiKey = apiKey
this.accuracy = OWM.Accuracy.LIKE
this.unit = OWM.Unit.STANDARD
this.lang = OWM.Language.ENGLISH
this.proxy = SystemTools.getSystemProxy()
this.retrofit = createRetrofitInstance(this.proxy)
}
/**
* Set search accuracy for getting data from OpenWeatherMap.org
*
* @param accuracy Search accuracy
*/
fun setAccuracy(accuracy: OWM.Accuracy): OWM {
this.accuracy = accuracy
this.retrofit = createRetrofitInstance(this.proxy)
return this
}
/**
* Set unit for getting data from OpenWeatherMap.org
*
* @param unit Unit
*/
fun setUnit(unit: OWM.Unit): OWM {
this.unit = unit
this.retrofit = createRetrofitInstance(this.proxy)
return this
}
/**
* Set language for getting data from OpenWeatherMap.org
*
* @param lang Language
*/
fun setLanguage(lang: OWM.Language): OWM {
this.lang = lang
this.retrofit = createRetrofitInstance(this.proxy)
return this
}
/**
* Set proxy for getting data from OpenWeatherMap.org
*
* @param proxy Proxy
*/
fun setProxy(proxy: Proxy): OWM {
this.retrofit = createRetrofitInstance(proxy)
return this
}
/**
* Set authenticated proxy for getting data from OpenWeatherMap.org
*
* @param proxy Proxy
* @param user User name for the proxy
* @param pass Password for the proxy
*/
fun setProxy(proxy: Proxy, user: String, pass: String): OWM {
setProxy(proxy)
SystemTools.setProxyAuthDetails(user, pass)
return this
}
/**
* Set HTTP proxy for getting data from OpenWeatherMap.org
*
* @param host Host address of the proxy
* @param port Port address of the proxy
*/
fun setProxy(host: String, port: Int): OWM {
setProxy(host, port, Proxy.Type.HTTP)
return this
}
/**
* Set proxy of any type for getting data from OpenWeatherMap.org
*
* @param host Host address of the proxy
* @param port Port address of the proxy
* @param type Type of the proxy
*/
fun setProxy(host: String, port: Int, type: Proxy.Type): OWM {
proxy = Proxy(type, InetSocketAddress(host, port))
setProxy(proxy)
return this
}
/**
* Set authenticated HTTP proxy for getting data from OpenWeatherMap.org
*
* @param host Host address of the proxy
* @param port Port address of the proxy
* @param user User name for the proxy if required
* @param pass Password for the proxy if required
*/
fun setProxy(host: String, port: Int, user: String, pass: String): OWM {
setProxy(host, port, user, pass, Proxy.Type.HTTP)
return this
}
/**
* Set authenticated proxy of any type for getting data from OpenWeatherMap.org
*
* @param host Host address of the proxy
* @param port Port address of the proxy
* @param user User name for the proxy if required
* @param pass Password for the proxy if required
* @param type Type of the proxy
*/
fun setProxy(host: String, port: Int, user: String, pass: String, type: Proxy.Type): OWM {
setProxy(host, port, type)
SystemTools.setProxyAuthDetails(user, pass)
return this
}
/**
* Remove proxy (i.e., direct connection) for getting data from OpenWeatherMap.org
*/
fun setNoProxy(): OWM {
setProxy(Proxy.NO_PROXY)
return this
}
/**
* Reset proxy to system's proxy for getting data from OpenWeatherMap.org
*/
fun resetProxy() {
setProxy(SystemTools.getSystemProxy())
SystemTools.setProxyAuthDetails("", "")
}
@Throws(APIException::class)
fun currentWeatherByCityName(cityName: String): CurrentWeather {
val api = retrofit.create(CurrentWeatherAPI::class.java)
val apiCall = api.getCurrentWeatherByCityName(cityName)
val apiResp = apiCall.execute()
var weather = apiResp.body()
if (weather == null) {
// TODO: if got weather, then check its respCode and throw if it is an error
// Also, setup a conf. for toggling this - if someone wish to handle himself
if (!apiResp.isSuccessful) {
throw APIException(apiResp.code(), apiResp.message())
}
weather = CurrentWeather()
}
return weather
}
@Throws(APIException::class)
fun currentWeatherByCityName(cityName: String, countryCode: OWM.Country): CurrentWeather {
return currentWeatherByCityName(cityName + "," + countryCode)
}
@Throws(APIException::class)
fun currentWeatherByCityId(cityId: Int): CurrentWeather {
val api = retrofit.create(CurrentWeatherAPI::class.java)
val apiCall = api.getCurrentWeatherByCityId(cityId)
val apiResp = apiCall.execute()
var weather = apiResp.body()
if (weather == null) {
if (!apiResp.isSuccessful) {
throw APIException(apiResp.code(), apiResp.message())
}
weather = CurrentWeather()
}
return weather
}
@Throws(APIException::class)
fun currentWeatherByCoords(latitude: Float, longitude: Float): CurrentWeather {
val api = retrofit.create(CurrentWeatherAPI::class.java)
val apiCall = api.getCurrentWeatherByCoords(latitude, longitude)
val apiResp = apiCall.execute()
var weather = apiResp.body()
if (weather == null) {
if (!apiResp.isSuccessful) {
throw APIException(apiResp.code(), apiResp.message())
}
weather = CurrentWeather()
}
return weather
}
@Throws(APIException::class)
fun currentWeatherByZipCode(zipCode: Int): CurrentWeather {
return currentWeatherByZipCode(zipCode, OWM.Country.UNITED_STATES)
}
@Throws(APIException::class)
fun currentWeatherByZipCode(zipCode: Int, countryCode: OWM.Country): CurrentWeather {
val api = retrofit.create(CurrentWeatherAPI::class.java)
val apiCall = api.getCurrentWeatherByZipCode(zipCode.toString() + "," + countryCode)
val apiResp = apiCall.execute()
var weather = apiResp.body()
if (weather == null) {
if (!apiResp.isSuccessful) {
throw APIException(apiResp.code(), apiResp.message())
}
weather = CurrentWeather()
}
return weather
}
@Throws(APIException::class)
fun hourlyForecastByCityName(cityName: String): HourlyForecast {
val api = retrofit.create(HourlyForecastAPI::class.java)
val apiCall = api.getHourlyForecastByCityName(cityName)
val apiResp = apiCall.execute()
var forecast = apiResp.body()
if (forecast == null) {
if (!apiResp.isSuccessful) {
throw APIException(apiResp.code(), apiResp.message())
}
forecast = HourlyForecast()
}
return forecast
}
@Throws(APIException::class)
fun hourlyForecastByCityName(cityName: String, countryCode: OWM.Country): HourlyForecast {
return hourlyForecastByCityName(cityName + "," + countryCode)
}
@Throws(APIException::class)
fun hourlyForecastByCityId(cityId: Int): HourlyForecast {
val api = retrofit.create(HourlyForecastAPI::class.java)
val apiCall = api.getHourlyForecastByCityId(cityId)
val apiResp = apiCall.execute()
var forecast = apiResp.body()
if (forecast == null) {
if (!apiResp.isSuccessful) {
throw APIException(apiResp.code(), apiResp.message())
}
forecast = HourlyForecast()
}
return forecast
}
@Throws(APIException::class)
fun hourlyForecastByCoords(latitude: Float, longitude: Float): HourlyForecast {
val api = retrofit.create(HourlyForecastAPI::class.java)
val apiCall = api.getHourlyForecastByCoords(latitude, longitude)
val apiResp = apiCall.execute()
var forecast = apiResp.body()
if (forecast == null) {
if (!apiResp.isSuccessful) {
throw APIException(apiResp.code(), apiResp.message())
}
forecast = HourlyForecast()
}
return forecast
}
@Throws(APIException::class)
fun hourlyForecastByZipCode(zipCode: Int): HourlyForecast {
return hourlyForecastByZipCode(zipCode, OWM.Country.UNITED_STATES)
}
@Throws(APIException::class)
fun hourlyForecastByZipCode(zipCode: Int, countryCode: OWM.Country): HourlyForecast {
val api = retrofit.create(HourlyForecastAPI::class.java)
val apiCall = api.getHourlyForecastByZipCode(zipCode.toString() + "," + countryCode)
val apiResp = apiCall.execute()
var forecast = apiResp.body()
if (forecast == null) {
if (!apiResp.isSuccessful) {
throw APIException(apiResp.code(), apiResp.message())
}
forecast = HourlyForecast()
}
return forecast
}
@Throws(APIException::class)
fun dailyForecastByCityName(cityName: String): DailyForecast {
return dailyForecastByCityName(cityName, OWM_25_DAILY_FORECAST_MAX_COUNT)
}
@Throws(APIException::class)
fun dailyForecastByCityName(cityName: String, count: Byte): DailyForecast {
val api = retrofit.create(DailyForecastAPI::class.java)
val apiCall = api.getDailyForecastByCityName(cityName, count)
val apiResp = apiCall.execute()
var forecast = apiResp.body()
if (forecast == null) {
if (!apiResp.isSuccessful) {
throw APIException(apiResp.code(), apiResp.message())
}
forecast = DailyForecast()
}
return forecast
}
@Throws(APIException::class)
fun dailyForecastByCityName(cityName: String, countryCode: OWM.Country): DailyForecast {
return dailyForecastByCityName(cityName, countryCode, OWM_25_DAILY_FORECAST_MAX_COUNT)
}
@Throws(APIException::class)
fun dailyForecastByCityName(cityName: String, countryCode: OWM.Country, count: Byte): DailyForecast {
return dailyForecastByCityName(cityName + "," + countryCode, count)
}
@Throws(APIException::class)
fun dailyForecastByCityId(cityId: Int): DailyForecast {
return dailyForecastByCityId(cityId, OWM_25_DAILY_FORECAST_MAX_COUNT)
}
@Throws(APIException::class)
fun dailyForecastByCityId(cityId: Int, count: Byte): DailyForecast {
val api = retrofit.create(DailyForecastAPI::class.java)
val apiCall = api.getDailyForecastByCityId(cityId, count)
val apiResp = apiCall.execute()
var forecast = apiResp.body()
if (forecast == null) {
if (!apiResp.isSuccessful) {
throw APIException(apiResp.code(), apiResp.message())
}
forecast = DailyForecast()
}
return forecast
}
@Throws(APIException::class)
fun dailyForecastByCoords(latitude: Float, longitude: Float): DailyForecast {
return dailyForecastByCoords(latitude, longitude, OWM_25_DAILY_FORECAST_MAX_COUNT)
}
@Throws(APIException::class)
fun dailyForecastByCoords(latitude: Float, longitude: Float, count: Byte): DailyForecast {
val api = retrofit.create(DailyForecastAPI::class.java)
val apiCall = api.getDailyForecastByCoords(latitude, longitude, count)
val apiResp = apiCall.execute()
var forecast = apiResp.body()
if (forecast == null) {
if (!apiResp.isSuccessful) {
throw APIException(apiResp.code(), apiResp.message())
}
forecast = DailyForecast()
}
return forecast
}
@Throws(APIException::class)
fun dailyForecastByZipCode(zipCode: Int): DailyForecast {
return dailyForecastByZipCode(zipCode, OWM.Country.UNITED_STATES, OWM_25_DAILY_FORECAST_MAX_COUNT)
}
@Throws(APIException::class)
fun dailyForecastByZipCode(zipCode: Int, count: Byte): DailyForecast {
return dailyForecastByZipCode(zipCode, OWM.Country.UNITED_STATES, count)
}
@Throws(APIException::class)
fun dailyForecastByZipCode(zipCode: Int, countryCode: OWM.Country): DailyForecast {
return dailyForecastByZipCode(zipCode, countryCode, OWM_25_DAILY_FORECAST_MAX_COUNT)
}
@Throws(APIException::class)
fun dailyForecastByZipCode(zipCode: Int, countryCode: OWM.Country, count: Byte): DailyForecast {
val api = retrofit.create(DailyForecastAPI::class.java)
val apiCall = api.getDailyForecastByZipCode(zipCode.toString() + "," + countryCode, count)
val apiResp = apiCall.execute()
var forecast = apiResp.body()
if (forecast == null) {
if (!apiResp.isSuccessful) {
throw APIException(apiResp.code(), apiResp.message())
}
forecast = DailyForecast()
}
return forecast
}
/**
* Init Retrofit for getting data from OpenWeatherMap.org
*
* @param proxy Proxy
*/
private fun createRetrofitInstance(proxy: Proxy): Retrofit {
val clientBuilder = OkHttpClient.Builder().proxy(proxy)
OkHttpTools.addQueryParameter(clientBuilder, "appid", apiKey)
OkHttpTools.addQueryParameter(clientBuilder, "type", accuracy.toString())
OkHttpTools.addQueryParameter(clientBuilder, "lang", lang.toString())
if (unit != OWM.Unit.STANDARD) {
OkHttpTools.addQueryParameter(clientBuilder, "units", unit.toString())
}
val client = clientBuilder.build()
val gson = GsonBuilder().setLenient().create()
val builder = Retrofit.Builder()
.client(client)
.baseUrl(OWM_25_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
return builder.build()
}
/**
* Search accuracy that can be set for getting data from OpenWeatherMap.org
*
* [OpenWeatherMap.org's Search accuracy][https://openweathermap.org/current#accuracy]
*/
enum class Accuracy
constructor(private val accuracy: String) {
ACCURATE("accurate"),
LIKE("like")
}
/**
* Unit that can be set for getting data from OpenWeatherMap.org
*
* [OpenWeatherMap.org's Units format][https://openweathermap.org/current#data]
*/
enum class Unit
constructor(private val unit: String) {
IMPERIAL("imperial"),
METRIC("metric"),
STANDARD("standard")
}
/**
* Language that can be set for getting data from OpenWeatherMap.org
*
* [OpenWeatherMap.org's Multilingual support][https://openweathermap.org/current#multi]
*/
enum class Language
constructor(private val lang: String) {
ARABIC("ar"),
BULGARIAN("bg"),
CATALAN("ca"),
CHINESE_SIMPLIFIED("zh_cn"),
CHINESE_TRADITIONAL("zh_tw"),
CROATIAN("hr"),
CZECH("cz"),
DUTCH("nl"),
ENGLISH("en"),
FINNISH("fi"),
FRENCH("fr"),
GALICIAN("gl"),
GREEK("el"),
GERMAN("de"),
HUNGARIAN("hu"),
ITALIAN("it"),
JAPANESE("ja"),
KOREAN("kr"),
LATVIAN("la"),
LITHUANIAN("lt"),
MACEDONIAN("mk"),
PERSIAN("fa"),
POLISH("pl"),
PORTUGUESE("pt"),
ROMANIAN("ro"),
RUSSIAN("ru"),
SLOVAK("sk"),
SLOVENIAN("sl"),
SPANISH("es"),
SWEDISH("se"),
TURKISH("tr"),
UKRAINIAN("ua"),
VIETNAMESE("vi")
}
/**
* Country that can be set for getting data from OpenWeatherMap.org
*/
enum class Country
constructor(private val country: String) {
AFGHANISTAN("AF"),
ALAND_ISLANDS("AX"),
ALBANIA("AL"),
ALGERIA("DZ"),
AMERICAN_SAMOA("AS"),
ANDORRA("AD"),
ANGOLA("AO"),
ANGUILLA("AI"),
ANTARCTICA("AQ"),
ANTIGUA_AND_BARBUDA("AG"),
ARGENTINA("AR"),
ARMENIA("AM"),
ARUBA("AW"),
AUSTRALIA("AU"),
AUSTRIA("AT"),
AZERBAIJAN("AZ"),
BAHAMAS("BS"),
BAHRAIN("BH"),
BANGLADESH("BD"),
BARBADOS("BB"),
BELARUS("BY"),
BELGIUM("BE"),
BELIZE("BZ"),
BENIN("BJ"),
BERMUDA("BM"),
BHUTAN("BT"),
BOLIVIA("BO"),
BOSNIA_AND_HERZEGOVINA("BA"),
BOTSWANA("BW"),
BOUVET_ISLAND("BV"),
BRAZIL("BR"),
BRITISH_INDIAN_OCEAN_TERRITORY("IO"),
BRITISH_VIRGIN_ISLANDS("VG"),
BRUNEI("BN"),
BULGARIA("BG"),
BURKINA_FASO("BF"),
BURUNDI("BI"),
CAMBODIA("KH"),
CAMEROON("CM"),
CANADA("CA"),
CAPE_VERDE("CV"),
CARIBBEAN_NETHERLANDS("BQ"),
CAYMAN_ISLANDS("KY"),
CENTRAL_AFRICAN_REPUBLIC("CF"),
CHAD("TD"),
CHILE("CL"),
CHINA("CN"),
CHRISTMAS_ISLAND("CX"),
COCOS_KEELING_ISLANDS("CC"),
COLOMBIA("CO"),
COMOROS("KM"),
CONGO_BRAZZAVILLE("CG"),
CONGO_KINSHASA("CD"),
COOK_ISLANDS("CK"),
COSTA_RICA("CR"),
CROATIA("HR"),
CUBA("CU"),
CURACAO("CW"),
CYPRUS("CY"),
CZECH_REPUBLIC("CZ"),
COTE_D_IVOIRE("CI"),
DENMARK("DK"),
DJIBOUTI("DJ"),
DOMINICA("DM"),
DOMINICAN_REPUBLIC("DO"),
ECUADOR("EC"),
EGYPT("EG"),
EL_SALVADOR("SV"),
EQUATORIAL_GUINEA("GQ"),
ERITREA("ER"),
ESTONIA("EE"),
ETHIOPIA("ET"),
FALKLAND_ISLANDS("FK"),
FAROE_ISLANDS("FO"),
FIJI("FJ"),
FINLAND("FI"),
FRANCE("FR"),
FRENCH_GUIANA("GF"),
FRENCH_POLYNESIA("PF"),
FRENCH_SOUTHERN_TERRITORIES("TF"),
GABON("GA"),
GAMBIA("GM"),
GEORGIA("GE"),
GERMANY("DE"),
GHANA("GH"),
GIBRALTAR("GI"),
GREECE("GR"),
GREENLAND("GL"),
GRENADA("GD"),
GUADELOUPE("GP"),
GUAM("GU"),
GUATEMALA("GT"),
GUERNSEY("GG"),
GUINEA("GN"),
GUINEA_BISSAU("GW"),
GUYANA("GY"),
HAITI("HT"),
HEARD_AND_MCDONALD_ISLANDS("HM"),
HONDURAS("HN"),
HONG_KONG_SAR_CHINA("HK"),
HUNGARY("HU"),
ICELAND("IS"),
INDIA("IN"),
INDONESIA("ID"),
IRAN("IR"),
IRAQ("IQ"),
IRELAND("IE"),
ISLE_OF_MAN("IM"),
ISRAEL("IL"),
ITALY("IT"),
JAMAICA("JM"),
JAPAN("JP"),
JERSEY("JE"),
JORDAN("JO"),
KAZAKHSTAN("KZ"),
KENYA("KE"),
KIRIBATI("KI"),
KUWAIT("KW"),
KYRGYZSTAN("KG"),
LAOS("LA"),
LATVIA("LV"),
LEBANON("LB"),
LESOTHO("LS"),
LIBERIA("LR"),
LIBYA("LY"),
LIECHTENSTEIN("LI"),
LITHUANIA("LT"),
LUXEMBOURG("LU"),
MACAU_SAR_CHINA("MO"),
MACEDONIA("MK"),
MADAGASCAR("MG"),
MALAWI("MW"),
MALAYSIA("MY"),
MALDIVES("MV"),
MALI("ML"),
MALTA("MT"),
MARSHALL_ISLANDS("MH"),
MARTINIQUE("MQ"),
MAURITANIA("MR"),
MAURITIUS("MU"),
MAYOTTE("YT"),
MEXICO("MX"),
MICRONESIA("FM"),
MOLDOVA("MD"),
MONACO("MC"),
MONGOLIA("MN"),
MONTENEGRO("ME"),
MONTSERRAT("MS"),
MOROCCO("MA"),
MOZAMBIQUE("MZ"),
MYANMAR_BURMA("MM"),
NAMIBIA("NA"),
NAURU("NR"),
NEPAL("NP"),
NETHERLANDS("NL"),
NEW_CALEDONIA("NC"),
NEW_ZEALAND("NZ"),
NICARAGUA("NI"),
NIGER("NE"),
NIGERIA("NG"),
NIUE("NU"),
NORFOLK_ISLAND("NF"),
NORTH_KOREA("KP"),
NORTHERN_MARIANA_ISLANDS("MP"),
NORWAY("NO"),
OMAN("OM"),
PAKISTAN("PK"),
PALAU("PW"),
PALESTINIAN_TERRITORIES("PS"),
PANAMA("PA"),
PAPUA_NEW_GUINEA("PG"),
PARAGUAY("PY"),
PERU("PE"),
PHILIPPINES("PH"),
PITCAIRN_ISLANDS("PN"),
POLAND("PL"),
PORTUGAL("PT"),
PUERTO_RICO("PR"),
QATAR("QA"),
ROMANIA("RO"),
RUSSIA("RU"),
RWANDA("RW"),
REUNION("RE"),
SAMOA("WS"),
SAN_MARINO("SM"),
SAUDI_ARABIA("SA"),
SENEGAL("SN"),
SERBIA("RS"),
SEYCHELLES("SC"),
SIERRA_LEONE("SL"),
SINGAPORE("SG"),
SINT_MAARTEN("SX"),
SLOVAKIA("SK"),
SLOVENIA("SI"),
SOLOMON_ISLANDS("SB"),
SOMALIA("SO"),
SOUTH_AFRICA("ZA"),
SOUTH_GEORGIA_AND_SOUTH_SANDWICH_ISLANDS("GS"),
SOUTH_KOREA("KR"),
SOUTH_SUDAN("SS"),
SPAIN("ES"),
SRI_LANKA("LK"),
ST_BARTHELEMY("BL"),
ST_HELENA("SH"),
ST_KITTS_AND_NEVIS("KN"),
ST_LUCIA("LC"),
ST_MARTIN("MF"),
ST_PIERRE_AND_MIQUELON("PM"),
ST_VINCENT_AND_GRENADINES("VC"),
SUDAN("SD"),
SURINAME("SR"),
SVALBARD_AND_JAN_MAYEN("SJ"),
SWAZILAND("SZ"),
SWEDEN("SE"),
SWITZERLAND("CH"),
SYRIA("SY"),
SAO_TOME_AND_PRINCIPE("ST"),
TAIWAN("TW"),
TAJIKISTAN("TJ"),
TANZANIA("TZ"),
THAILAND("TH"),
TIMOR_LESTE("TL"),
TOGO("TG"),
TOKELAU("TK"),
TONGA("TO"),
TRINIDAD_AND_TOBAGO("TT"),
TUNISIA("TN"),
TURKEY("TR"),
TURKMENISTAN("TM"),
TURKS_AND_CAICOS_ISLANDS("TC"),
TUVALU("TV"),
US_OUTLYING_ISLANDS("UM"),
US_VIRGIN_ISLANDS("VI"),
UGANDA("UG"),
UKRAINE("UA"),
UNITED_ARAB_EMIRATES("AE"),
UNITED_KINGDOM("GB"),
UNITED_STATES("US"),
URUGUAY("UY"),
UZBEKISTAN("UZ"),
VANUATU("VU"),
VATICAN_CITY("VA"),
VENEZUELA("VE"),
VIETNAM("VN"),
WALLIS_AND_FUTUNA("WF"),
WESTERN_SAHARA("EH"),
YEMEN("YE"),
ZAMBIA("ZM"),
ZIMBABWE("ZW")
}
}

View file

@ -0,0 +1,118 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
import net.aksingh.owmjapis.model.param.*
import java.util.*
data class CurrentWeather(
@field:SerializedName("dt")
private val dt: Int? = null,
@field:SerializedName("rain")
val rainData: Rain? = null,
@field:SerializedName("snow")
val snowData: Snow? = null,
@field:SerializedName("coord")
val coordData: Coord? = null,
@field:SerializedName("weather")
val weatherList: List<Weather?>? = null,
@field:SerializedName("name")
val cityName: String? = null,
@field:SerializedName("cod")
val respCode: Int? = null,
@field:SerializedName("main")
val mainData: Main? = null,
@field:SerializedName("clouds")
val cloudData: Cloud? = null,
@field:SerializedName("id")
val cityId: Int? = null,
@field:SerializedName("sys")
val systemData: System? = null,
@field:SerializedName("base")
val baseStation: String? = null,
@field:SerializedName("wind")
val windData: Wind? = null
) {
var dateTime: Date? = null
get() {
if (dt != null) {
return Date(dt!!.toLong() * 1000L)
}
return null
}
fun hasDateTime(): Boolean = dateTime != null
fun hasRainData(): Boolean = rainData != null
fun hasSnowData(): Boolean = snowData != null
fun hasCoordData(): Boolean = coordData != null
fun hasWeatherList(): Boolean = weatherList != null
fun hasCityName(): Boolean = cityName != null
fun hasRespCode(): Boolean = respCode != null
fun hasMainData(): Boolean = mainData != null
fun hasCloudData(): Boolean = cloudData != null
fun hasCityId(): Boolean = cityId != null
fun hassystemData(): Boolean = systemData != null
fun hasBaseStation(): Boolean = baseStation != null
fun hasWindData(): Boolean = windData != null
companion object Static {
@JvmStatic
fun fromJson(json: String): CurrentWeather {
return GsonBuilder().create().fromJson(json, CurrentWeather::class.java)
}
@JvmStatic
fun toJson(pojo: CurrentWeather): String {
return GsonBuilder().create().toJson(pojo)
}
@JvmStatic
fun toJsonPretty(pojo: CurrentWeather): String {
return GsonBuilder().setPrettyPrinting().create().toJson(pojo)
}
}
}

View file

@ -0,0 +1,62 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
data class CurrentWeatherList(
@field:SerializedName("cod")
var respCode: String? = null,
@field:SerializedName("calctime")
var calcTime: Float? = null,
@field:SerializedName("cnt")
var dataCount: Short? = null,
@field:SerializedName("list")
var dataList: List<CurrentWeather>? = null
) {
fun hasRespCode(): Boolean = respCode != null
fun hasCalcTime(): Boolean = calcTime != null
fun hasDataCount(): Boolean = dataCount != null
fun hasDataList(): Boolean = dataList != null
companion object Static {
@JvmStatic
fun fromJson(json: String): CurrentWeatherList {
return GsonBuilder().create().fromJson(json, CurrentWeatherList::class.java)
}
@JvmStatic
fun toJson(pojo: CurrentWeatherList): String {
return GsonBuilder().create().toJson(pojo)
}
@JvmStatic
fun toJsonPretty(pojo: CurrentWeatherList): String {
return GsonBuilder().setPrettyPrinting().create().toJson(pojo)
}
}
}

View file

@ -0,0 +1,70 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
import net.aksingh.owmjapis.model.param.City
import net.aksingh.owmjapis.model.param.Data
data class DailyForecast(
@field:SerializedName("cod")
var respCode: String? = null,
@field:SerializedName("message")
var message: Float? = null,
@field:SerializedName("city")
var cityData: City? = null,
@field:SerializedName("cnt")
var dataCount: Int? = null,
@field:SerializedName("list")
var dataList: List<Data?>? = null
) {
fun hasRespCode(): Boolean = respCode != null
fun hasMessage(): Boolean = message != null
fun hasCityData(): Boolean = cityData != null
fun hasDataCount(): Boolean = dataCount != null
fun hasDataList(): Boolean = dataList != null
companion object Static {
@JvmStatic
fun fromJson(json: String): DailyForecast {
return GsonBuilder().create().fromJson(json, DailyForecast::class.java)
}
@JvmStatic
fun toJson(pojo: DailyForecast): String {
return GsonBuilder().create().toJson(pojo)
}
@JvmStatic
fun toJsonPretty(pojo: DailyForecast): String {
return GsonBuilder().setPrettyPrinting().create().toJson(pojo)
}
}
}

View file

@ -0,0 +1,89 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
import net.aksingh.owmjapis.model.param.City
import net.aksingh.owmjapis.model.param.Data
/**
* <p>
* Parses hourly forecast data and provides methods to get/access the same information.
* This class provides <code>has</code> and <code>get</code> methods to access the information.
* </p>
* <p>
* <code>has</code> methods can be used to check if the data exists, i.e., if the data was available
* (successfully downloaded) and was parsed correctly.
* <code>get</code> methods can be used to access the data, if the data exists, otherwise <code>get</code>
* methods will give value as per following basis:
* Others: <code>null</code>
* </p>
*
* @author Ashutosh Kumar Singh
* @version 2017/11/08
*
* @see [OpenWeatherMap.org's Weather Data API](https://openweathermap.org/forecast)
* @since 2.5.1.0
*/
data class HourlyForecast(
@field:SerializedName("cod")
var respCode: String? = null,
@field:SerializedName("message")
var message: Float? = null,
@field:SerializedName("city")
var cityData: City? = null,
@field:SerializedName("cnt")
var dataCount: Int? = null,
@field:SerializedName("list")
var dataList: List<Data?>? = null
) {
fun hasRespCode(): Boolean = respCode != null
fun hasMessage(): Boolean = message != null
fun hasCityData(): Boolean = cityData != null
fun hasDataCount(): Boolean = dataCount != null
fun hasDataList(): Boolean = dataList != null
companion object Static {
@JvmStatic
fun fromJson(json: String): HourlyForecast {
return GsonBuilder().create().fromJson(json, HourlyForecast::class.java)
}
@JvmStatic
fun toJson(pojo: HourlyForecast): String {
return GsonBuilder().create().toJson(pojo)
}
@JvmStatic
fun toJsonPretty(pojo: HourlyForecast): String {
return GsonBuilder().setPrettyPrinting().create().toJson(pojo)
}
}
}

View file

@ -0,0 +1,59 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model.param
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
data class City(
@field:SerializedName("id")
val id: Int? = null,
@field:SerializedName("name")
val name: String? = null,
@field:SerializedName("coord")
val coordData: Coord? = null,
@field:SerializedName("country")
val countryCode: String? = null,
@field:SerializedName("population")
val population: Long? = null
) {
fun hasId(): Boolean = id != null
fun hasName(): Boolean = name != null
fun hasCoordData(): Boolean = coordData != null
fun hasCountryCode(): Boolean = countryCode != null
fun hasPopulation(): Boolean = population != null
fun toJson(): String {
return GsonBuilder().create().toJson(this)
}
fun toJsonPretty(): String {
return GsonBuilder().setPrettyPrinting().create().toJson(this)
}
}

View file

@ -0,0 +1,39 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model.param
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
data class Cloud(
@field:SerializedName("all")
val cloudiness: Int? = null
) {
fun hasCloudiness(): Boolean = cloudiness != null
fun toJson(): String {
return GsonBuilder().create().toJson(this)
}
fun toJsonPretty(): String {
return GsonBuilder().setPrettyPrinting().create().toJson(this)
}
}

View file

@ -0,0 +1,44 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model.param
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
data class Coord(
@field:SerializedName("lon")
val longitude: Float? = null,
@field:SerializedName("lat")
val latitude: Float? = null
) {
fun hasLongitude(): Boolean = longitude != null
fun hasLatitude(): Boolean = latitude != null
fun toJson(): String {
return GsonBuilder().create().toJson(this)
}
fun toJsonPretty(): String {
return GsonBuilder().setPrettyPrinting().create().toJson(this)
}
}

View file

@ -0,0 +1,93 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model.param
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
import java.util.*
data class Data(
@field:SerializedName("dt")
private val dt: Int? = null,
@field:SerializedName("main")
val mainData: Main? = null,
@field:SerializedName("temp")
val tempData: Temp? = null,
@field:SerializedName("pressure")
val pressure: Float? = null,
@field:SerializedName("humidity")
val humidity: Int? = null,
@field:SerializedName("weather")
val weatherList: List<Weather?>? = null,
@field:SerializedName("clouds")
val cloudData: Cloud? = null,
@field:SerializedName("wind")
val windData: Wind? = null,
@field:SerializedName("sys")
val systemData: System? = null,
@field:SerializedName("dt_txt")
val dateTimeText: String? = null
) {
var dateTime: Date? = null
get() {
if (dt != null) {
return Date(dt.toLong() * 1000L)
}
return null
}
fun hasDateTime(): Boolean = dateTime != null
fun hasMainData(): Boolean = mainData != null
fun hasTempData(): Boolean = tempData != null
fun hasPressure(): Boolean = pressure != null
fun hasHumidity(): Boolean = humidity != null
fun hasWeatherList(): Boolean = weatherList != null
fun hasCloudData(): Boolean = cloudData != null
fun hasWindData(): Boolean = windData != null
fun hassystemData(): Boolean = systemData != null
fun hasDateTimeText(): Boolean = dateTimeText != null
fun toJson(): String {
return GsonBuilder().create().toJson(this)
}
fun toJsonPretty(): String {
return GsonBuilder().setPrettyPrinting().create().toJson(this)
}
}

View file

@ -0,0 +1,74 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model.param
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
data class Main(
@field:SerializedName("temp")
val temp: Float? = null,
@field:SerializedName("temp_min")
val tempMin: Float? = null,
@field:SerializedName("temp_max")
val tempMax: Float? = null,
@field:SerializedName("pressure")
val pressure: Float? = null,
@field:SerializedName("sea_level")
val seaLevel: Float? = null,
@field:SerializedName("grnd_level")
val groundLevel: Float? = null,
@field:SerializedName("humidity")
val humidity: Int? = null,
@field:SerializedName("temp_kf")
val tempKf: Float? = null
) {
fun hasTemp(): Boolean = temp != null
fun hasTempMax(): Boolean = tempMax != null
fun hasTempMin(): Boolean = tempMin != null
fun hasPressure(): Boolean = pressure != null
fun hasSeaLevel(): Boolean = seaLevel != null
fun hasGroundLevel(): Boolean = groundLevel != null
fun hasHumidity(): Boolean = humidity != null
fun hasTempKf(): Boolean = tempKf != null
fun toJson(): String {
return GsonBuilder().create().toJson(this)
}
fun toJsonPretty(): String {
return GsonBuilder().setPrettyPrinting().create().toJson(this)
}
}

View file

@ -0,0 +1,39 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model.param
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
data class Rain(
@field:SerializedName("3h")
val precipVol3h: Int? = null
) {
fun hasPrecipVol3h(): Boolean = precipVol3h != null
fun toJson(): String {
return GsonBuilder().create().toJson(this)
}
fun toJsonPretty(): String {
return GsonBuilder().setPrettyPrinting().create().toJson(this)
}
}

View file

@ -0,0 +1,39 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model.param
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
data class Snow(
@field:SerializedName("3h")
val snowVol3h: Int? = null
) {
fun hasSnowVol3h(): Boolean = snowVol3h != null
fun toJson(): String {
return GsonBuilder().create().toJson(this)
}
fun toJsonPretty(): String {
return GsonBuilder().setPrettyPrinting().create().toJson(this)
}
}

View file

@ -0,0 +1,84 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model.param
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
import java.util.*
data class System(
@field:SerializedName("type")
val type: Int? = null,
@field:SerializedName("id")
val id: Int? = null,
@field:SerializedName("message")
val message: Float? = null,
@field:SerializedName("country")
val countryCode: String? = null,
@field:SerializedName("sunrise")
private val sunrise: Int? = null,
@field:SerializedName("sunset")
private val sunset: Int? = null,
@field:SerializedName("pod")
val pod: String? = null
) {
var sunriseDateTime: Date? = null
get() {
if (sunrise != null) {
return Date(sunrise.toLong() * 1000L)
}
return null
}
var sunsetDateTime: Date? = null
get() {
if (sunset != null) {
return Date(sunset.toLong() * 1000L)
}
return null
}
fun hasType(): Boolean = type != null
fun hasId(): Boolean = id != null
fun hasMessage(): Boolean = message != null
fun hasCountryCode(): Boolean = countryCode != null
fun hasSunriseDateTime(): Boolean = sunriseDateTime != null
fun hasSunsetDateTime(): Boolean = sunsetDateTime != null
fun toJson(): String {
return GsonBuilder().create().toJson(this)
}
fun toJsonPretty(): String {
return GsonBuilder().setPrettyPrinting().create().toJson(this)
}
}

View file

@ -0,0 +1,64 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model.param
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
data class Temp(
@field:SerializedName("day")
val tempDay: Float? = null,
@field:SerializedName("min")
val tempMin: Float? = null,
@field:SerializedName("max")
val tempMax: Float? = null,
@field:SerializedName("night")
val tempNight: Float? = null,
@field:SerializedName("eve")
val tempEvening: Float? = null,
@field:SerializedName("morn")
val tempMorning: Float? = null
) {
fun hasTempDay(): Boolean = tempDay != null
fun hasTempMin(): Boolean = tempMin != null
fun hasTempMax(): Boolean = tempMax != null
fun hasTempNight(): Boolean = tempNight != null
fun hasTempEvening(): Boolean = tempEvening != null
fun hasTempMorning(): Boolean = tempMorning != null
fun toJson(): String {
return GsonBuilder().create().toJson(this)
}
fun toJsonPretty(): String {
return GsonBuilder().setPrettyPrinting().create().toJson(this)
}
}

View file

@ -0,0 +1,54 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model.param
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
data class Weather(
@field:SerializedName("id")
val conditionId: Int? = null,
@field:SerializedName("main")
val mainInfo: String? = null,
@field:SerializedName("description")
val moreInfo: String? = null,
@field:SerializedName("icon")
val iconCode: String? = null
) {
fun hasConditionId(): Boolean = conditionId != null
fun hasMainInfo(): Boolean = mainInfo != null
fun hasMoreInfo(): Boolean = moreInfo != null
fun hasIconCode(): Boolean = iconCode != null
fun toJson(): String {
return GsonBuilder().create().toJson(this)
}
fun toJsonPretty(): String {
return GsonBuilder().setPrettyPrinting().create().toJson(this)
}
}

View file

@ -0,0 +1,49 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.model.param
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName
data class Wind(
@field:SerializedName("speed")
val speed: Float? = null,
@field:SerializedName("deg")
val degree: Float? = null,
@field:SerializedName("gust")
val gust: Float? = null
) {
fun hasSpeed(): Boolean = speed != null
fun hasDegree(): Boolean = degree != null
fun hasGust(): Boolean = gust != null
fun toJson(): String {
return GsonBuilder().create().toJson(this)
}
fun toJsonPretty(): String {
return GsonBuilder().setPrettyPrinting().create().toJson(this)
}
}

View file

@ -0,0 +1,110 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.util
/**
* Provides methods for conversions, like converting
* windData direction from degree to direction code or name.
*
* @author Ashutosh Kumar Singh
* @version 2017-11-06
* @since 2.5.1.0
*/
class ConversionTools {
companion object Static {
/**
* Converts degree to direction code.
*
* @param degree Degree of windData (as received from OpenWeatherMap.org).
* @return Direction code, e.g., "N", "NE", etc.
* @throws IllegalArgumentException Degree should be between 0 and 360.
*/
@JvmStatic
@Throws(IllegalArgumentException::class)
fun convertDegree2DirectionCode(degree: Float): String {
val directionCode: String
// degree should be between 0 and 360
if (degree < 0.0f || degree > 360.0f) {
throw IllegalArgumentException("Degree cannot be less than 0 or more than 360.")
}
when {
degree <= 11.25f -> directionCode = "N"
degree <= 33.75f -> directionCode = "NNE"
degree <= 56.25f -> directionCode = "NE"
degree <= 78.75f -> directionCode = "ENE"
degree <= 101.25f -> directionCode = "E"
degree <= 123.75f -> directionCode = "ESE"
degree <= 146.25f -> directionCode = "SE"
degree <= 168.75f -> directionCode = "SSE"
degree <= 191.25f -> directionCode = "S"
degree <= 213.75f -> directionCode = "SSW"
degree <= 236.25f -> directionCode = "SW"
degree <= 258.75f -> directionCode = "WSW"
degree <= 281.25f -> directionCode = "W"
degree <= 303.75f -> directionCode = "WNW"
degree <= 326.25f -> directionCode = "NW"
degree <= 348.75f -> directionCode = "NNW"
else -> directionCode = "N"
}
return directionCode
}
/**
* Converts degree to direction name.
*
* @param degree Degree of windData (as received from OpenWeatherMap.org).
* @return Direction name, e.g., "North", "North East", etc.
* @throws IllegalArgumentException Degree should be between 0 and 360.
*/
@JvmStatic
@Throws(IllegalArgumentException::class)
fun convertDegree2DirectionName(degree: Float): String {
val directionName: String
val directionCode = convertDegree2DirectionCode(degree)
when (directionCode) {
"N" -> directionName = "North"
"NNE" -> directionName = "North North East"
"NE" -> directionName = "North East"
"ENE" -> directionName = "East North East"
"E" -> directionName = "East"
"ESE" -> directionName = "East South East"
"SE" -> directionName = "South East"
"SSE" -> directionName = "South South East"
"S" -> directionName = "South"
"SSW" -> directionName = "South South West"
"SW" -> directionName = "South West"
"WSW" -> directionName = "West South West"
"W" -> directionName = "West"
"WNW" -> directionName = "West North West"
"NW" -> directionName = "North West"
"NNW" -> directionName = "North North West"
else -> directionName = "North"
}
return directionName
}
}
}

View file

@ -0,0 +1,62 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.util
import okhttp3.OkHttpClient
/**
* Provides methods for OkHttp lib. handling.
*
* @author Ashutosh Kumar Singh
* @version 2017-11-08
* @since 2.5.1.0
*/
internal class OkHttpTools {
companion object Static {
/**
* Add a query parameter to OkHttpClient.Builder instance.
* It is used to add default parameters to Retrofit instance.
*
* @param httpClientBuilder OkHttpClient.Builder instance
* @param key Key in the query string
* @param value Value in the query string
*/
@JvmStatic
fun addQueryParameter(httpClientBuilder: OkHttpClient.Builder, key: String, value: String) {
httpClientBuilder.addInterceptor { chain ->
val original = chain.request()
val originalHttpUrl = original.url()
val url = originalHttpUrl.newBuilder()
.addQueryParameter(key, value)
.build()
val requestBuilder = original.newBuilder()
.url(url)
val request = requestBuilder.build()
chain.proceed(request)
}
}
}
}

View file

@ -0,0 +1,76 @@
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis.util
import java.net.*
/**
* Provides methods for system handling.
*
* @author Ashutosh Kumar Singh
* @version 2017-11-08
* @since 2.5.1.0
*/
internal class SystemTools {
companion object Static {
/**
* Get the system proxy configured
*
* @return Proxy default to the system
*/
@JvmStatic
fun getSystemProxy(): Proxy {
var sysProxy = Proxy.NO_PROXY
var proxyList: List<*>? = null
try {
proxyList = ProxySelector.getDefault().select(URI("http://localhost/"))
} catch (e: URISyntaxException) {
e.printStackTrace()
}
if (proxyList != null) {
val iter = proxyList.iterator()
while (iter.hasNext()) {
sysProxy = iter.next() as java.net.Proxy
}
}
return sysProxy
}
/**
* Set the proxy's authentication details
*
* @param user Username for the proxy
* @param pass Password for the proxy
*/
@JvmStatic
fun setProxyAuthDetails(user: String, pass: String) {
Authenticator.setDefault(object : Authenticator() {
public override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication(user, pass.toCharArray())
}
})
}
}
}

View file

@ -1,24 +1,21 @@
/*
* Copyright (c) 2013-2015 Ashutosh Kumar Singh <me@aksingh.net>
*
* 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.
*/
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis;
@ -35,32 +32,32 @@ import java.io.IOException;
*/
public class CurrentWeatherTest {
public static void main(String[] args) throws IOException {
OpenWeatherMap owm = new OpenWeatherMap("");
CurrentWeather cw = owm.currentWeatherByCityName("London, UK");
public static void main(String[] args) throws IOException {
OpenWeatherMap owm = new OpenWeatherMap("");
CurrentWeather cw = owm.currentWeatherByCityName("London, UK");
if (!cw.isValid()) {
System.out.println("Reponse is inValid!");
} else {
System.out.println("Reponse is Valid!");
System.out.println();
if (!cw.isValid()) {
System.out.println("Reponse is inValid!");
} else {
System.out.println("Reponse is Valid!");
System.out.println();
if (cw.hasBaseStation()) {
System.out.println("Base station: " + cw.getBaseStation());
}
if (cw.hasDateTime()) {
System.out.println("Date time: " + cw.getDateTime());
}
System.out.println();
if (cw.hasBaseStation()) {
System.out.println("Base station: " + cw.getBaseStation());
}
if (cw.hasDateTime()) {
System.out.println("Date time: " + cw.getDateTime());
}
System.out.println();
if (cw.hasCityCode()) {
System.out.println("City code: " + cw.getCityCode());
}
if (cw.hasCityName()) {
System.out.println("City name: " + cw.getCityName());
}
System.out.println();
}
if (cw.hasCityCode()) {
System.out.println("City code: " + cw.getCityCode());
}
if (cw.hasCityName()) {
System.out.println("City name: " + cw.getCityName());
}
System.out.println();
}
}
}

View file

@ -1,24 +1,21 @@
/*
* Copyright (c) 2013-2015 Ashutosh Kumar Singh <me@aksingh.net>
*
* 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.
*/
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis;
@ -35,43 +32,43 @@ import java.io.IOException;
*/
public class DailyForecastTest {
public static void main(String[] args) throws IOException {
OpenWeatherMap owm = new OpenWeatherMap("");
DailyForecast df = owm.dailyForecastByCityName("London, UK", Byte.parseByte("5"));
public static void main(String[] args) throws IOException {
OpenWeatherMap owm = new OpenWeatherMap("");
DailyForecast df = owm.dailyForecastByCityName("London, UK", Byte.parseByte("5"));
if (!df.isValid()) {
System.out.println("Reponse is inValid!");
} else {
System.out.println("Reponse is Valid!");
System.out.println();
if (!df.isValid()) {
System.out.println("Reponse is inValid!");
} else {
System.out.println("Reponse is Valid!");
System.out.println();
if (df.hasCityInstance()) {
DailyForecast.City city = df.getCityInstance();
if (city.hasCityName()) {
if (city.hasCityCode()) {
System.out.println("City code: " + city.getCityCode());
}
if (city.hasCityName()) {
System.out.println("City name: " + city.getCityName());
}
System.out.println();
}
}
System.out.println("Total forecast instances: " + df.getForecastCount());
System.out.println();
for (int i = 0; i < df.getForecastCount(); i++) {
DailyForecast.Forecast forecast = df.getForecastInstance(i);
System.out.println("*** Forecast instance number " + (i+1) + " ***");
if (forecast.hasDateTime()) {
System.out.println(forecast.getDateTime());
}
System.out.println();
}
if (df.hasCityInstance()) {
DailyForecast.City city = df.getCityInstance();
if (city.hasCityName()) {
if (city.hasCityCode()) {
System.out.println("City code: " + city.getCityCode());
}
if (city.hasCityName()) {
System.out.println("City name: " + city.getCityName());
}
System.out.println();
}
}
System.out.println("Total forecast instances: " + df.getForecastCount());
System.out.println();
for (int i = 0; i < df.getForecastCount(); i++) {
DailyForecast.Forecast forecast = df.getForecastInstance(i);
System.out.println("*** Data instance number " + (i + 1) + " ***");
if (forecast.hasDateTime()) {
System.out.println(forecast.getDateTime());
}
System.out.println();
}
}
}
}

View file

@ -1,24 +1,21 @@
/*
* Copyright (c) 2013-2015 Ashutosh Kumar Singh <me@aksingh.net>
*
* 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.
*/
/**************************************************************************************************
* Copyright (c) 2013-2017 Ashutosh Kumar Singh <ashutosh@aksingh.net> *
* *
* 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 net.aksingh.owmjapis;
@ -35,43 +32,43 @@ import java.io.IOException;
*/
public class HourlyForecastTest {
public static void main(String[] args) throws IOException {
OpenWeatherMap owm = new OpenWeatherMap("");
HourlyForecast hf = owm.hourlyForecastByCityName("London, UK");
public static void main(String[] args) throws IOException {
OpenWeatherMap owm = new OpenWeatherMap("");
HourlyForecast hf = owm.hourlyForecastByCityName("London, UK");
if (!hf.isValid()) {
System.out.println("Reponse is inValid!");
} else {
System.out.println("Reponse is Valid!");
System.out.println();
if (!hf.isValid()) {
System.out.println("Reponse is inValid!");
} else {
System.out.println("Reponse is Valid!");
System.out.println();
if (hf.hasCityInstance()) {
HourlyForecast.City city = hf.getCityInstance();
if (city.hasCityName()) {
if (city.hasCityCode()) {
System.out.println("City code: " + city.getCityCode());
}
if (city.hasCityName()) {
System.out.println("City name: " + city.getCityName());
}
System.out.println();
}
}
System.out.println("Total forecast instances: " + hf.getForecastCount());
System.out.println();
for (int i = 0; i < hf.getForecastCount(); i++) {
HourlyForecast.Forecast forecast = hf.getForecastInstance(i);
System.out.println("*** Forecast instance number " + (i+1) + " ***");
if (forecast.hasDateTime()) {
System.out.println(forecast.getDateTime());
}
System.out.println();
}
if (hf.hasCityInstance()) {
HourlyForecast.City city = hf.getCityInstance();
if (city.hasCityName()) {
if (city.hasCityCode()) {
System.out.println("City code: " + city.getCityCode());
}
if (city.hasCityName()) {
System.out.println("City name: " + city.getCityName());
}
System.out.println();
}
}
System.out.println("Total forecast instances: " + hf.getForecastCount());
System.out.println();
for (int i = 0; i < hf.getForecastCount(); i++) {
HourlyForecast.Forecast forecast = hf.getForecastInstance(i);
System.out.println("*** Data instance number " + (i + 1) + " ***");
if (forecast.hasDateTime()) {
System.out.println(forecast.getDateTime());
}
System.out.println();
}
}
}
}