diff --git a/.gitignore b/.gitignore index 7d300c6..77eac78 100644 --- a/.gitignore +++ b/.gitignore @@ -85,3 +85,6 @@ docs ### Node node_modules/ + +### Idea +.idea/ diff --git a/README.md b/README.md index 1f5525b..569775d 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Add the following to your `pom.xml`: io.openepi openepi-client - 0.1 + 2.0.0 ``` @@ -30,94 +30,20 @@ Works on Java 8 (and higher) ## Examples -### Crop Health -```java -import io.openepi.client.CropHealthApi; -import io.openepi.client.ApiException; -import io.openepi.crop_health.model.BinaryPredictionResponse; -import java.io.File; - -public class Main { - public static void main(String[] args) { - CropHealthApi api = new CropHealthApi(); - try { - File file = new File("path/to/file"); - BinaryPredictionResponse response = api.predictionsWithBinary(file); - System.out.println(response.getHLT()); - } catch (ApiException e) { - System.err.println("Exception when calling CropHealthApi#getCropHealth"); - e.printStackTrace(); - } - } -} -``` - -### Deforestation - -```java -import io.openepi.common.ApiException; -import io.openepi.deforestation.api.DeforestationApi; -import io.openepi.deforestation.model.DeforestationBasinGeoJSON; - -import java.math.BigDecimal; - - -public class Main { - public static void main(String[] args) { - DeforestationApi api = new DeforestationApi(); - try { - BigDecimal lon = new BigDecimal("30.06"); - BigDecimal lat = BigDecimal.valueOf(-1.94); - DeforestationBasinGeoJSON response = api.getLossyearBasinSinglePoint(lon, lat); - System.out.println(response.getFeatures()); - } catch (ApiException e) { - System.err.println("Exception when calling DeforestationApi#lossyearBasinGet"); - e.printStackTrace(); - } - } -} -``` - -### Flood - -```java -import io.openepi.flood.api.FloodApi; -import io.openepi.flood.model.SummaryResponseModel; -import io.openepi.common.ApiException; - -import java.math.BigDecimal; - -public class Main { - public static void main(String[] args) { - FloodApi api = new FloodApi(); - try { - BigDecimal lon = new BigDecimal("33.57"); - BigDecimal lat = BigDecimal.valueOf(-1.37); - SummaryResponseModel response = api.getForecastSummarySinglePoint(lon, lat, false); - System.out.println(response.getQueriedLocation().getFeatures()); - } catch (ApiException e) { - System.err.println("Exception when calling FloodApi#getFlood"); - e.printStackTrace(); - } - } -} -``` - ### Geocoding ```java -import io.openepi.geocoding.api.GeocodingApi; +import io.openepi.geocoding.GeocodingClient; import io.openepi.geocoding.model.FeatureCollection; -import io.openepi.common.ApiException; public class Main { public static void main(String[] args) { - GeocodingApi api = new GeocodingApi(); + GeocodingClient client = new GeocodingClient(); try { - FeatureCollection response = api.getGeocoding("Rwanda"); + FeatureCollection response = client.geocode("Rwanda"); System.out.println(response); } catch (ApiException e) { - System.err.println("Exception when calling GeocodingApi#getGeocoding"); + System.err.println("Exception when calling GeocodingClient#geocode"); e.printStackTrace(); } } @@ -125,31 +51,7 @@ public class Main { ``` -### Soil -```java -import io.openepi.soil.api.SoilApi; -import io.openepi.soil.model.SoilTypeJSON; -import io.openepi.common.ApiException; - -import java.math.BigDecimal; - -public class Main { - public static void main(String[] args) { - BigDecimal lon = new BigDecimal("9.58"); - BigDecimal lat = new BigDecimal("60.1"); - SoilApi api = new SoilApi(); - try { - SoilTypeJSON response = api.getSoilType(lon, lat, null); - System.out.println(response); - } catch (ApiException e) { - System.err.println("Exception when calling SoilApi#getSoil"); - e.printStackTrace(); - } - } -} - -``` ### Weather @@ -214,16 +116,9 @@ The generator generates a lot of the same code for each API. This library theref Generation should be done in a separate folder, and files that are relevant should be copied and adapted into this project: ```bash -openapi-generator generate -i https://api.openepi.io/crop-health/openapi.weatherJson -g java -o ./crop-health -openapi-generator generate -i https://api.openepi.io/deforestation/openapi.weatherJson -g java -o ./deforestation -openapi-generator generate -i https://api.openepi.io/flood/openapi.weatherJson -g java -o ./flood -openapi-generator generate -i https://api.openepi.io/soil/openapi.weatherJson -g java -o ./soil openapi-generator generate -i https://api.met.no/weatherapi/locationforecast/2.0/swagger -g java -o ./weather openapi-generator generate -i https://api.met.no/weatherapi/sunrise/3.0/swagger -g java -o ./sunrise ``` - -There is a special case for the geocoding api. When the api generates its openapi spec, it generates with `anyOf` and -`prefixItems`, which `openapi-generator` does not support. The following commands downloads and replaces the part that makes `openapi-generator` crash. ```bash diff --git a/pom.xml b/pom.xml index 09f9365..129f789 100644 --- a/pom.xml +++ b/pom.xml @@ -147,6 +147,19 @@ + + org.apache.maven.plugins + maven-failsafe-plugin + 3.5.4 + + + integration-test + + integration-test + + + + maven-dependency-plugin 3.6.1 diff --git a/src/main/java/io/openepi/common/GeoLocation.java b/src/main/java/io/openepi/common/GeoLocation.java new file mode 100644 index 0000000..7b1068b --- /dev/null +++ b/src/main/java/io/openepi/common/GeoLocation.java @@ -0,0 +1,45 @@ +package io.openepi.common; + +import java.util.Objects; +import java.util.Optional; + +public class GeoLocation { + private final float lat; + private final float lon; + private final Integer alt; + + public GeoLocation(final float lat, float lon, Integer alt) { + this.lat = lat; + this.lon = lon; + this.alt = alt; + } + + public GeoLocation(final float lat, float lon) { + this(lat, lon, null); + } + + public float getLat() { + return lat; + } + + public float getLon() { + return lon; + } + + public Optional getAlt() { + return Optional.ofNullable(alt); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + GeoLocation that = (GeoLocation) o; + return Float.compare(lat, that.lat) == 0 && Float.compare(lon, that.lon) == 0 && Objects.equals(alt, that.alt); + } + + @Override + public int hashCode() { + return Objects.hash(lat, lon, alt); + } +} diff --git a/src/main/java/io/openepi/crop_health/ApiClient.java b/src/main/java/io/openepi/crop_health/ApiClient.java deleted file mode 100644 index b79b3e9..0000000 --- a/src/main/java/io/openepi/crop_health/ApiClient.java +++ /dev/null @@ -1,1565 +0,0 @@ -/* - * Crop Health API - * This is a RESTful service that provides predictions for crop health.
The API consists of three pre-trained PyTorch models served using TorchServe. The models are designed to predict the health of crops based on images of the crops. The models were trained on the following crop types: maize, beans, cocoa, cassava, and banana.
The data were collected from the Harvard Dataverse and are licensed under the Creative Commons 1.0 DEED license.
The models differ in the number of classes they predict. The models are:
1. Binary model: This is a binary model that predicts the health of crops into three classes: healthy and diseased.
2. Single-HLT model: This is a multiclass model that predicts the health of crops into a single healthy (HLT) class and several diseases.
3. Multi-HLT model: This is a multiclass model that predicts the health of crops into multiple healthy (HLT) classes and several diseases.
The key difference between the single-HLT and multi-HLT models is that only the multi-HLT model has a healthy class for each crop type.
The nine specific datasets used can be found at the following URLs:
1. Spectrometry Cassava Dataset
2. Cassava Dataset Uganda
3. Maize Dataset Tanzania
4. Maize Dataset Namibia
5. Maize Dataset Uganda
6. Beans Dataset Uganda
7. Bananas Dataset Tanzania
8. KaraAgro AI Cocoa Dataset
9. KaraAgro AI Maize Dataset - * - * The version of the OpenAPI document: 0.1.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.crop_health; - -import okhttp3.*; -import okhttp3.internal.http.HttpMethod; -import okhttp3.internal.tls.OkHostnameVerifier; -import okhttp3.logging.HttpLoggingInterceptor; -import okhttp3.logging.HttpLoggingInterceptor.Level; -import okio.Buffer; -import okio.BufferedSink; -import okio.Okio; - -import javax.net.ssl.*; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; -import java.net.URI; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.text.DateFormat; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import io.openepi.common.auth.Authentication; -import io.openepi.common.auth.HttpBasicAuth; -import io.openepi.common.auth.HttpBearerAuth; -import io.openepi.common.auth.ApiKeyAuth; -import io.openepi.common.*; - -/** - *

ApiClient class.

- */ -public class ApiClient { - - private String basePath = "https://api.openepi.io/crop-health"; - protected List servers = new ArrayList(Arrays.asList( - new ServerConfiguration( - "https://api.openepi.io/crop-health", - "No description provided", - new HashMap() - ) - )); - protected Integer serverIndex = 0; - protected Map serverVariables = null; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private Map defaultCookieMap = new HashMap(); - private String tempFolderPath = null; - - private Map authentications; - - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; - - private InputStream sslCaCert; - private boolean verifyingSsl; - private KeyManager[] keyManagers; - - private OkHttpClient httpClient; - private JSON json; - - private HttpLoggingInterceptor loggingInterceptor; - - /** - * Basic constructor for ApiClient - */ - public ApiClient() { - init(); - initHttpClient(); - - // Setup authentications (key: authentication name, value: authentication). - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - /** - * Basic constructor with custom OkHttpClient - * - * @param client a {@link okhttp3.OkHttpClient} object - */ - public ApiClient(OkHttpClient client) { - init(); - - httpClient = client; - - // Setup authentications (key: authentication name, value: authentication). - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - private void initHttpClient() { - initHttpClient(Collections.emptyList()); - } - - private void initHttpClient(List interceptors) { - OkHttpClient.Builder builder = new OkHttpClient.Builder(); - builder.addNetworkInterceptor(getProgressInterceptor()); - for (Interceptor interceptor: interceptors) { - builder.addInterceptor(interceptor); - } - - httpClient = builder.build(); - } - - private void init() { - verifyingSsl = true; - - json = new JSON(); - - // Set default User-Agent. - setUserAgent("OpenAPI-Generator/0.1.10/java"); - - authentications = new HashMap(); - } - - /** - * Get base path - * - * @return Base path - */ - public String getBasePath() { - return basePath; - } - - /** - * Set base path - * - * @param basePath Base path of the URL (e.g https://api.openepi.io/crop-health - * @return An instance of OkHttpClient - */ - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - this.serverIndex = null; - return this; - } - - public List getServers() { - return servers; - } - - public ApiClient setServers(List servers) { - this.servers = servers; - return this; - } - - public Integer getServerIndex() { - return serverIndex; - } - - public ApiClient setServerIndex(Integer serverIndex) { - this.serverIndex = serverIndex; - return this; - } - - public Map getServerVariables() { - return serverVariables; - } - - public ApiClient setServerVariables(Map serverVariables) { - this.serverVariables = serverVariables; - return this; - } - - /** - * Get HTTP client - * - * @return An instance of OkHttpClient - */ - public OkHttpClient getHttpClient() { - return httpClient; - } - - /** - * Set HTTP client, which must never be null. - * - * @param newHttpClient An instance of OkHttpClient - * @return Api Client - * @throws java.lang.NullPointerException when newHttpClient is null - */ - public ApiClient setHttpClient(OkHttpClient newHttpClient) { - this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!"); - return this; - } - - /** - * Get JSON - * - * @return JSON object - */ - public JSON getJSON() { - return json; - } - - /** - * Set JSON - * - * @param json JSON object - * @return Api client - */ - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - /** - * True if isVerifyingSsl flag is on - * - * @return True if isVerifySsl flag is on - */ - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - * - * @param verifyingSsl True to verify TLS/SSL connection - * @return ApiClient - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - /** - * Get SSL CA cert. - * - * @return Input stream to the SSL CA cert - */ - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - * - * @param sslCaCert input stream for SSL CA cert - * @return ApiClient - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - /** - *

Getter for the field keyManagers.

- * - * @return an array of {@link javax.net.ssl.KeyManager} objects - */ - public KeyManager[] getKeyManagers() { - return keyManagers; - } - - /** - * Configure client keys to use for authorization in an SSL session. - * Use null to reset to default. - * - * @param managers The KeyManagers to use - * @return ApiClient - */ - public ApiClient setKeyManagers(KeyManager[] managers) { - this.keyManagers = managers; - applySslSettings(); - return this; - } - - /** - *

Getter for the field dateFormat.

- * - * @return a {@link java.text.DateFormat} object - */ - public DateFormat getDateFormat() { - return dateFormat; - } - - /** - *

Setter for the field dateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link io.openepi.crop_health.ApiClient} object - */ - public ApiClient setDateFormat(DateFormat dateFormat) { - JSON.setDateFormat(dateFormat); - return this; - } - - /** - *

Set SqlDateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link io.openepi.crop_health.ApiClient} object - */ - public ApiClient setSqlDateFormat(DateFormat dateFormat) { - JSON.setSqlDateFormat(dateFormat); - return this; - } - - /** - *

Set OffsetDateTimeFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link io.openepi.crop_health.ApiClient} object - */ - public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - JSON.setOffsetDateTimeFormat(dateFormat); - return this; - } - - /** - *

Set LocalDateFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link io.openepi.crop_health.ApiClient} object - */ - public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { - JSON.setLocalDateFormat(dateFormat); - return this; - } - - /** - *

Set LenientOnJson.

- * - * @param lenientOnJson a boolean - * @return a {@link io.openepi.crop_health.ApiClient} object - */ - public ApiClient setLenientOnJson(boolean lenientOnJson) { - JSON.setLenientOnJson(lenientOnJson); - return this; - } - - /** - * Get authentications (key: authentication name, value: authentication). - * - * @return Map of authentication objects - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - - /** - * Helper method to set username for the first HTTP basic authentication. - * - * @param username Username - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - * - * @param password Password - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - * - * @param apiKey API key - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - * - * @param apiKeyPrefix API key prefix - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - * - * @param accessToken Access token - */ - public void setAccessToken(String accessToken) { - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Helper method to set credentials for AWSV4 Signature - * - * @param accessKey Access Key - * @param secretKey Secret Key - * @param region Region - * @param service Service to access to - */ - public void setAWS4Configuration(String accessKey, String secretKey, String region, String service) { - throw new RuntimeException("No AWS4 authentication configured!"); - } - - /** - * Helper method to set credentials for AWSV4 Signature - * - * @param accessKey Access Key - * @param secretKey Secret Key - * @param sessionToken Session Token - * @param region Region - * @param service Service to access to - */ - public void setAWS4Configuration(String accessKey, String secretKey, String sessionToken, String region, String service) { - throw new RuntimeException("No AWS4 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - * - * @param userAgent HTTP request's user agent - * @return ApiClient - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - * @return ApiClient - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * Add a default cookie. - * - * @param key The cookie's key - * @param value The cookie's value - * @return ApiClient - */ - public ApiClient addDefaultCookie(String key, String value) { - defaultCookieMap.put(key, value); - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - * - * @return True if debugging is enabled, false otherwise. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - * @return ApiClient - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); - } else { - final OkHttpClient.Builder builder = httpClient.newBuilder(); - builder.interceptors().remove(loggingInterceptor); - httpClient = builder.build(); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default temporary folder. - * - * @see createTempFile - * @return Temporary folder path - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - /** - * Set the temporary folder path (for downloading files) - * - * @param tempFolderPath Temporary folder path - * @return ApiClient - */ - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Get connection timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getConnectTimeout() { - return httpClient.connectTimeoutMillis(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param connectionTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - /** - * Get read timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getReadTimeout() { - return httpClient.readTimeoutMillis(); - } - - /** - * Sets the read timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param readTimeout read timeout in milliseconds - * @return Api client - */ - public ApiClient setReadTimeout(int readTimeout) { - httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - /** - * Get write timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getWriteTimeout() { - return httpClient.writeTimeoutMillis(); - } - - /** - * Sets the write timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param writeTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setWriteTimeout(int writeTimeout) { - httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - - /** - * Format the given parameter object into string. - * - * @param param Parameter - * @return String representation of the parameter - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) { - //Serialize to json string and remove the " enclosing characters - String jsonStr = JSON.serialize(param); - return jsonStr.substring(1, jsonStr.length() - 1); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection) param) { - if (b.length() > 0) { - b.append(","); - } - b.append(o); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /** - * Formats the specified query parameter to a list containing a single {@code Pair} object. - * - * Note that {@code value} must not be a collection. - * - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list containing a single {@code Pair} object. - */ - public List parameterToPair(String name, Object value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value instanceof Collection) { - return params; - } - - params.add(new Pair(name, parameterToString(value))); - return params; - } - - /** - * Formats the specified collection query parameters to a list of {@code Pair} objects. - * - * Note that the values of each of the returned Pair objects are percent-encoded. - * - * @param collectionFormat The collection format of the parameter. - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list of {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Collection value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value.isEmpty()) { - return params; - } - - // create the params based on the collection format - if ("multi".equals(collectionFormat)) { - for (Object item : value) { - params.add(new Pair(name, escapeString(parameterToString(item)))); - } - return params; - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - // escape all delimiters except commas, which are URI reserved - // characters - if ("ssv".equals(collectionFormat)) { - delimiter = escapeString(" "); - } else if ("tsv".equals(collectionFormat)) { - delimiter = escapeString("\t"); - } else if ("pipes".equals(collectionFormat)) { - delimiter = escapeString("|"); - } - - StringBuilder sb = new StringBuilder(); - for (Object item : value) { - sb.append(delimiter); - sb.append(escapeString(parameterToString(item))); - } - - params.add(new Pair(name, sb.substring(delimiter.length()))); - - return params; - } - - /** - * Formats the specified collection path parameter to a string value. - * - * @param collectionFormat The collection format of the parameter. - * @param value The value of the parameter. - * @return String representation of the parameter - */ - public String collectionPathParameterToString(String collectionFormat, Collection value) { - // create the value based on the collection format - if ("multi".equals(collectionFormat)) { - // not valid for path params - return parameterToString(value); - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - if ("ssv".equals(collectionFormat)) { - delimiter = " "; - } else if ("tsv".equals(collectionFormat)) { - delimiter = "\t"; - } else if ("pipes".equals(collectionFormat)) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : value) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - return sb.substring(delimiter.length()); - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * application/vnd.company+json - * "* / *" is also default to JSON - * @param mime MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public boolean isJsonMime(String mime) { - String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; - return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * returns null. If it matches "any", JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return null; - } - - if (contentTypes[0].equals("*/*")) { - return "application/json"; - } - - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - * - * @param str String to be escaped - * @return Escaped string - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param Type - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws io.openepi.common.ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - @SuppressWarnings("unchecked") - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; - } - - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); - } - - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); - } - - if (respBody == null || "".equals(respBody)) { - return null; - } - - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return JSON.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } - } - - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws io.openepi.common.ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create((File) obj, MediaType.parse(contentType)); - } else if ("text/plain".equals(contentType) && obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - return RequestBody.create(content, MediaType.parse(contentType)); - } else if (obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } - } - - /** - * Download file from the given response. - * - * @param response An instance of the Response object - * @throws io.openepi.common.ApiException If fail to read file content from response and write to disk - * @return Downloaded file - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * Prepare file for download - * - * @param response An instance of the Response object - * @return Prepared file for the download - * @throws java.io.IOException If fail to prepare file for download - */ - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } - } - - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // Files.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; - } - - if (tempFolderPath == null) - return Files.createTempFile(prefix, suffix).toFile(); - else - return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); - } - - /** - * {@link #execute(Call, Type)} - * - * @param Type - * @param call An instance of the Call object - * @return ApiResponse<T> - * @throws io.openepi.common.ApiException If fail to execute the call - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @param call Call - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws io.openepi.common.ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * {@link #executeAsync(Call, Type, ApiCallback)} - * - * @param Type - * @param call An instance of the Call object - * @param callback ApiCallback<T> - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } - - /** - * Execute HTTP call asynchronously. - * - * @param Type - * @param call The callback to be executed when the API call finishes - * @param returnType Return type - * @param callback ApiCallback - * @see #execute(Call, Type) - */ - @SuppressWarnings("unchecked") - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } - - @Override - public void onResponse(Call call, Response response) throws IOException { - T result; - try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; - } catch (Exception e) { - callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); - return; - } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @param Type - * @param response Response - * @param returnType Return type - * @return Type - * @throws io.openepi.common.ApiException If the response has an unsuccessful status code or - * fail to deserialize the response body - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - if (response.body() != null) { - try { - response.body().close(); - } catch (Exception e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { - try { - respBody = response.body().string(); - } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - - /** - * Build HTTP call with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP call - * @throws io.openepi.common.ApiException If fail to serialize the request body object - */ - public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); - - return httpClient.newCall(request); - } - - /** - * Build an HTTP request with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP request - * @throws io.openepi.common.ApiException If fail to serialize the request body object - */ - public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams - List allQueryParams = new ArrayList(queryParams); - allQueryParams.addAll(collectionQueryParams); - - final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); - - // prepare HTTP request body - RequestBody reqBody; - String contentType = headerParams.get("Content-Type"); - String contentTypePure = contentType; - if (contentTypePure != null && contentTypePure.contains(";")) { - contentTypePure = contentType.substring(0, contentType.indexOf(";")); - } - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentTypePure)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentTypePure)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create("", contentType == null ? null : MediaType.parse(contentType)); - } - } else { - reqBody = serialize(body, contentType); - } - - // update parameters with authentication settings - updateParamsForAuth(authNames, allQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url)); - - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - processCookieParams(cookieParams, reqBuilder); - - // Associate callback with request (if not null) so interceptor can - // access it when creating ProgressResponseBody - reqBuilder.tag(callback); - - Request request = null; - - if (callback != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return request; - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param baseUrl The base URL - * @param path The sub path - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @return The full URL - */ - public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { - final StringBuilder url = new StringBuilder(); - if (baseUrl != null) { - url.append(baseUrl).append(path); - } else { - String baseURL; - if (serverIndex != null) { - if (serverIndex < 0 || serverIndex >= servers.size()) { - throw new ArrayIndexOutOfBoundsException(String.format( - "Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size() - )); - } - baseURL = servers.get(serverIndex).URL(serverVariables); - } else { - baseURL = basePath; - } - url.append(baseURL).append(path); - } - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { - String prefix = url.toString().contains("?") ? "&" : "?"; - for (Pair param : collectionQueryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - // collection query parameter value already escaped as part of parameterToPairs - url.append(escapeString(param.getName())).append("=").append(value); - } - } - } - - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - * - * @param headerParams Header parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Set cookie parameters to the request builder, including default cookies. - * - * @param cookieParams Cookie parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processCookieParams(Map cookieParams, Request.Builder reqBuilder) { - for (Entry param : cookieParams.entrySet()) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - for (Entry param : defaultCookieMap.entrySet()) { - if (!cookieParams.containsKey(param.getKey())) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - * @param cookieParams Map of cookie parameters - * @param payload HTTP request body - * @param method HTTP method - * @param uri URI - * @throws io.openepi.common.ApiException If fails to update the parameters - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, - Map cookieParams, String payload, String method, URI uri) throws ApiException { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) { - throw new RuntimeException("Authentication undefined: " + authName); - } - auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); - } - } - - /** - * Build a form-encoding request body with the given form parameters. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - addPartToMultiPartBuilder(mpBuilder, param.getKey(), file); - } else if (param.getValue() instanceof List) { - List list = (List) param.getValue(); - for (Object item: list) { - if (item instanceof File) { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item); - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The guessed Content-Type - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - - /** - * Add a Content-Disposition Header for the given key and file to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param file The file to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, File file) { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); - } - - /** - * Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param obj The complex object to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) { - RequestBody requestBody; - if (obj instanceof String) { - requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain")); - } else { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - requestBody = RequestBody.create(content, MediaType.parse("application/json")); - } - - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""); - mpBuilder.addPart(partHeaders, requestBody); - } - - /** - * Get network interceptor to add it to the httpClient to track download progress for - * async requests. - */ - private Interceptor getProgressInterceptor() { - return new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - final Request request = chain.request(); - final Response originalResponse = chain.proceed(request); - if (request.tag() instanceof ApiCallback) { - final ApiCallback callback = (ApiCallback) request.tag(); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), callback)) - .build(); - } - return originalResponse; - } - }; - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { - try { - TrustManager[] trustManagers; - HostnameVerifier hostnameVerifier; - if (!verifyingSsl) { - trustManagers = new TrustManager[]{ - new X509TrustManager() { - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[]{}; - } - } - }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - } else { - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - - if (sslCaCert == null) { - trustManagerFactory.init((KeyStore) null); - } else { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); - } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + (index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); - } - trustManagerFactory.init(caKeyStore); - } - trustManagers = trustManagerFactory.getTrustManagers(); - hostnameVerifier = OkHostnameVerifier.INSTANCE; - } - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient = httpClient.newBuilder() - .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) - .hostnameVerifier(hostnameVerifier) - .build(); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); - } - } - - /** - * Convert the HTTP request body to a string. - * - * @param requestBody The HTTP request object - * @return The string representation of the HTTP request body - * @throws io.openepi.common.ApiException If fail to serialize the request body object into a string - */ - private String requestBodyToString(RequestBody requestBody) throws ApiException { - if (requestBody != null) { - try { - final Buffer buffer = new Buffer(); - requestBody.writeTo(buffer); - return buffer.readUtf8(); - } catch (final IOException e) { - throw new ApiException(e); - } - } - - // empty http request body - return ""; - } -} diff --git a/src/main/java/io/openepi/crop_health/Configuration.java b/src/main/java/io/openepi/crop_health/Configuration.java deleted file mode 100644 index e11a65d..0000000 --- a/src/main/java/io/openepi/crop_health/Configuration.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Crop Health API - * This is a RESTful service that provides predictions for crop health.
The API consists of three pre-trained PyTorch models served using TorchServe. The models are designed to predict the health of crops based on images of the crops. The models were trained on the following crop types: maize, beans, cocoa, cassava, and banana.
The data were collected from the Harvard Dataverse and are licensed under the Creative Commons 1.0 DEED license.
The models differ in the number of classes they predict. The models are:
1. Binary model: This is a binary model that predicts the health of crops into three classes: healthy and diseased.
2. Single-HLT model: This is a multiclass model that predicts the health of crops into a single healthy (HLT) class and several diseases.
3. Multi-HLT model: This is a multiclass model that predicts the health of crops into multiple healthy (HLT) classes and several diseases.
The key difference between the single-HLT and multi-HLT models is that only the multi-HLT model has a healthy class for each crop type.
The nine specific datasets used can be found at the following URLs:
1. Spectrometry Cassava Dataset
2. Cassava Dataset Uganda
3. Maize Dataset Tanzania
4. Maize Dataset Namibia
5. Maize Dataset Uganda
6. Beans Dataset Uganda
7. Bananas Dataset Tanzania
8. KaraAgro AI Cocoa Dataset
9. KaraAgro AI Maize Dataset - * - * The version of the OpenAPI document: 0.1.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.crop_health; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-26T11:13:50.974079+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class Configuration { - public static final String VERSION = "0.1.10"; - - private static ApiClient defaultApiClient = new ApiClient(); - - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - * - * @return Default API client - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } - - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - * - * @param apiClient API client - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } -} diff --git a/src/main/java/io/openepi/crop_health/JSON.java b/src/main/java/io/openepi/crop_health/JSON.java deleted file mode 100644 index 990d47e..0000000 --- a/src/main/java/io/openepi/crop_health/JSON.java +++ /dev/null @@ -1,405 +0,0 @@ -/* - * Crop Health API - * This is a RESTful service that provides predictions for crop health.
The API consists of three pre-trained PyTorch models served using TorchServe. The models are designed to predict the health of crops based on images of the crops. The models were trained on the following crop types: maize, beans, cocoa, cassava, and banana.
The data were collected from the Harvard Dataverse and are licensed under the Creative Commons 1.0 DEED license.
The models differ in the number of classes they predict. The models are:
1. Binary model: This is a binary model that predicts the health of crops into three classes: healthy and diseased.
2. Single-HLT model: This is a multiclass model that predicts the health of crops into a single healthy (HLT) class and several diseases.
3. Multi-HLT model: This is a multiclass model that predicts the health of crops into multiple healthy (HLT) classes and several diseases.
The key difference between the single-HLT and multi-HLT models is that only the multi-HLT model has a healthy class for each crop type.
The nine specific datasets used can be found at the following URLs:
1. Spectrometry Cassava Dataset
2. Cassava Dataset Uganda
3. Maize Dataset Tanzania
4. Maize Dataset Namibia
5. Maize Dataset Uganda
6. Beans Dataset Uganda
7. Bananas Dataset Tanzania
8. KaraAgro AI Cocoa Dataset
9. KaraAgro AI Maize Dataset - * - * The version of the OpenAPI document: 0.1.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.crop_health; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.internal.bind.util.ISO8601Utils; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonElement; -import io.gsonfire.GsonFireBuilder; -import io.gsonfire.TypeSelector; - -import okio.ByteString; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Type; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.ParsePosition; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.Locale; -import java.util.Map; -import java.util.HashMap; - -/* - * A JSON utility class - * - * NOTE: in the future, this class may be converted to static, which may break - * backward-compatibility - */ -public class JSON { - private static Gson gson; - private static boolean isLenientOnJson = false; - private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); - private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); - private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); - private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); - private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - - @SuppressWarnings("unchecked") - public static GsonBuilder createGson() { - GsonFireBuilder fireBuilder = new GsonFireBuilder() - ; - GsonBuilder builder = fireBuilder.createGsonBuilder(); - return builder; - } - - private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { - JsonElement element = readElement.getAsJsonObject().get(discriminatorField); - if (null == element) { - throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); - } - return element.getAsString(); - } - - /** - * Returns the Java class that implements the OpenAPI schema for the specified discriminator value. - * - * @param classByDiscriminatorValue The map of discriminator values to Java classes. - * @param discriminatorValue The value of the OpenAPI discriminator in the input data. - * @return The Java class that implements the OpenAPI schema - */ - private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { - Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue); - if (null == clazz) { - throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); - } - return clazz; - } - - static { - GsonBuilder gsonBuilder = createGson(); - gsonBuilder.registerTypeAdapter(Date.class, dateTypeAdapter); - gsonBuilder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); - gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); - gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); - gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.crop_health.model.BinaryPredictionResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.crop_health.model.MultiHLTPredictionResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.crop_health.model.Ping200Response.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.crop_health.model.Ping500Response.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.crop_health.model.SingleHLTPredictionResponse.CustomTypeAdapterFactory()); - gson = gsonBuilder.create(); - } - - /** - * Get Gson. - * - * @return Gson - */ - public static Gson getGson() { - return gson; - } - - /** - * Set Gson. - * - * @param gson Gson - */ - public static void setGson(Gson gson) { - JSON.gson = gson; - } - - public static void setLenientOnJson(boolean lenientOnJson) { - isLenientOnJson = lenientOnJson; - } - - /** - * Serialize the given Java object into JSON string. - * - * @param obj Object - * @return String representation of the JSON - */ - public static String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param Type - * @param body The JSON string - * @param returnType The type to deserialize into - * @return The deserialized Java object - */ - @SuppressWarnings("unchecked") - public static T deserialize(String body, Type returnType) { - try { - if (isLenientOnJson) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - if (returnType.equals(String.class)) { - return (T) body; - } else { - throw (e); - } - } - } - - /** - * Gson TypeAdapter for Byte Array type - */ - public static class ByteArrayAdapter extends TypeAdapter { - - @Override - public void write(JsonWriter out, byte[] value) throws IOException { - if (value == null) { - out.nullValue(); - } else { - out.value(ByteString.of(value).base64()); - } - } - - @Override - public byte[] read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String bytesAsBase64 = in.nextString(); - ByteString byteString = ByteString.decodeBase64(bytesAsBase64); - return byteString.toByteArray(); - } - } - } - - /** - * Gson TypeAdapter for JSR310 OffsetDateTime type - */ - public static class OffsetDateTimeTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public OffsetDateTimeTypeAdapter() { - this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); - } - - public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, OffsetDateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public OffsetDateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - if (date.endsWith("+0000")) { - date = date.substring(0, date.length()-5) + "Z"; - } - return OffsetDateTime.parse(date, formatter); - } - } - } - - /** - * Gson TypeAdapter for JSR310 LocalDate type - */ - public static class LocalDateTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public LocalDateTypeAdapter() { - this(DateTimeFormatter.ISO_LOCAL_DATE); - } - - public LocalDateTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return LocalDate.parse(date, formatter); - } - } - } - - public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - offsetDateTimeTypeAdapter.setFormat(dateFormat); - } - - public static void setLocalDateFormat(DateTimeFormatter dateFormat) { - localDateTypeAdapter.setFormat(dateFormat); - } - - /** - * Gson TypeAdapter for java.sql.Date type - * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used - * (more efficient than SimpleDateFormat). - */ - public static class SqlDateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public SqlDateTypeAdapter() {} - - public SqlDateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, java.sql.Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = date.toString(); - } - out.value(value); - } - } - - @Override - public java.sql.Date read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return new java.sql.Date(dateFormat.parse(date).getTime()); - } - return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } - } - - /** - * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, ISO8601Utils will be used. - */ - public static class DateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public DateTypeAdapter() {} - - public DateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = ISO8601Utils.format(date, true); - } - out.value(value); - } - } - - @Override - public Date read(JsonReader in) throws IOException { - try { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return dateFormat.parse(date); - } - return ISO8601Utils.parse(date, new ParsePosition(0)); - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } catch (IllegalArgumentException e) { - throw new JsonParseException(e); - } - } - } - - public static void setDateFormat(DateFormat dateFormat) { - dateTypeAdapter.setFormat(dateFormat); - } - - public static void setSqlDateFormat(DateFormat dateFormat) { - sqlDateTypeAdapter.setFormat(dateFormat); - } -} diff --git a/src/main/java/io/openepi/crop_health/api/CropHealthApi.java b/src/main/java/io/openepi/crop_health/api/CropHealthApi.java deleted file mode 100644 index 4919b13..0000000 --- a/src/main/java/io/openepi/crop_health/api/CropHealthApi.java +++ /dev/null @@ -1,594 +0,0 @@ -/* - * Crop Health API - * This is a RESTful service that provides predictions for crop health.
The API consists of three pre-trained PyTorch models served using TorchServe. The models are designed to predict the health of crops based on images of the crops. The models were trained on the following crop types: maize, beans, cocoa, cassava, and banana.
The data were collected from the Harvard Dataverse and are licensed under the Creative Commons 1.0 DEED license.
The models differ in the number of classes they predict. The models are:
1. Binary model: This is a binary model that predicts the health of crops into three classes: healthy and diseased.
2. Single-HLT model: This is a multiclass model that predicts the health of crops into a single healthy (HLT) class and several diseases.
3. Multi-HLT model: This is a multiclass model that predicts the health of crops into multiple healthy (HLT) classes and several diseases.
The key difference between the single-HLT and multi-HLT models is that only the multi-HLT model has a healthy class for each crop type.
The nine specific datasets used can be found at the following URLs:
1. Spectrometry Cassava Dataset
2. Cassava Dataset Uganda
3. Maize Dataset Tanzania
4. Maize Dataset Namibia
5. Maize Dataset Uganda
6. Beans Dataset Uganda
7. Bananas Dataset Tanzania
8. KaraAgro AI Cocoa Dataset
9. KaraAgro AI Maize Dataset - * - * The version of the OpenAPI document: 0.1.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.crop_health.api; - -import io.openepi.crop_health.ApiClient; -import io.openepi.crop_health.Configuration; -import io.openepi.common.ApiCallback; -import io.openepi.common.ApiException; -import io.openepi.common.ApiResponse; -import io.openepi.common.Pair; - -import com.google.gson.reflect.TypeToken; - - -import io.openepi.crop_health.model.BinaryPredictionResponse; -import io.openepi.crop_health.model.MultiHLTPredictionResponse; -import io.openepi.crop_health.model.Ping200Response; -import io.openepi.crop_health.model.SingleHLTPredictionResponse; - -import java.io.File; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class CropHealthApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public CropHealthApi() { - this(Configuration.getDefaultApiClient()); - } - - public CropHealthApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for ping - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 TorchServe status -
500 Internal Server Error -
- */ - public okhttp3.Call pingCall(final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/ping"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call pingValidateBeforeCall(final ApiCallback _callback) throws ApiException { - return pingCall(_callback); - - } - - /** - * - * Get TorchServe status. - * @return Ping200Response - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 TorchServe status -
500 Internal Server Error -
- */ - public Ping200Response ping() throws ApiException { - ApiResponse localVarResp = pingWithHttpInfo(); - return localVarResp.getData(); - } - - /** - * - * Get TorchServe status. - * @return ApiResponse<Ping200Response> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 TorchServe status -
500 Internal Server Error -
- */ - public ApiResponse pingWithHttpInfo() throws ApiException { - okhttp3.Call localVarCall = pingValidateBeforeCall(null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * (asynchronously) - * Get TorchServe status. - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 TorchServe status -
500 Internal Server Error -
- */ - public okhttp3.Call pingAsync(final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = pingValidateBeforeCall(_callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for predictionsWithBinary - * @param body Picture of a plant. (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - - - -
Status Code Description Response Headers
404 Model not found or Model Version not found -
500 Internal Server Error -
503 No worker is available to serve request -
200 Predicted class confidences, all summing to 1.0. -
- */ - public okhttp3.Call predictionsWithBinaryCall(File body, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/predictions/binary"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call predictionsWithBinaryValidateBeforeCall(File body, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling predictionsWithBinary(Async)"); - } - - return predictionsWithBinaryCall(body, _callback); - - } - - /** - * - * Health predictions by the Binary model. - * @param body Picture of a plant. (required) - * @return BinaryPredictionResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - - -
Status Code Description Response Headers
404 Model not found or Model Version not found -
500 Internal Server Error -
503 No worker is available to serve request -
200 Predicted class confidences, all summing to 1.0. -
- */ - public BinaryPredictionResponse postPredictionBinary(File body) throws ApiException { - ApiResponse localVarResp = predictionsWithBinaryWithHttpInfo(body); - return localVarResp.getData(); - } - - /** - * - * Health predictions by the Binary model. - * @param body Picture of a plant. (required) - * @return ApiResponse<BinaryPredictionResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - - -
Status Code Description Response Headers
404 Model not found or Model Version not found -
500 Internal Server Error -
503 No worker is available to serve request -
200 Predicted class confidences, all summing to 1.0. -
- */ - public ApiResponse predictionsWithBinaryWithHttpInfo(File body) throws ApiException { - okhttp3.Call localVarCall = predictionsWithBinaryValidateBeforeCall(body, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * (asynchronously) - * Health predictions by the Binary model. - * @param body Picture of a plant. (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - - -
Status Code Description Response Headers
404 Model not found or Model Version not found -
500 Internal Server Error -
503 No worker is available to serve request -
200 Predicted class confidences, all summing to 1.0. -
- */ - public okhttp3.Call postPredictionBinaryAsync(File body, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = predictionsWithBinaryValidateBeforeCall(body, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for predictionsWithMultiHLT - * @param body Picture of a plant. (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - - - -
Status Code Description Response Headers
404 Model not found or Model Version not found -
500 Internal Server Error -
503 No worker is available to serve request -
200 Predicted class confidences, all summing to 1.0. -
- */ - public okhttp3.Call predictionsWithMultiHLTCall(File body, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/predictions/multi-HLT"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call predictionsWithMultiHLTValidateBeforeCall(File body, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling predictionsWithMultiHLT(Async)"); - } - - return predictionsWithMultiHLTCall(body, _callback); - - } - - /** - * - * Health predictions by the MultiHLT model. - * @param body Picture of a plant. (required) - * @return MultiHLTPredictionResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - - -
Status Code Description Response Headers
404 Model not found or Model Version not found -
500 Internal Server Error -
503 No worker is available to serve request -
200 Predicted class confidences, all summing to 1.0. -
- */ - public MultiHLTPredictionResponse postPredictionMulti(File body) throws ApiException { - ApiResponse localVarResp = predictionsWithMultiHLTWithHttpInfo(body); - return localVarResp.getData(); - } - - /** - * - * Health predictions by the MultiHLT model. - * @param body Picture of a plant. (required) - * @return ApiResponse<MultiHLTPredictionResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - - -
Status Code Description Response Headers
404 Model not found or Model Version not found -
500 Internal Server Error -
503 No worker is available to serve request -
200 Predicted class confidences, all summing to 1.0. -
- */ - public ApiResponse predictionsWithMultiHLTWithHttpInfo(File body) throws ApiException { - okhttp3.Call localVarCall = predictionsWithMultiHLTValidateBeforeCall(body, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * (asynchronously) - * Health predictions by the MultiHLT model. - * @param body Picture of a plant. (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - - -
Status Code Description Response Headers
404 Model not found or Model Version not found -
500 Internal Server Error -
503 No worker is available to serve request -
200 Predicted class confidences, all summing to 1.0. -
- */ - public okhttp3.Call postPredictionMultiAsync(File body, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = predictionsWithMultiHLTValidateBeforeCall(body, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for predictionsWithSingleHLT - * @param body Picture of a plant. (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - - - -
Status Code Description Response Headers
404 Model not found or Model Version not found -
500 Internal Server Error -
503 No worker is available to serve request -
200 Predicted class confidences, all summing to 1.0. -
- */ - public okhttp3.Call predictionsWithSingleHLTCall(File body, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/predictions/single-HLT"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call predictionsWithSingleHLTValidateBeforeCall(File body, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling predictionsWithSingleHLT(Async)"); - } - - return predictionsWithSingleHLTCall(body, _callback); - - } - - /** - * - * Health predictions by the SingleHLT model. - * @param body Picture of a plant. (required) - * @return SingleHLTPredictionResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - - -
Status Code Description Response Headers
404 Model not found or Model Version not found -
500 Internal Server Error -
503 No worker is available to serve request -
200 Predicted class confidences, all summing to 1.0. -
- */ - public SingleHLTPredictionResponse postPredictionSingle(File body) throws ApiException { - ApiResponse localVarResp = predictionsWithSingleHLTWithHttpInfo(body); - return localVarResp.getData(); - } - - /** - * - * Health predictions by the SingleHLT model. - * @param body Picture of a plant. (required) - * @return ApiResponse<SingleHLTPredictionResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - - -
Status Code Description Response Headers
404 Model not found or Model Version not found -
500 Internal Server Error -
503 No worker is available to serve request -
200 Predicted class confidences, all summing to 1.0. -
- */ - public ApiResponse predictionsWithSingleHLTWithHttpInfo(File body) throws ApiException { - okhttp3.Call localVarCall = predictionsWithSingleHLTValidateBeforeCall(body, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * (asynchronously) - * Health predictions by the SingleHLT model. - * @param body Picture of a plant. (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - - -
Status Code Description Response Headers
404 Model not found or Model Version not found -
500 Internal Server Error -
503 No worker is available to serve request -
200 Predicted class confidences, all summing to 1.0. -
- */ - public okhttp3.Call postPredictionSingleAsync(File body, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = predictionsWithSingleHLTValidateBeforeCall(body, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } -} diff --git a/src/main/java/io/openepi/crop_health/model/AbstractOpenApiSchema.java b/src/main/java/io/openepi/crop_health/model/AbstractOpenApiSchema.java deleted file mode 100644 index eaff2bc..0000000 --- a/src/main/java/io/openepi/crop_health/model/AbstractOpenApiSchema.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Crop Health API - * This is a RESTful service that provides predictions for crop health.
The API consists of three pre-trained PyTorch models served using TorchServe. The models are designed to predict the health of crops based on images of the crops. The models were trained on the following crop types: maize, beans, cocoa, cassava, and banana.
The data were collected from the Harvard Dataverse and are licensed under the Creative Commons 1.0 DEED license.
The models differ in the number of classes they predict. The models are:
1. Binary model: This is a binary model that predicts the health of crops into three classes: healthy and diseased.
2. Single-HLT model: This is a multiclass model that predicts the health of crops into a single healthy (HLT) class and several diseases.
3. Multi-HLT model: This is a multiclass model that predicts the health of crops into multiple healthy (HLT) classes and several diseases.
The key difference between the single-HLT and multi-HLT models is that only the multi-HLT model has a healthy class for each crop type.
The nine specific datasets used can be found at the following URLs:
1. Spectrometry Cassava Dataset
2. Cassava Dataset Uganda
3. Maize Dataset Tanzania
4. Maize Dataset Namibia
5. Maize Dataset Uganda
6. Beans Dataset Uganda
7. Bananas Dataset Tanzania
8. KaraAgro AI Cocoa Dataset
9. KaraAgro AI Maize Dataset - * - * The version of the OpenAPI document: 0.1.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.crop_health.model; - -import io.openepi.common.ApiException; -import java.util.Objects; -import java.lang.reflect.Type; -import java.util.Map; - -/** - * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-26T11:13:50.974079+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public abstract class AbstractOpenApiSchema { - - // store the actual instance of the schema/object - private Object instance; - - // is nullable - private Boolean isNullable; - - // schema type (e.g. oneOf, anyOf) - private final String schemaType; - - public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { - this.schemaType = schemaType; - this.isNullable = isNullable; - } - - /** - * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object - * - * @return an instance of the actual schema/object - */ - public abstract Map> getSchemas(); - - /** - * Get the actual instance - * - * @return an instance of the actual schema/object - */ - //@JsonValue - public Object getActualInstance() {return instance;} - - /** - * Set the actual instance - * - * @param instance the actual instance of the schema/object - */ - public void setActualInstance(Object instance) {this.instance = instance;} - - /** - * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well - * - * @return an instance of the actual schema/object - */ - public Object getActualInstanceRecursively() { - return getActualInstanceRecursively(this); - } - - private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { - if (object.getActualInstance() == null) { - return null; - } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { - return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); - } else { - return object.getActualInstance(); - } - } - - /** - * Get the schema type (e.g. anyOf, oneOf) - * - * @return the schema type - */ - public String getSchemaType() { - return schemaType; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ").append(getClass()).append(" {\n"); - sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); - sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); - sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; - return Objects.equals(this.instance, a.instance) && - Objects.equals(this.isNullable, a.isNullable) && - Objects.equals(this.schemaType, a.schemaType); - } - - @Override - public int hashCode() { - return Objects.hash(instance, isNullable, schemaType); - } - - /** - * Is nullable - * - * @return true if it's nullable - */ - public Boolean isNullable() { - if (Boolean.TRUE.equals(isNullable)) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } - - - -} diff --git a/src/main/java/io/openepi/crop_health/model/BinaryPredictionResponse.java b/src/main/java/io/openepi/crop_health/model/BinaryPredictionResponse.java deleted file mode 100644 index 06845f1..0000000 --- a/src/main/java/io/openepi/crop_health/model/BinaryPredictionResponse.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Crop Health API - * This is a RESTful service that provides predictions for crop health.
The API consists of three pre-trained PyTorch models served using TorchServe. The models are designed to predict the health of crops based on images of the crops. The models were trained on the following crop types: maize, beans, cocoa, cassava, and banana.
The data were collected from the Harvard Dataverse and are licensed under the Creative Commons 1.0 DEED license.
The models differ in the number of classes they predict. The models are:
1. Binary model: This is a binary model that predicts the health of crops into three classes: healthy and diseased.
2. Single-HLT model: This is a multiclass model that predicts the health of crops into a single healthy (HLT) class and several diseases.
3. Multi-HLT model: This is a multiclass model that predicts the health of crops into multiple healthy (HLT) classes and several diseases.
The key difference between the single-HLT and multi-HLT models is that only the multi-HLT model has a healthy class for each crop type.
The nine specific datasets used can be found at the following URLs:
1. Spectrometry Cassava Dataset
2. Cassava Dataset Uganda
3. Maize Dataset Tanzania
4. Maize Dataset Namibia
5. Maize Dataset Uganda
6. Beans Dataset Uganda
7. Bananas Dataset Tanzania
8. KaraAgro AI Cocoa Dataset
9. KaraAgro AI Maize Dataset - * - * The version of the OpenAPI document: 0.1.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.crop_health.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.crop_health.JSON; - -/** - * BinaryPredictionResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-26T11:13:50.974079+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class BinaryPredictionResponse { - public static final String SERIALIZED_NAME_H_L_T = "HLT"; - @SerializedName(SERIALIZED_NAME_H_L_T) - private BigDecimal HLT; - - public static final String SERIALIZED_NAME_N_O_T_H_L_T = "NOT_HLT"; - @SerializedName(SERIALIZED_NAME_N_O_T_H_L_T) - private BigDecimal NOT_HLT; - - public BinaryPredictionResponse() { - } - - public BinaryPredictionResponse HLT(BigDecimal HLT) { - this.HLT = HLT; - return this; - } - - /** - * Healthy - * @return HLT - */ - @javax.annotation.Nonnull - public BigDecimal getHLT() { - return HLT; - } - - public void setHLT(BigDecimal HLT) { - this.HLT = HLT; - } - - - public BinaryPredictionResponse NOT_HLT(BigDecimal NOT_HLT) { - this.NOT_HLT = NOT_HLT; - return this; - } - - /** - * Not Healthy - * @return NOT_HLT - */ - @javax.annotation.Nonnull - public BigDecimal getNOTHLT() { - return NOT_HLT; - } - - public void setNOTHLT(BigDecimal NOT_HLT) { - this.NOT_HLT = NOT_HLT; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - BinaryPredictionResponse binaryPredictionResponse = (BinaryPredictionResponse) o; - return Objects.equals(this.HLT, binaryPredictionResponse.HLT) && - Objects.equals(this.NOT_HLT, binaryPredictionResponse.NOT_HLT); - } - - @Override - public int hashCode() { - return Objects.hash(HLT, NOT_HLT); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class BinaryPredictionResponse {\n"); - sb.append(" HLT: ").append(toIndentedString(HLT)).append("\n"); - sb.append(" NOT_HLT: ").append(toIndentedString(NOT_HLT)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("HLT"); - openapiFields.add("NOT_HLT"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("HLT"); - openapiRequiredFields.add("NOT_HLT"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to BinaryPredictionResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!BinaryPredictionResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in BinaryPredictionResponse is not found in the empty JSON string", BinaryPredictionResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!BinaryPredictionResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `BinaryPredictionResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : BinaryPredictionResponse.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!BinaryPredictionResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'BinaryPredictionResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(BinaryPredictionResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, BinaryPredictionResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public BinaryPredictionResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of BinaryPredictionResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of BinaryPredictionResponse - * @throws IOException if the JSON string is invalid with respect to BinaryPredictionResponse - */ - public static BinaryPredictionResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, BinaryPredictionResponse.class); - } - - /** - * Convert an instance of BinaryPredictionResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/crop_health/model/MultiHLTPredictionResponse.java b/src/main/java/io/openepi/crop_health/model/MultiHLTPredictionResponse.java deleted file mode 100644 index c27d1d6..0000000 --- a/src/main/java/io/openepi/crop_health/model/MultiHLTPredictionResponse.java +++ /dev/null @@ -1,644 +0,0 @@ -/* - * Crop Health API - * This is a RESTful service that provides predictions for crop health.
The API consists of three pre-trained PyTorch models served using TorchServe. The models are designed to predict the health of crops based on images of the crops. The models were trained on the following crop types: maize, beans, cocoa, cassava, and banana.
The data were collected from the Harvard Dataverse and are licensed under the Creative Commons 1.0 DEED license.
The models differ in the number of classes they predict. The models are:
1. Binary model: This is a binary model that predicts the health of crops into three classes: healthy and diseased.
2. Single-HLT model: This is a multiclass model that predicts the health of crops into a single healthy (HLT) class and several diseases.
3. Multi-HLT model: This is a multiclass model that predicts the health of crops into multiple healthy (HLT) classes and several diseases.
The key difference between the single-HLT and multi-HLT models is that only the multi-HLT model has a healthy class for each crop type.
The nine specific datasets used can be found at the following URLs:
1. Spectrometry Cassava Dataset
2. Cassava Dataset Uganda
3. Maize Dataset Tanzania
4. Maize Dataset Namibia
5. Maize Dataset Uganda
6. Beans Dataset Uganda
7. Bananas Dataset Tanzania
8. KaraAgro AI Cocoa Dataset
9. KaraAgro AI Maize Dataset - * - * The version of the OpenAPI document: 0.1.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.crop_health.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.crop_health.JSON; - -/** - * MultiHLTPredictionResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-26T11:13:50.974079+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class MultiHLTPredictionResponse { - public static final String SERIALIZED_NAME_HL_T_CASSAVA = "HLT_cassava"; - @SerializedName(SERIALIZED_NAME_HL_T_CASSAVA) - private BigDecimal hlTCassava; - - public static final String SERIALIZED_NAME_CB_S_D_CASSAVA = "CBSD_cassava"; - @SerializedName(SERIALIZED_NAME_CB_S_D_CASSAVA) - private BigDecimal cbSDCassava; - - public static final String SERIALIZED_NAME_CM_D_CASSAVA = "CMD_cassava"; - @SerializedName(SERIALIZED_NAME_CM_D_CASSAVA) - private BigDecimal cmDCassava; - - public static final String SERIALIZED_NAME_ML_N_MAIZE = "MLN_maize"; - @SerializedName(SERIALIZED_NAME_ML_N_MAIZE) - private BigDecimal mlNMaize; - - public static final String SERIALIZED_NAME_HL_T_MAIZE = "HLT_maize"; - @SerializedName(SERIALIZED_NAME_HL_T_MAIZE) - private BigDecimal hlTMaize; - - public static final String SERIALIZED_NAME_MS_V_MAIZE = "MSV_maize"; - @SerializedName(SERIALIZED_NAME_MS_V_MAIZE) - private BigDecimal msVMaize; - - public static final String SERIALIZED_NAME_FA_W_MAIZE = "FAW_maize"; - @SerializedName(SERIALIZED_NAME_FA_W_MAIZE) - private BigDecimal faWMaize; - - public static final String SERIALIZED_NAME_ML_B_MAIZE = "MLB_maize"; - @SerializedName(SERIALIZED_NAME_ML_B_MAIZE) - private BigDecimal mlBMaize; - - public static final String SERIALIZED_NAME_HL_T_BEANS = "HLT_beans"; - @SerializedName(SERIALIZED_NAME_HL_T_BEANS) - private BigDecimal hlTBeans; - - public static final String SERIALIZED_NAME_BR_BEANS = "BR_beans"; - @SerializedName(SERIALIZED_NAME_BR_BEANS) - private BigDecimal brBeans; - - public static final String SERIALIZED_NAME_AL_S_BEANS = "ALS_beans"; - @SerializedName(SERIALIZED_NAME_AL_S_BEANS) - private BigDecimal alSBeans; - - public static final String SERIALIZED_NAME_HL_T_BANANAS = "HLT_bananas"; - @SerializedName(SERIALIZED_NAME_HL_T_BANANAS) - private BigDecimal hlTBananas; - - public static final String SERIALIZED_NAME_BS_BANANAS = "BS_bananas"; - @SerializedName(SERIALIZED_NAME_BS_BANANAS) - private BigDecimal bsBananas; - - public static final String SERIALIZED_NAME_FW_BANANAS = "FW_bananas"; - @SerializedName(SERIALIZED_NAME_FW_BANANAS) - private BigDecimal fwBananas; - - public static final String SERIALIZED_NAME_HL_T_COCOA = "HLT_cocoa"; - @SerializedName(SERIALIZED_NAME_HL_T_COCOA) - private BigDecimal hlTCocoa; - - public static final String SERIALIZED_NAME_AN_T_COCOA = "ANT_cocoa"; - @SerializedName(SERIALIZED_NAME_AN_T_COCOA) - private BigDecimal anTCocoa; - - public static final String SERIALIZED_NAME_CS_S_V_D_COCOA = "CSSVD_cocoa"; - @SerializedName(SERIALIZED_NAME_CS_S_V_D_COCOA) - private BigDecimal csSVDCocoa; - - public MultiHLTPredictionResponse() { - } - - public MultiHLTPredictionResponse hlTCassava(BigDecimal hlTCassava) { - this.hlTCassava = hlTCassava; - return this; - } - - /** - * Healthy Cassava - * @return hlTCassava - */ - @javax.annotation.Nonnull - public BigDecimal getHlTCassava() { - return hlTCassava; - } - - public void setHlTCassava(BigDecimal hlTCassava) { - this.hlTCassava = hlTCassava; - } - - - public MultiHLTPredictionResponse cbSDCassava(BigDecimal cbSDCassava) { - this.cbSDCassava = cbSDCassava; - return this; - } - - /** - * Cassava Brown Streak Disease - * @return cbSDCassava - */ - @javax.annotation.Nonnull - public BigDecimal getCbSDCassava() { - return cbSDCassava; - } - - public void setCbSDCassava(BigDecimal cbSDCassava) { - this.cbSDCassava = cbSDCassava; - } - - - public MultiHLTPredictionResponse cmDCassava(BigDecimal cmDCassava) { - this.cmDCassava = cmDCassava; - return this; - } - - /** - * Cassava Mosaic Disease - * @return cmDCassava - */ - @javax.annotation.Nonnull - public BigDecimal getCmDCassava() { - return cmDCassava; - } - - public void setCmDCassava(BigDecimal cmDCassava) { - this.cmDCassava = cmDCassava; - } - - - public MultiHLTPredictionResponse mlNMaize(BigDecimal mlNMaize) { - this.mlNMaize = mlNMaize; - return this; - } - - /** - * Maize Lethal Necrosis - * @return mlNMaize - */ - @javax.annotation.Nonnull - public BigDecimal getMlNMaize() { - return mlNMaize; - } - - public void setMlNMaize(BigDecimal mlNMaize) { - this.mlNMaize = mlNMaize; - } - - - public MultiHLTPredictionResponse hlTMaize(BigDecimal hlTMaize) { - this.hlTMaize = hlTMaize; - return this; - } - - /** - * Healthy Maize - * @return hlTMaize - */ - @javax.annotation.Nonnull - public BigDecimal getHlTMaize() { - return hlTMaize; - } - - public void setHlTMaize(BigDecimal hlTMaize) { - this.hlTMaize = hlTMaize; - } - - - public MultiHLTPredictionResponse msVMaize(BigDecimal msVMaize) { - this.msVMaize = msVMaize; - return this; - } - - /** - * Maize Streak Virus - * @return msVMaize - */ - @javax.annotation.Nonnull - public BigDecimal getMsVMaize() { - return msVMaize; - } - - public void setMsVMaize(BigDecimal msVMaize) { - this.msVMaize = msVMaize; - } - - - public MultiHLTPredictionResponse faWMaize(BigDecimal faWMaize) { - this.faWMaize = faWMaize; - return this; - } - - /** - * Fall Armyworm - * @return faWMaize - */ - @javax.annotation.Nonnull - public BigDecimal getFaWMaize() { - return faWMaize; - } - - public void setFaWMaize(BigDecimal faWMaize) { - this.faWMaize = faWMaize; - } - - - public MultiHLTPredictionResponse mlBMaize(BigDecimal mlBMaize) { - this.mlBMaize = mlBMaize; - return this; - } - - /** - * Maize Leaf Blight - * @return mlBMaize - */ - @javax.annotation.Nonnull - public BigDecimal getMlBMaize() { - return mlBMaize; - } - - public void setMlBMaize(BigDecimal mlBMaize) { - this.mlBMaize = mlBMaize; - } - - - public MultiHLTPredictionResponse hlTBeans(BigDecimal hlTBeans) { - this.hlTBeans = hlTBeans; - return this; - } - - /** - * Healthy Beans - * @return hlTBeans - */ - @javax.annotation.Nonnull - public BigDecimal getHlTBeans() { - return hlTBeans; - } - - public void setHlTBeans(BigDecimal hlTBeans) { - this.hlTBeans = hlTBeans; - } - - - public MultiHLTPredictionResponse brBeans(BigDecimal brBeans) { - this.brBeans = brBeans; - return this; - } - - /** - * Bean Rust - * @return brBeans - */ - @javax.annotation.Nonnull - public BigDecimal getBrBeans() { - return brBeans; - } - - public void setBrBeans(BigDecimal brBeans) { - this.brBeans = brBeans; - } - - - public MultiHLTPredictionResponse alSBeans(BigDecimal alSBeans) { - this.alSBeans = alSBeans; - return this; - } - - /** - * Angular Leaf Spot - * @return alSBeans - */ - @javax.annotation.Nonnull - public BigDecimal getAlSBeans() { - return alSBeans; - } - - public void setAlSBeans(BigDecimal alSBeans) { - this.alSBeans = alSBeans; - } - - - public MultiHLTPredictionResponse hlTBananas(BigDecimal hlTBananas) { - this.hlTBananas = hlTBananas; - return this; - } - - /** - * Healthy Bananas - * @return hlTBananas - */ - @javax.annotation.Nonnull - public BigDecimal getHlTBananas() { - return hlTBananas; - } - - public void setHlTBananas(BigDecimal hlTBananas) { - this.hlTBananas = hlTBananas; - } - - - public MultiHLTPredictionResponse bsBananas(BigDecimal bsBananas) { - this.bsBananas = bsBananas; - return this; - } - - /** - * Black Sigatoka - * @return bsBananas - */ - @javax.annotation.Nonnull - public BigDecimal getBsBananas() { - return bsBananas; - } - - public void setBsBananas(BigDecimal bsBananas) { - this.bsBananas = bsBananas; - } - - - public MultiHLTPredictionResponse fwBananas(BigDecimal fwBananas) { - this.fwBananas = fwBananas; - return this; - } - - /** - * Fusarium Wilt Race 1 - * @return fwBananas - */ - @javax.annotation.Nonnull - public BigDecimal getFwBananas() { - return fwBananas; - } - - public void setFwBananas(BigDecimal fwBananas) { - this.fwBananas = fwBananas; - } - - - public MultiHLTPredictionResponse hlTCocoa(BigDecimal hlTCocoa) { - this.hlTCocoa = hlTCocoa; - return this; - } - - /** - * Healthy Cocoa - * @return hlTCocoa - */ - @javax.annotation.Nonnull - public BigDecimal getHlTCocoa() { - return hlTCocoa; - } - - public void setHlTCocoa(BigDecimal hlTCocoa) { - this.hlTCocoa = hlTCocoa; - } - - - public MultiHLTPredictionResponse anTCocoa(BigDecimal anTCocoa) { - this.anTCocoa = anTCocoa; - return this; - } - - /** - * Anthracnose - * @return anTCocoa - */ - @javax.annotation.Nonnull - public BigDecimal getAnTCocoa() { - return anTCocoa; - } - - public void setAnTCocoa(BigDecimal anTCocoa) { - this.anTCocoa = anTCocoa; - } - - - public MultiHLTPredictionResponse csSVDCocoa(BigDecimal csSVDCocoa) { - this.csSVDCocoa = csSVDCocoa; - return this; - } - - /** - * Cocoa Swollen Shoot Virus Disease - * @return csSVDCocoa - */ - @javax.annotation.Nonnull - public BigDecimal getCsSVDCocoa() { - return csSVDCocoa; - } - - public void setCsSVDCocoa(BigDecimal csSVDCocoa) { - this.csSVDCocoa = csSVDCocoa; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MultiHLTPredictionResponse multiHLTPredictionResponse = (MultiHLTPredictionResponse) o; - return Objects.equals(this.hlTCassava, multiHLTPredictionResponse.hlTCassava) && - Objects.equals(this.cbSDCassava, multiHLTPredictionResponse.cbSDCassava) && - Objects.equals(this.cmDCassava, multiHLTPredictionResponse.cmDCassava) && - Objects.equals(this.mlNMaize, multiHLTPredictionResponse.mlNMaize) && - Objects.equals(this.hlTMaize, multiHLTPredictionResponse.hlTMaize) && - Objects.equals(this.msVMaize, multiHLTPredictionResponse.msVMaize) && - Objects.equals(this.faWMaize, multiHLTPredictionResponse.faWMaize) && - Objects.equals(this.mlBMaize, multiHLTPredictionResponse.mlBMaize) && - Objects.equals(this.hlTBeans, multiHLTPredictionResponse.hlTBeans) && - Objects.equals(this.brBeans, multiHLTPredictionResponse.brBeans) && - Objects.equals(this.alSBeans, multiHLTPredictionResponse.alSBeans) && - Objects.equals(this.hlTBananas, multiHLTPredictionResponse.hlTBananas) && - Objects.equals(this.bsBananas, multiHLTPredictionResponse.bsBananas) && - Objects.equals(this.fwBananas, multiHLTPredictionResponse.fwBananas) && - Objects.equals(this.hlTCocoa, multiHLTPredictionResponse.hlTCocoa) && - Objects.equals(this.anTCocoa, multiHLTPredictionResponse.anTCocoa) && - Objects.equals(this.csSVDCocoa, multiHLTPredictionResponse.csSVDCocoa); - } - - @Override - public int hashCode() { - return Objects.hash(hlTCassava, cbSDCassava, cmDCassava, mlNMaize, hlTMaize, msVMaize, faWMaize, mlBMaize, hlTBeans, brBeans, alSBeans, hlTBananas, bsBananas, fwBananas, hlTCocoa, anTCocoa, csSVDCocoa); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class MultiHLTPredictionResponse {\n"); - sb.append(" hlTCassava: ").append(toIndentedString(hlTCassava)).append("\n"); - sb.append(" cbSDCassava: ").append(toIndentedString(cbSDCassava)).append("\n"); - sb.append(" cmDCassava: ").append(toIndentedString(cmDCassava)).append("\n"); - sb.append(" mlNMaize: ").append(toIndentedString(mlNMaize)).append("\n"); - sb.append(" hlTMaize: ").append(toIndentedString(hlTMaize)).append("\n"); - sb.append(" msVMaize: ").append(toIndentedString(msVMaize)).append("\n"); - sb.append(" faWMaize: ").append(toIndentedString(faWMaize)).append("\n"); - sb.append(" mlBMaize: ").append(toIndentedString(mlBMaize)).append("\n"); - sb.append(" hlTBeans: ").append(toIndentedString(hlTBeans)).append("\n"); - sb.append(" brBeans: ").append(toIndentedString(brBeans)).append("\n"); - sb.append(" alSBeans: ").append(toIndentedString(alSBeans)).append("\n"); - sb.append(" hlTBananas: ").append(toIndentedString(hlTBananas)).append("\n"); - sb.append(" bsBananas: ").append(toIndentedString(bsBananas)).append("\n"); - sb.append(" fwBananas: ").append(toIndentedString(fwBananas)).append("\n"); - sb.append(" hlTCocoa: ").append(toIndentedString(hlTCocoa)).append("\n"); - sb.append(" anTCocoa: ").append(toIndentedString(anTCocoa)).append("\n"); - sb.append(" csSVDCocoa: ").append(toIndentedString(csSVDCocoa)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("HLT_cassava"); - openapiFields.add("CBSD_cassava"); - openapiFields.add("CMD_cassava"); - openapiFields.add("MLN_maize"); - openapiFields.add("HLT_maize"); - openapiFields.add("MSV_maize"); - openapiFields.add("FAW_maize"); - openapiFields.add("MLB_maize"); - openapiFields.add("HLT_beans"); - openapiFields.add("BR_beans"); - openapiFields.add("ALS_beans"); - openapiFields.add("HLT_bananas"); - openapiFields.add("BS_bananas"); - openapiFields.add("FW_bananas"); - openapiFields.add("HLT_cocoa"); - openapiFields.add("ANT_cocoa"); - openapiFields.add("CSSVD_cocoa"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("HLT_cassava"); - openapiRequiredFields.add("CBSD_cassava"); - openapiRequiredFields.add("CMD_cassava"); - openapiRequiredFields.add("MLN_maize"); - openapiRequiredFields.add("HLT_maize"); - openapiRequiredFields.add("MSV_maize"); - openapiRequiredFields.add("FAW_maize"); - openapiRequiredFields.add("MLB_maize"); - openapiRequiredFields.add("HLT_beans"); - openapiRequiredFields.add("BR_beans"); - openapiRequiredFields.add("ALS_beans"); - openapiRequiredFields.add("HLT_bananas"); - openapiRequiredFields.add("BS_bananas"); - openapiRequiredFields.add("FW_bananas"); - openapiRequiredFields.add("HLT_cocoa"); - openapiRequiredFields.add("ANT_cocoa"); - openapiRequiredFields.add("CSSVD_cocoa"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to MultiHLTPredictionResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!MultiHLTPredictionResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in MultiHLTPredictionResponse is not found in the empty JSON string", MultiHLTPredictionResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!MultiHLTPredictionResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `MultiHLTPredictionResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : MultiHLTPredictionResponse.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!MultiHLTPredictionResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'MultiHLTPredictionResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(MultiHLTPredictionResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, MultiHLTPredictionResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public MultiHLTPredictionResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of MultiHLTPredictionResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of MultiHLTPredictionResponse - * @throws IOException if the JSON string is invalid with respect to MultiHLTPredictionResponse - */ - public static MultiHLTPredictionResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, MultiHLTPredictionResponse.class); - } - - /** - * Convert an instance of MultiHLTPredictionResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/crop_health/model/Ping200Response.java b/src/main/java/io/openepi/crop_health/model/Ping200Response.java deleted file mode 100644 index 005241c..0000000 --- a/src/main/java/io/openepi/crop_health/model/Ping200Response.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Crop Health API - * This is a RESTful service that provides predictions for crop health.
The API consists of three pre-trained PyTorch models served using TorchServe. The models are designed to predict the health of crops based on images of the crops. The models were trained on the following crop types: maize, beans, cocoa, cassava, and banana.
The data were collected from the Harvard Dataverse and are licensed under the Creative Commons 1.0 DEED license.
The models differ in the number of classes they predict. The models are:
1. Binary model: This is a binary model that predicts the health of crops into three classes: healthy and diseased.
2. Single-HLT model: This is a multiclass model that predicts the health of crops into a single healthy (HLT) class and several diseases.
3. Multi-HLT model: This is a multiclass model that predicts the health of crops into multiple healthy (HLT) classes and several diseases.
The key difference between the single-HLT and multi-HLT models is that only the multi-HLT model has a healthy class for each crop type.
The nine specific datasets used can be found at the following URLs:
1. Spectrometry Cassava Dataset
2. Cassava Dataset Uganda
3. Maize Dataset Tanzania
4. Maize Dataset Namibia
5. Maize Dataset Uganda
6. Beans Dataset Uganda
7. Bananas Dataset Tanzania
8. KaraAgro AI Cocoa Dataset
9. KaraAgro AI Maize Dataset - * - * The version of the OpenAPI document: 0.1.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.crop_health.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.crop_health.JSON; - -/** - * Ping200Response - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-26T11:13:50.974079+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class Ping200Response { - public static final String SERIALIZED_NAME_STATUS = "status"; - @SerializedName(SERIALIZED_NAME_STATUS) - private String status; - - public Ping200Response() { - } - - public Ping200Response status(String status) { - this.status = status; - return this; - } - - /** - * Overall status of the TorchServe. - * @return status - */ - @javax.annotation.Nonnull - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Ping200Response ping200Response = (Ping200Response) o; - return Objects.equals(this.status, ping200Response.status); - } - - @Override - public int hashCode() { - return Objects.hash(status); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Ping200Response {\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("status"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("status"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to Ping200Response - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!Ping200Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in Ping200Response is not found in the empty JSON string", Ping200Response.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!Ping200Response.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Ping200Response` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : Ping200Response.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (!jsonObj.get("status").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!Ping200Response.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'Ping200Response' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(Ping200Response.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, Ping200Response value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public Ping200Response read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of Ping200Response given an JSON string - * - * @param jsonString JSON string - * @return An instance of Ping200Response - * @throws IOException if the JSON string is invalid with respect to Ping200Response - */ - public static Ping200Response fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, Ping200Response.class); - } - - /** - * Convert an instance of Ping200Response to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/crop_health/model/Ping500Response.java b/src/main/java/io/openepi/crop_health/model/Ping500Response.java deleted file mode 100644 index eae7597..0000000 --- a/src/main/java/io/openepi/crop_health/model/Ping500Response.java +++ /dev/null @@ -1,271 +0,0 @@ -/* - * Crop Health API - * This is a RESTful service that provides predictions for crop health.
The API consists of three pre-trained PyTorch models served using TorchServe. The models are designed to predict the health of crops based on images of the crops. The models were trained on the following crop types: maize, beans, cocoa, cassava, and banana.
The data were collected from the Harvard Dataverse and are licensed under the Creative Commons 1.0 DEED license.
The models differ in the number of classes they predict. The models are:
1. Binary model: This is a binary model that predicts the health of crops into three classes: healthy and diseased.
2. Single-HLT model: This is a multiclass model that predicts the health of crops into a single healthy (HLT) class and several diseases.
3. Multi-HLT model: This is a multiclass model that predicts the health of crops into multiple healthy (HLT) classes and several diseases.
The key difference between the single-HLT and multi-HLT models is that only the multi-HLT model has a healthy class for each crop type.
The nine specific datasets used can be found at the following URLs:
1. Spectrometry Cassava Dataset
2. Cassava Dataset Uganda
3. Maize Dataset Tanzania
4. Maize Dataset Namibia
5. Maize Dataset Uganda
6. Beans Dataset Uganda
7. Bananas Dataset Tanzania
8. KaraAgro AI Cocoa Dataset
9. KaraAgro AI Maize Dataset - * - * The version of the OpenAPI document: 0.1.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.crop_health.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.crop_health.JSON; - -/** - * Ping500Response - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-26T11:13:50.974079+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class Ping500Response { - public static final String SERIALIZED_NAME_CODE = "code"; - @SerializedName(SERIALIZED_NAME_CODE) - private Integer code; - - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private String type; - - public static final String SERIALIZED_NAME_MESSAGE = "message"; - @SerializedName(SERIALIZED_NAME_MESSAGE) - private String message; - - public Ping500Response() { - } - - public Ping500Response code(Integer code) { - this.code = code; - return this; - } - - /** - * Error code. - * @return code - */ - @javax.annotation.Nonnull - public Integer getCode() { - return code; - } - - public void setCode(Integer code) { - this.code = code; - } - - - public Ping500Response type(String type) { - this.type = type; - return this; - } - - /** - * Error type. - * @return type - */ - @javax.annotation.Nonnull - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - - public Ping500Response message(String message) { - this.message = message; - return this; - } - - /** - * Error message. - * @return message - */ - @javax.annotation.Nonnull - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Ping500Response ping500Response = (Ping500Response) o; - return Objects.equals(this.code, ping500Response.code) && - Objects.equals(this.type, ping500Response.type) && - Objects.equals(this.message, ping500Response.message); - } - - @Override - public int hashCode() { - return Objects.hash(code, type, message); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Ping500Response {\n"); - sb.append(" code: ").append(toIndentedString(code)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" message: ").append(toIndentedString(message)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("code"); - openapiFields.add("type"); - openapiFields.add("message"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("code"); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("message"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to Ping500Response - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!Ping500Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in Ping500Response is not found in the empty JSON string", Ping500Response.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!Ping500Response.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Ping500Response` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : Ping500Response.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (!jsonObj.get("type").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); - } - if (!jsonObj.get("message").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!Ping500Response.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'Ping500Response' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(Ping500Response.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, Ping500Response value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public Ping500Response read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of Ping500Response given an JSON string - * - * @param jsonString JSON string - * @return An instance of Ping500Response - * @throws IOException if the JSON string is invalid with respect to Ping500Response - */ - public static Ping500Response fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, Ping500Response.class); - } - - /** - * Convert an instance of Ping500Response to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/crop_health/model/SingleHLTPredictionResponse.java b/src/main/java/io/openepi/crop_health/model/SingleHLTPredictionResponse.java deleted file mode 100644 index 29d18cd..0000000 --- a/src/main/java/io/openepi/crop_health/model/SingleHLTPredictionResponse.java +++ /dev/null @@ -1,536 +0,0 @@ -/* - * Crop Health API - * This is a RESTful service that provides predictions for crop health.
The API consists of three pre-trained PyTorch models served using TorchServe. The models are designed to predict the health of crops based on images of the crops. The models were trained on the following crop types: maize, beans, cocoa, cassava, and banana.
The data were collected from the Harvard Dataverse and are licensed under the Creative Commons 1.0 DEED license.
The models differ in the number of classes they predict. The models are:
1. Binary model: This is a binary model that predicts the health of crops into three classes: healthy and diseased.
2. Single-HLT model: This is a multiclass model that predicts the health of crops into a single healthy (HLT) class and several diseases.
3. Multi-HLT model: This is a multiclass model that predicts the health of crops into multiple healthy (HLT) classes and several diseases.
The key difference between the single-HLT and multi-HLT models is that only the multi-HLT model has a healthy class for each crop type.
The nine specific datasets used can be found at the following URLs:
1. Spectrometry Cassava Dataset
2. Cassava Dataset Uganda
3. Maize Dataset Tanzania
4. Maize Dataset Namibia
5. Maize Dataset Uganda
6. Beans Dataset Uganda
7. Bananas Dataset Tanzania
8. KaraAgro AI Cocoa Dataset
9. KaraAgro AI Maize Dataset - * - * The version of the OpenAPI document: 0.1.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.crop_health.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.crop_health.JSON; - -/** - * SingleHLTPredictionResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-26T11:13:50.974079+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SingleHLTPredictionResponse { - public static final String SERIALIZED_NAME_H_L_T = "HLT"; - @SerializedName(SERIALIZED_NAME_H_L_T) - private BigDecimal HLT; - - public static final String SERIALIZED_NAME_C_B_S_D = "CBSD"; - @SerializedName(SERIALIZED_NAME_C_B_S_D) - private BigDecimal CBSD; - - public static final String SERIALIZED_NAME_C_M_D = "CMD"; - @SerializedName(SERIALIZED_NAME_C_M_D) - private BigDecimal CMD; - - public static final String SERIALIZED_NAME_M_L_N = "MLN"; - @SerializedName(SERIALIZED_NAME_M_L_N) - private BigDecimal MLN; - - public static final String SERIALIZED_NAME_M_S_V = "MSV"; - @SerializedName(SERIALIZED_NAME_M_S_V) - private BigDecimal MSV; - - public static final String SERIALIZED_NAME_F_A_W = "FAW"; - @SerializedName(SERIALIZED_NAME_F_A_W) - private BigDecimal FAW; - - public static final String SERIALIZED_NAME_M_L_B = "MLB"; - @SerializedName(SERIALIZED_NAME_M_L_B) - private BigDecimal MLB; - - public static final String SERIALIZED_NAME_B_R = "BR"; - @SerializedName(SERIALIZED_NAME_B_R) - private BigDecimal BR; - - public static final String SERIALIZED_NAME_A_L_S = "ALS"; - @SerializedName(SERIALIZED_NAME_A_L_S) - private BigDecimal ALS; - - public static final String SERIALIZED_NAME_B_S = "BS"; - @SerializedName(SERIALIZED_NAME_B_S) - private BigDecimal BS; - - public static final String SERIALIZED_NAME_F_W = "FW"; - @SerializedName(SERIALIZED_NAME_F_W) - private BigDecimal FW; - - public static final String SERIALIZED_NAME_A_N_T = "ANT"; - @SerializedName(SERIALIZED_NAME_A_N_T) - private BigDecimal ANT; - - public static final String SERIALIZED_NAME_C_S_S_V_D = "CSSVD"; - @SerializedName(SERIALIZED_NAME_C_S_S_V_D) - private BigDecimal CSSVD; - - public SingleHLTPredictionResponse() { - } - - public SingleHLTPredictionResponse HLT(BigDecimal HLT) { - this.HLT = HLT; - return this; - } - - /** - * Healthy - * @return HLT - */ - @javax.annotation.Nonnull - public BigDecimal getHLT() { - return HLT; - } - - public void setHLT(BigDecimal HLT) { - this.HLT = HLT; - } - - - public SingleHLTPredictionResponse CBSD(BigDecimal CBSD) { - this.CBSD = CBSD; - return this; - } - - /** - * Cassava Brown Streak Disease - * @return CBSD - */ - @javax.annotation.Nonnull - public BigDecimal getCBSD() { - return CBSD; - } - - public void setCBSD(BigDecimal CBSD) { - this.CBSD = CBSD; - } - - - public SingleHLTPredictionResponse CMD(BigDecimal CMD) { - this.CMD = CMD; - return this; - } - - /** - * Cassava Mosaic Disease - * @return CMD - */ - @javax.annotation.Nonnull - public BigDecimal getCMD() { - return CMD; - } - - public void setCMD(BigDecimal CMD) { - this.CMD = CMD; - } - - - public SingleHLTPredictionResponse MLN(BigDecimal MLN) { - this.MLN = MLN; - return this; - } - - /** - * Maize Lethal Necrosis - * @return MLN - */ - @javax.annotation.Nonnull - public BigDecimal getMLN() { - return MLN; - } - - public void setMLN(BigDecimal MLN) { - this.MLN = MLN; - } - - - public SingleHLTPredictionResponse MSV(BigDecimal MSV) { - this.MSV = MSV; - return this; - } - - /** - * Maize Streak Virus - * @return MSV - */ - @javax.annotation.Nonnull - public BigDecimal getMSV() { - return MSV; - } - - public void setMSV(BigDecimal MSV) { - this.MSV = MSV; - } - - - public SingleHLTPredictionResponse FAW(BigDecimal FAW) { - this.FAW = FAW; - return this; - } - - /** - * Fall Armyworm - * @return FAW - */ - @javax.annotation.Nonnull - public BigDecimal getFAW() { - return FAW; - } - - public void setFAW(BigDecimal FAW) { - this.FAW = FAW; - } - - - public SingleHLTPredictionResponse MLB(BigDecimal MLB) { - this.MLB = MLB; - return this; - } - - /** - * Maize Leaf Blight - * @return MLB - */ - @javax.annotation.Nonnull - public BigDecimal getMLB() { - return MLB; - } - - public void setMLB(BigDecimal MLB) { - this.MLB = MLB; - } - - - public SingleHLTPredictionResponse BR(BigDecimal BR) { - this.BR = BR; - return this; - } - - /** - * Bean Rust - * @return BR - */ - @javax.annotation.Nonnull - public BigDecimal getBR() { - return BR; - } - - public void setBR(BigDecimal BR) { - this.BR = BR; - } - - - public SingleHLTPredictionResponse ALS(BigDecimal ALS) { - this.ALS = ALS; - return this; - } - - /** - * Angular Leaf Spot - * @return ALS - */ - @javax.annotation.Nonnull - public BigDecimal getALS() { - return ALS; - } - - public void setALS(BigDecimal ALS) { - this.ALS = ALS; - } - - - public SingleHLTPredictionResponse BS(BigDecimal BS) { - this.BS = BS; - return this; - } - - /** - * Black Sigatoka - * @return BS - */ - @javax.annotation.Nonnull - public BigDecimal getBS() { - return BS; - } - - public void setBS(BigDecimal BS) { - this.BS = BS; - } - - - public SingleHLTPredictionResponse FW(BigDecimal FW) { - this.FW = FW; - return this; - } - - /** - * Fusarium Wilt Race 1 - * @return FW - */ - @javax.annotation.Nonnull - public BigDecimal getFW() { - return FW; - } - - public void setFW(BigDecimal FW) { - this.FW = FW; - } - - - public SingleHLTPredictionResponse ANT(BigDecimal ANT) { - this.ANT = ANT; - return this; - } - - /** - * Anthracnose - * @return ANT - */ - @javax.annotation.Nonnull - public BigDecimal getANT() { - return ANT; - } - - public void setANT(BigDecimal ANT) { - this.ANT = ANT; - } - - - public SingleHLTPredictionResponse CSSVD(BigDecimal CSSVD) { - this.CSSVD = CSSVD; - return this; - } - - /** - * Cocoa Swollen Shoot Virus Disease - * @return CSSVD - */ - @javax.annotation.Nonnull - public BigDecimal getCSSVD() { - return CSSVD; - } - - public void setCSSVD(BigDecimal CSSVD) { - this.CSSVD = CSSVD; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SingleHLTPredictionResponse singleHLTPredictionResponse = (SingleHLTPredictionResponse) o; - return Objects.equals(this.HLT, singleHLTPredictionResponse.HLT) && - Objects.equals(this.CBSD, singleHLTPredictionResponse.CBSD) && - Objects.equals(this.CMD, singleHLTPredictionResponse.CMD) && - Objects.equals(this.MLN, singleHLTPredictionResponse.MLN) && - Objects.equals(this.MSV, singleHLTPredictionResponse.MSV) && - Objects.equals(this.FAW, singleHLTPredictionResponse.FAW) && - Objects.equals(this.MLB, singleHLTPredictionResponse.MLB) && - Objects.equals(this.BR, singleHLTPredictionResponse.BR) && - Objects.equals(this.ALS, singleHLTPredictionResponse.ALS) && - Objects.equals(this.BS, singleHLTPredictionResponse.BS) && - Objects.equals(this.FW, singleHLTPredictionResponse.FW) && - Objects.equals(this.ANT, singleHLTPredictionResponse.ANT) && - Objects.equals(this.CSSVD, singleHLTPredictionResponse.CSSVD); - } - - @Override - public int hashCode() { - return Objects.hash(HLT, CBSD, CMD, MLN, MSV, FAW, MLB, BR, ALS, BS, FW, ANT, CSSVD); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SingleHLTPredictionResponse {\n"); - sb.append(" HLT: ").append(toIndentedString(HLT)).append("\n"); - sb.append(" CBSD: ").append(toIndentedString(CBSD)).append("\n"); - sb.append(" CMD: ").append(toIndentedString(CMD)).append("\n"); - sb.append(" MLN: ").append(toIndentedString(MLN)).append("\n"); - sb.append(" MSV: ").append(toIndentedString(MSV)).append("\n"); - sb.append(" FAW: ").append(toIndentedString(FAW)).append("\n"); - sb.append(" MLB: ").append(toIndentedString(MLB)).append("\n"); - sb.append(" BR: ").append(toIndentedString(BR)).append("\n"); - sb.append(" ALS: ").append(toIndentedString(ALS)).append("\n"); - sb.append(" BS: ").append(toIndentedString(BS)).append("\n"); - sb.append(" FW: ").append(toIndentedString(FW)).append("\n"); - sb.append(" ANT: ").append(toIndentedString(ANT)).append("\n"); - sb.append(" CSSVD: ").append(toIndentedString(CSSVD)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("HLT"); - openapiFields.add("CBSD"); - openapiFields.add("CMD"); - openapiFields.add("MLN"); - openapiFields.add("MSV"); - openapiFields.add("FAW"); - openapiFields.add("MLB"); - openapiFields.add("BR"); - openapiFields.add("ALS"); - openapiFields.add("BS"); - openapiFields.add("FW"); - openapiFields.add("ANT"); - openapiFields.add("CSSVD"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("HLT"); - openapiRequiredFields.add("CBSD"); - openapiRequiredFields.add("CMD"); - openapiRequiredFields.add("MLN"); - openapiRequiredFields.add("MSV"); - openapiRequiredFields.add("FAW"); - openapiRequiredFields.add("MLB"); - openapiRequiredFields.add("BR"); - openapiRequiredFields.add("ALS"); - openapiRequiredFields.add("BS"); - openapiRequiredFields.add("FW"); - openapiRequiredFields.add("ANT"); - openapiRequiredFields.add("CSSVD"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SingleHLTPredictionResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SingleHLTPredictionResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SingleHLTPredictionResponse is not found in the empty JSON string", SingleHLTPredictionResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SingleHLTPredictionResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SingleHLTPredictionResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SingleHLTPredictionResponse.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SingleHLTPredictionResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SingleHLTPredictionResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SingleHLTPredictionResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SingleHLTPredictionResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SingleHLTPredictionResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SingleHLTPredictionResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of SingleHLTPredictionResponse - * @throws IOException if the JSON string is invalid with respect to SingleHLTPredictionResponse - */ - public static SingleHLTPredictionResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SingleHLTPredictionResponse.class); - } - - /** - * Convert an instance of SingleHLTPredictionResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/deforestation/ApiClient.java b/src/main/java/io/openepi/deforestation/ApiClient.java deleted file mode 100644 index 2b608b7..0000000 --- a/src/main/java/io/openepi/deforestation/ApiClient.java +++ /dev/null @@ -1,1565 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation; - -import okhttp3.*; -import okhttp3.internal.http.HttpMethod; -import okhttp3.internal.tls.OkHostnameVerifier; -import okhttp3.logging.HttpLoggingInterceptor; -import okhttp3.logging.HttpLoggingInterceptor.Level; -import okio.Buffer; -import okio.BufferedSink; -import okio.Okio; - -import javax.net.ssl.*; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; -import java.net.URI; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.text.DateFormat; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import io.openepi.common.auth.Authentication; -import io.openepi.common.auth.HttpBasicAuth; -import io.openepi.common.auth.HttpBearerAuth; -import io.openepi.common.auth.ApiKeyAuth; -import io.openepi.common.*; - -/** - *

ApiClient class.

- */ -public class ApiClient { - - private String basePath = "https://api.openepi.io/deforestation"; - protected List servers = new ArrayList(Arrays.asList( - new ServerConfiguration( - "https://api.openepi.io/deforestation", - "No description provided", - new HashMap() - ) - )); - protected Integer serverIndex = 0; - protected Map serverVariables = null; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private Map defaultCookieMap = new HashMap(); - private String tempFolderPath = null; - - private Map authentications; - - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; - - private InputStream sslCaCert; - private boolean verifyingSsl; - private KeyManager[] keyManagers; - - private OkHttpClient httpClient; - private JSON json; - - private HttpLoggingInterceptor loggingInterceptor; - - /** - * Basic constructor for ApiClient - */ - public ApiClient() { - init(); - initHttpClient(); - - // Setup authentications (key: authentication name, value: authentication). - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - /** - * Basic constructor with custom OkHttpClient - * - * @param client a {@link okhttp3.OkHttpClient} object - */ - public ApiClient(OkHttpClient client) { - init(); - - httpClient = client; - - // Setup authentications (key: authentication name, value: authentication). - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - private void initHttpClient() { - initHttpClient(Collections.emptyList()); - } - - private void initHttpClient(List interceptors) { - OkHttpClient.Builder builder = new OkHttpClient.Builder(); - builder.addNetworkInterceptor(getProgressInterceptor()); - for (Interceptor interceptor: interceptors) { - builder.addInterceptor(interceptor); - } - - httpClient = builder.build(); - } - - private void init() { - verifyingSsl = true; - - json = new JSON(); - - // Set default User-Agent. - setUserAgent("OpenAPI-Generator/0.3.6/java"); - - authentications = new HashMap(); - } - - /** - * Get base path - * - * @return Base path - */ - public String getBasePath() { - return basePath; - } - - /** - * Set base path - * - * @param basePath Base path of the URL (e.g https://api.openepi.io/deforestation - * @return An instance of OkHttpClient - */ - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - this.serverIndex = null; - return this; - } - - public List getServers() { - return servers; - } - - public ApiClient setServers(List servers) { - this.servers = servers; - return this; - } - - public Integer getServerIndex() { - return serverIndex; - } - - public ApiClient setServerIndex(Integer serverIndex) { - this.serverIndex = serverIndex; - return this; - } - - public Map getServerVariables() { - return serverVariables; - } - - public ApiClient setServerVariables(Map serverVariables) { - this.serverVariables = serverVariables; - return this; - } - - /** - * Get HTTP client - * - * @return An instance of OkHttpClient - */ - public OkHttpClient getHttpClient() { - return httpClient; - } - - /** - * Set HTTP client, which must never be null. - * - * @param newHttpClient An instance of OkHttpClient - * @return Api Client - * @throws java.lang.NullPointerException when newHttpClient is null - */ - public ApiClient setHttpClient(OkHttpClient newHttpClient) { - this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!"); - return this; - } - - /** - * Get JSON - * - * @return JSON object - */ - public JSON getJSON() { - return json; - } - - /** - * Set JSON - * - * @param json JSON object - * @return Api client - */ - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - /** - * True if isVerifyingSsl flag is on - * - * @return True if isVerifySsl flag is on - */ - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - * - * @param verifyingSsl True to verify TLS/SSL connection - * @return ApiClient - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - /** - * Get SSL CA cert. - * - * @return Input stream to the SSL CA cert - */ - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - * - * @param sslCaCert input stream for SSL CA cert - * @return ApiClient - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - /** - *

Getter for the field keyManagers.

- * - * @return an array of {@link javax.net.ssl.KeyManager} objects - */ - public KeyManager[] getKeyManagers() { - return keyManagers; - } - - /** - * Configure client keys to use for authorization in an SSL session. - * Use null to reset to default. - * - * @param managers The KeyManagers to use - * @return ApiClient - */ - public ApiClient setKeyManagers(KeyManager[] managers) { - this.keyManagers = managers; - applySslSettings(); - return this; - } - - /** - *

Getter for the field dateFormat.

- * - * @return a {@link java.text.DateFormat} object - */ - public DateFormat getDateFormat() { - return dateFormat; - } - - /** - *

Setter for the field dateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link io.openepi.deforestation.ApiClient} object - */ - public ApiClient setDateFormat(DateFormat dateFormat) { - JSON.setDateFormat(dateFormat); - return this; - } - - /** - *

Set SqlDateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link io.openepi.deforestation.ApiClient} object - */ - public ApiClient setSqlDateFormat(DateFormat dateFormat) { - JSON.setSqlDateFormat(dateFormat); - return this; - } - - /** - *

Set OffsetDateTimeFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link io.openepi.deforestation.ApiClient} object - */ - public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - JSON.setOffsetDateTimeFormat(dateFormat); - return this; - } - - /** - *

Set LocalDateFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link io.openepi.deforestation.ApiClient} object - */ - public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { - JSON.setLocalDateFormat(dateFormat); - return this; - } - - /** - *

Set LenientOnJson.

- * - * @param lenientOnJson a boolean - * @return a {@link io.openepi.deforestation.ApiClient} object - */ - public ApiClient setLenientOnJson(boolean lenientOnJson) { - JSON.setLenientOnJson(lenientOnJson); - return this; - } - - /** - * Get authentications (key: authentication name, value: authentication). - * - * @return Map of authentication objects - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - - /** - * Helper method to set username for the first HTTP basic authentication. - * - * @param username Username - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - * - * @param password Password - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - * - * @param apiKey API key - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - * - * @param apiKeyPrefix API key prefix - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - * - * @param accessToken Access token - */ - public void setAccessToken(String accessToken) { - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Helper method to set credentials for AWSV4 Signature - * - * @param accessKey Access Key - * @param secretKey Secret Key - * @param region Region - * @param service Service to access to - */ - public void setAWS4Configuration(String accessKey, String secretKey, String region, String service) { - throw new RuntimeException("No AWS4 authentication configured!"); - } - - /** - * Helper method to set credentials for AWSV4 Signature - * - * @param accessKey Access Key - * @param secretKey Secret Key - * @param sessionToken Session Token - * @param region Region - * @param service Service to access to - */ - public void setAWS4Configuration(String accessKey, String secretKey, String sessionToken, String region, String service) { - throw new RuntimeException("No AWS4 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - * - * @param userAgent HTTP request's user agent - * @return ApiClient - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - * @return ApiClient - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * Add a default cookie. - * - * @param key The cookie's key - * @param value The cookie's value - * @return ApiClient - */ - public ApiClient addDefaultCookie(String key, String value) { - defaultCookieMap.put(key, value); - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - * - * @return True if debugging is enabled, false otherwise. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - * @return ApiClient - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); - } else { - final OkHttpClient.Builder builder = httpClient.newBuilder(); - builder.interceptors().remove(loggingInterceptor); - httpClient = builder.build(); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default temporary folder. - * - * @see createTempFile - * @return Temporary folder path - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - /** - * Set the temporary folder path (for downloading files) - * - * @param tempFolderPath Temporary folder path - * @return ApiClient - */ - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Get connection timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getConnectTimeout() { - return httpClient.connectTimeoutMillis(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param connectionTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - /** - * Get read timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getReadTimeout() { - return httpClient.readTimeoutMillis(); - } - - /** - * Sets the read timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param readTimeout read timeout in milliseconds - * @return Api client - */ - public ApiClient setReadTimeout(int readTimeout) { - httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - /** - * Get write timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getWriteTimeout() { - return httpClient.writeTimeoutMillis(); - } - - /** - * Sets the write timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param writeTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setWriteTimeout(int writeTimeout) { - httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - - /** - * Format the given parameter object into string. - * - * @param param Parameter - * @return String representation of the parameter - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) { - //Serialize to json string and remove the " enclosing characters - String jsonStr = JSON.serialize(param); - return jsonStr.substring(1, jsonStr.length() - 1); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection) param) { - if (b.length() > 0) { - b.append(","); - } - b.append(o); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /** - * Formats the specified query parameter to a list containing a single {@code Pair} object. - * - * Note that {@code value} must not be a collection. - * - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list containing a single {@code Pair} object. - */ - public List parameterToPair(String name, Object value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value instanceof Collection) { - return params; - } - - params.add(new Pair(name, parameterToString(value))); - return params; - } - - /** - * Formats the specified collection query parameters to a list of {@code Pair} objects. - * - * Note that the values of each of the returned Pair objects are percent-encoded. - * - * @param collectionFormat The collection format of the parameter. - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list of {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Collection value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value.isEmpty()) { - return params; - } - - // create the params based on the collection format - if ("multi".equals(collectionFormat)) { - for (Object item : value) { - params.add(new Pair(name, escapeString(parameterToString(item)))); - } - return params; - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - // escape all delimiters except commas, which are URI reserved - // characters - if ("ssv".equals(collectionFormat)) { - delimiter = escapeString(" "); - } else if ("tsv".equals(collectionFormat)) { - delimiter = escapeString("\t"); - } else if ("pipes".equals(collectionFormat)) { - delimiter = escapeString("|"); - } - - StringBuilder sb = new StringBuilder(); - for (Object item : value) { - sb.append(delimiter); - sb.append(escapeString(parameterToString(item))); - } - - params.add(new Pair(name, sb.substring(delimiter.length()))); - - return params; - } - - /** - * Formats the specified collection path parameter to a string value. - * - * @param collectionFormat The collection format of the parameter. - * @param value The value of the parameter. - * @return String representation of the parameter - */ - public String collectionPathParameterToString(String collectionFormat, Collection value) { - // create the value based on the collection format - if ("multi".equals(collectionFormat)) { - // not valid for path params - return parameterToString(value); - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - if ("ssv".equals(collectionFormat)) { - delimiter = " "; - } else if ("tsv".equals(collectionFormat)) { - delimiter = "\t"; - } else if ("pipes".equals(collectionFormat)) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : value) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - return sb.substring(delimiter.length()); - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * application/vnd.company+json - * "* / *" is also default to JSON - * @param mime MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public boolean isJsonMime(String mime) { - String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; - return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * returns null. If it matches "any", JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return null; - } - - if (contentTypes[0].equals("*/*")) { - return "application/json"; - } - - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - * - * @param str String to be escaped - * @return Escaped string - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param Type - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws io.openepi.common.ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - @SuppressWarnings("unchecked") - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; - } - - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); - } - - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); - } - - if (respBody == null || "".equals(respBody)) { - return null; - } - - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return JSON.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } - } - - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws io.openepi.common.ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create((File) obj, MediaType.parse(contentType)); - } else if ("text/plain".equals(contentType) && obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - return RequestBody.create(content, MediaType.parse(contentType)); - } else if (obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } - } - - /** - * Download file from the given response. - * - * @param response An instance of the Response object - * @throws io.openepi.common.ApiException If fail to read file content from response and write to disk - * @return Downloaded file - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * Prepare file for download - * - * @param response An instance of the Response object - * @return Prepared file for the download - * @throws java.io.IOException If fail to prepare file for download - */ - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } - } - - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // Files.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; - } - - if (tempFolderPath == null) - return Files.createTempFile(prefix, suffix).toFile(); - else - return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); - } - - /** - * {@link #execute(Call, Type)} - * - * @param Type - * @param call An instance of the Call object - * @return ApiResponse<T> - * @throws io.openepi.common.ApiException If fail to execute the call - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @param call Call - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws io.openepi.common.ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * {@link #executeAsync(Call, Type, ApiCallback)} - * - * @param Type - * @param call An instance of the Call object - * @param callback ApiCallback<T> - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } - - /** - * Execute HTTP call asynchronously. - * - * @param Type - * @param call The callback to be executed when the API call finishes - * @param returnType Return type - * @param callback ApiCallback - * @see #execute(Call, Type) - */ - @SuppressWarnings("unchecked") - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } - - @Override - public void onResponse(Call call, Response response) throws IOException { - T result; - try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; - } catch (Exception e) { - callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); - return; - } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @param Type - * @param response Response - * @param returnType Return type - * @return Type - * @throws io.openepi.common.ApiException If the response has an unsuccessful status code or - * fail to deserialize the response body - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - if (response.body() != null) { - try { - response.body().close(); - } catch (Exception e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { - try { - respBody = response.body().string(); - } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - - /** - * Build HTTP call with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP call - * @throws io.openepi.common.ApiException If fail to serialize the request body object - */ - public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); - - return httpClient.newCall(request); - } - - /** - * Build an HTTP request with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP request - * @throws io.openepi.common.ApiException If fail to serialize the request body object - */ - public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams - List allQueryParams = new ArrayList(queryParams); - allQueryParams.addAll(collectionQueryParams); - - final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); - - // prepare HTTP request body - RequestBody reqBody; - String contentType = headerParams.get("Content-Type"); - String contentTypePure = contentType; - if (contentTypePure != null && contentTypePure.contains(";")) { - contentTypePure = contentType.substring(0, contentType.indexOf(";")); - } - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentTypePure)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentTypePure)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create("", contentType == null ? null : MediaType.parse(contentType)); - } - } else { - reqBody = serialize(body, contentType); - } - - // update parameters with authentication settings - updateParamsForAuth(authNames, allQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url)); - - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - processCookieParams(cookieParams, reqBuilder); - - // Associate callback with request (if not null) so interceptor can - // access it when creating ProgressResponseBody - reqBuilder.tag(callback); - - Request request = null; - - if (callback != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return request; - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param baseUrl The base URL - * @param path The sub path - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @return The full URL - */ - public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { - final StringBuilder url = new StringBuilder(); - if (baseUrl != null) { - url.append(baseUrl).append(path); - } else { - String baseURL; - if (serverIndex != null) { - if (serverIndex < 0 || serverIndex >= servers.size()) { - throw new ArrayIndexOutOfBoundsException(String.format( - "Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size() - )); - } - baseURL = servers.get(serverIndex).URL(serverVariables); - } else { - baseURL = basePath; - } - url.append(baseURL).append(path); - } - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { - String prefix = url.toString().contains("?") ? "&" : "?"; - for (Pair param : collectionQueryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - // collection query parameter value already escaped as part of parameterToPairs - url.append(escapeString(param.getName())).append("=").append(value); - } - } - } - - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - * - * @param headerParams Header parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Set cookie parameters to the request builder, including default cookies. - * - * @param cookieParams Cookie parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processCookieParams(Map cookieParams, Request.Builder reqBuilder) { - for (Entry param : cookieParams.entrySet()) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - for (Entry param : defaultCookieMap.entrySet()) { - if (!cookieParams.containsKey(param.getKey())) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - * @param cookieParams Map of cookie parameters - * @param payload HTTP request body - * @param method HTTP method - * @param uri URI - * @throws io.openepi.common.ApiException If fails to update the parameters - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, - Map cookieParams, String payload, String method, URI uri) throws ApiException { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) { - throw new RuntimeException("Authentication undefined: " + authName); - } - auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); - } - } - - /** - * Build a form-encoding request body with the given form parameters. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - addPartToMultiPartBuilder(mpBuilder, param.getKey(), file); - } else if (param.getValue() instanceof List) { - List list = (List) param.getValue(); - for (Object item: list) { - if (item instanceof File) { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item); - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The guessed Content-Type - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - - /** - * Add a Content-Disposition Header for the given key and file to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param file The file to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, File file) { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); - } - - /** - * Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param obj The complex object to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) { - RequestBody requestBody; - if (obj instanceof String) { - requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain")); - } else { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - requestBody = RequestBody.create(content, MediaType.parse("application/json")); - } - - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""); - mpBuilder.addPart(partHeaders, requestBody); - } - - /** - * Get network interceptor to add it to the httpClient to track download progress for - * async requests. - */ - private Interceptor getProgressInterceptor() { - return new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - final Request request = chain.request(); - final Response originalResponse = chain.proceed(request); - if (request.tag() instanceof ApiCallback) { - final ApiCallback callback = (ApiCallback) request.tag(); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), callback)) - .build(); - } - return originalResponse; - } - }; - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { - try { - TrustManager[] trustManagers; - HostnameVerifier hostnameVerifier; - if (!verifyingSsl) { - trustManagers = new TrustManager[]{ - new X509TrustManager() { - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[]{}; - } - } - }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - } else { - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - - if (sslCaCert == null) { - trustManagerFactory.init((KeyStore) null); - } else { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); - } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + (index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); - } - trustManagerFactory.init(caKeyStore); - } - trustManagers = trustManagerFactory.getTrustManagers(); - hostnameVerifier = OkHostnameVerifier.INSTANCE; - } - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient = httpClient.newBuilder() - .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) - .hostnameVerifier(hostnameVerifier) - .build(); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); - } - } - - /** - * Convert the HTTP request body to a string. - * - * @param requestBody The HTTP request object - * @return The string representation of the HTTP request body - * @throws io.openepi.common.ApiException If fail to serialize the request body object into a string - */ - private String requestBodyToString(RequestBody requestBody) throws ApiException { - if (requestBody != null) { - try { - final Buffer buffer = new Buffer(); - requestBody.writeTo(buffer); - return buffer.readUtf8(); - } catch (final IOException e) { - throw new ApiException(e); - } - } - - // empty http request body - return ""; - } -} diff --git a/src/main/java/io/openepi/deforestation/Configuration.java b/src/main/java/io/openepi/deforestation/Configuration.java deleted file mode 100644 index b42fadd..0000000 --- a/src/main/java/io/openepi/deforestation/Configuration.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:55:50.527454+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class Configuration { - public static final String VERSION = "0.3.6"; - - private static ApiClient defaultApiClient = new ApiClient(); - - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - * - * @return Default API client - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } - - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - * - * @param apiClient API client - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } -} diff --git a/src/main/java/io/openepi/deforestation/JSON.java b/src/main/java/io/openepi/deforestation/JSON.java deleted file mode 100644 index 376097a..0000000 --- a/src/main/java/io/openepi/deforestation/JSON.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.internal.bind.util.ISO8601Utils; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonElement; -import io.gsonfire.GsonFireBuilder; -import io.gsonfire.TypeSelector; - -import okio.ByteString; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Type; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.ParsePosition; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.Locale; -import java.util.Map; -import java.util.HashMap; - -/* - * A JSON utility class - * - * NOTE: in the future, this class may be converted to static, which may break - * backward-compatibility - */ -public class JSON { - private static Gson gson; - private static boolean isLenientOnJson = false; - private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); - private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); - private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); - private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); - private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - - @SuppressWarnings("unchecked") - public static GsonBuilder createGson() { - GsonFireBuilder fireBuilder = new GsonFireBuilder() - ; - GsonBuilder builder = fireBuilder.createGsonBuilder(); - return builder; - } - - private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { - JsonElement element = readElement.getAsJsonObject().get(discriminatorField); - if (null == element) { - throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); - } - return element.getAsString(); - } - - /** - * Returns the Java class that implements the OpenAPI schema for the specified discriminator value. - * - * @param classByDiscriminatorValue The map of discriminator values to Java classes. - * @param discriminatorValue The value of the OpenAPI discriminator in the input data. - * @return The Java class that implements the OpenAPI schema - */ - private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { - Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue); - if (null == clazz) { - throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); - } - return clazz; - } - - static { - GsonBuilder gsonBuilder = createGson(); - gsonBuilder.registerTypeAdapter(Date.class, dateTypeAdapter); - gsonBuilder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); - gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); - gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); - gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.deforestation.model.BasinProperties.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.deforestation.model.DeforestationBasinFeature.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.deforestation.model.DeforestationBasinGeoJSON.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.deforestation.model.Geometry.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.deforestation.model.HTTPValidationError.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.deforestation.model.LossYear.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.deforestation.model.MultiPolygon.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.deforestation.model.Polygon.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.deforestation.model.ValidationError.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.deforestation.model.ValidationErrorLocInner.CustomTypeAdapterFactory()); - gson = gsonBuilder.create(); - } - - /** - * Get Gson. - * - * @return Gson - */ - public static Gson getGson() { - return gson; - } - - /** - * Set Gson. - * - * @param gson Gson - */ - public static void setGson(Gson gson) { - JSON.gson = gson; - } - - public static void setLenientOnJson(boolean lenientOnJson) { - isLenientOnJson = lenientOnJson; - } - - /** - * Serialize the given Java object into JSON string. - * - * @param obj Object - * @return String representation of the JSON - */ - public static String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param Type - * @param body The JSON string - * @param returnType The type to deserialize into - * @return The deserialized Java object - */ - @SuppressWarnings("unchecked") - public static T deserialize(String body, Type returnType) { - try { - if (isLenientOnJson) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - if (returnType.equals(String.class)) { - return (T) body; - } else { - throw (e); - } - } - } - - /** - * Gson TypeAdapter for Byte Array type - */ - public static class ByteArrayAdapter extends TypeAdapter { - - @Override - public void write(JsonWriter out, byte[] value) throws IOException { - if (value == null) { - out.nullValue(); - } else { - out.value(ByteString.of(value).base64()); - } - } - - @Override - public byte[] read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String bytesAsBase64 = in.nextString(); - ByteString byteString = ByteString.decodeBase64(bytesAsBase64); - return byteString.toByteArray(); - } - } - } - - /** - * Gson TypeAdapter for JSR310 OffsetDateTime type - */ - public static class OffsetDateTimeTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public OffsetDateTimeTypeAdapter() { - this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); - } - - public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, OffsetDateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public OffsetDateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - if (date.endsWith("+0000")) { - date = date.substring(0, date.length()-5) + "Z"; - } - return OffsetDateTime.parse(date, formatter); - } - } - } - - /** - * Gson TypeAdapter for JSR310 LocalDate type - */ - public static class LocalDateTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public LocalDateTypeAdapter() { - this(DateTimeFormatter.ISO_LOCAL_DATE); - } - - public LocalDateTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return LocalDate.parse(date, formatter); - } - } - } - - public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - offsetDateTimeTypeAdapter.setFormat(dateFormat); - } - - public static void setLocalDateFormat(DateTimeFormatter dateFormat) { - localDateTypeAdapter.setFormat(dateFormat); - } - - /** - * Gson TypeAdapter for java.sql.Date type - * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used - * (more efficient than SimpleDateFormat). - */ - public static class SqlDateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public SqlDateTypeAdapter() {} - - public SqlDateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, java.sql.Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = date.toString(); - } - out.value(value); - } - } - - @Override - public java.sql.Date read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return new java.sql.Date(dateFormat.parse(date).getTime()); - } - return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } - } - - /** - * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, ISO8601Utils will be used. - */ - public static class DateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public DateTypeAdapter() {} - - public DateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = ISO8601Utils.format(date, true); - } - out.value(value); - } - } - - @Override - public Date read(JsonReader in) throws IOException { - try { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return dateFormat.parse(date); - } - return ISO8601Utils.parse(date, new ParsePosition(0)); - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } catch (IllegalArgumentException e) { - throw new JsonParseException(e); - } - } - } - - public static void setDateFormat(DateFormat dateFormat) { - dateTypeAdapter.setFormat(dateFormat); - } - - public static void setSqlDateFormat(DateFormat dateFormat) { - sqlDateTypeAdapter.setFormat(dateFormat); - } -} diff --git a/src/main/java/io/openepi/deforestation/api/DeforestationApi.java b/src/main/java/io/openepi/deforestation/api/DeforestationApi.java deleted file mode 100644 index d6f22eb..0000000 --- a/src/main/java/io/openepi/deforestation/api/DeforestationApi.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation.api; - -import io.openepi.deforestation.ApiClient; -import io.openepi.deforestation.Configuration; -import io.openepi.common.ApiCallback; -import io.openepi.common.ApiException; -import io.openepi.common.ApiResponse; -import io.openepi.common.Pair; - -import com.google.gson.reflect.TypeToken; - - -import java.math.BigDecimal; -import io.openepi.deforestation.model.DeforestationBasinGeoJSON; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class DeforestationApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public DeforestationApi() { - this(Configuration.getDefaultApiClient()); - } - - public DeforestationApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for lossyearBasinGet - * @param lon Longitude of the point to retrieve data for. (optional) - * @param lat Latitude of the point to retrieve data for. (optional) - * @param minLon Minimum longitude of the bounding box to retrieve data for. (optional) - * @param minLat Minimum latitude of the bounding box to retrieve data for. (optional) - * @param maxLon Maximum longitude of the bounding box to retrieve data for. (optional) - * @param maxLat Maximum latitude of the bounding box to retrieve data for. (optional) - * @param startYear First year in the date range to return data for. (optional, default to 2001) - * @param endYear Last year in the data range to return data for. (optional, default to 2022) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call lossyearBasinGetCall(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal minLat, BigDecimal maxLon, BigDecimal maxLat, Integer startYear, Integer endYear, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/basin"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - if (lon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lon", lon)); - } - - if (lat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lat", lat)); - } - - if (minLon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("min_lon", minLon)); - } - - if (minLat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("min_lat", minLat)); - } - - if (maxLon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("max_lon", maxLon)); - } - - if (maxLat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("max_lat", maxLat)); - } - - if (startYear != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("start_year", startYear)); - } - - if (endYear != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("end_year", endYear)); - } - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call lossyearBasinGetValidateBeforeCall(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal minLat, BigDecimal maxLon, BigDecimal maxLat, Integer startYear, Integer endYear, final ApiCallback _callback) throws ApiException { - return lossyearBasinGetCall(lon, lat, minLon, minLat, maxLon, maxLat, startYear, endYear, _callback); - - } - - /** - * Get yearly forest cover loss within a river basin - * Returns the estimated deforested area per year within a river basin for the given location. To retrieve data for a single point both `lon` and `lon` must be included in the request. To retrieve data within a bounding box all of `min_lon`, `min_lat`, `max_lon`, `max_lat` must be included in the request. - * @param lon Longitude of the point to retrieve data for. (optional) - * @param lat Latitude of the point to retrieve data for. (optional) - * @param minLon Minimum longitude of the bounding box to retrieve data for. (optional) - * @param minLat Minimum latitude of the bounding box to retrieve data for. (optional) - * @param maxLon Maximum longitude of the bounding box to retrieve data for. (optional) - * @param maxLat Maximum latitude of the bounding box to retrieve data for. (optional) - * @param startYear First year in the date range to return data for. (optional, default to 2001) - * @param endYear Last year in the data range to return data for. (optional, default to 2022) - * @return DeforestationBasinGeoJSON - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public DeforestationBasinGeoJSON getLossyearBasin(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal minLat, BigDecimal maxLon, BigDecimal maxLat, Integer startYear, Integer endYear) throws ApiException { - ApiResponse localVarResp = lossyearBasinGetWithHttpInfo(lon, lat, minLon, minLat, maxLon, maxLat, startYear, endYear); - return localVarResp.getData(); - } - - /** - * Get yearly forest cover loss within a river basin for a single point. - * Returns the estimated deforested area per year within a river basin for a single point. - * @param lon Longitude of the point to retrieve data for. (required) - * @param lat Latitude of the point to retrieve data for. (required) - * @return DeforestationBasinGeoJSON - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public DeforestationBasinGeoJSON getLossyearBasinSinglePoint(BigDecimal lon, BigDecimal lat) throws ApiException { - return getLossyearBasin(lon, lat, null, null, null, null, null, null); - } - - /** - * Get yearly forest cover loss within a river basin for a bounding box. - * @param minLon Minimum longitude of the bounding box to retrieve data for. (required) - * @param minLat Minimum latitude of the bounding box to retrieve data for. (required) - * @param maxLon Maximum longitude of the bounding box to retrieve data for. (required) - * @param maxLat Maximum latitude of the bounding box to retrieve data for. (required) - * @return DeforestationBasinGeoJSON - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public DeforestationBasinGeoJSON getLossyearBasinBoundingBox(BigDecimal minLon, BigDecimal minLat, BigDecimal maxLon, BigDecimal maxLat) throws ApiException { - return getLossyearBasin(null, null, minLon, minLat, maxLon, maxLat, null, null); - } - - /** - * Get yearly forest cover loss within a river basin - * Returns the estimated deforested area per year within a river basin for the given location. To retrieve data for a single point both `lon` and `lon` must be included in the request. To retrieve data within a bounding box all of `min_lon`, `min_lat`, `max_lon`, `max_lat` must be included in the request. - * @param lon Longitude of the point to retrieve data for. (optional) - * @param lat Latitude of the point to retrieve data for. (optional) - * @param minLon Minimum longitude of the bounding box to retrieve data for. (optional) - * @param minLat Minimum latitude of the bounding box to retrieve data for. (optional) - * @param maxLon Maximum longitude of the bounding box to retrieve data for. (optional) - * @param maxLat Maximum latitude of the bounding box to retrieve data for. (optional) - * @param startYear First year in the date range to return data for. (optional, default to 2001) - * @param endYear Last year in the data range to return data for. (optional, default to 2022) - * @return ApiResponse<DeforestationBasinGeoJSON> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public ApiResponse lossyearBasinGetWithHttpInfo(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal minLat, BigDecimal maxLon, BigDecimal maxLat, Integer startYear, Integer endYear) throws ApiException { - okhttp3.Call localVarCall = lossyearBasinGetValidateBeforeCall(lon, lat, minLon, minLat, maxLon, maxLat, startYear, endYear, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Get yearly forest cover loss within a river basin (asynchronously) - * Returns the estimated deforested area per year within a river basin for the given location. To retrieve data for a single point both `lon` and `lon` must be included in the request. To retrieve data within a bounding box all of `min_lon`, `min_lat`, `max_lon`, `max_lat` must be included in the request. - * @param lon Longitude of the point to retrieve data for. (optional) - * @param lat Latitude of the point to retrieve data for. (optional) - * @param minLon Minimum longitude of the bounding box to retrieve data for. (optional) - * @param minLat Minimum latitude of the bounding box to retrieve data for. (optional) - * @param maxLon Maximum longitude of the bounding box to retrieve data for. (optional) - * @param maxLat Maximum latitude of the bounding box to retrieve data for. (optional) - * @param startYear First year in the date range to return data for. (optional, default to 2001) - * @param endYear Last year in the data range to return data for. (optional, default to 2022) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call getLossyearBasinAsync(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal minLat, BigDecimal maxLon, BigDecimal maxLat, Integer startYear, Integer endYear, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = lossyearBasinGetValidateBeforeCall(lon, lat, minLon, minLat, maxLon, maxLat, startYear, endYear, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - - - /** - * Get yearly forest cover loss within a river basin (asynchronously) - * Returns the estimated deforested area per year within a river basin for the given location. To retrieve data for a single point both `lon` and `lon` must be included in the request. To retrieve data within a bounding box all of `min_lon`, `min_lat`, `max_lon`, `max_lat` must be included in the request. - * @param lon Longitude of the point to retrieve data for. (required) - * @param lat Latitude of the point to retrieve data for. (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public okhttp3.Call getLossyearBasinSinglePointAsync(BigDecimal lon, BigDecimal lat, final ApiCallback _callback) throws ApiException { - return getLossyearBasinAsync(lon, lat, null, null, null, null, null, null, _callback); - } - - /** - * Get yearly forest cover loss within a river basin (asynchronously) - * Returns the estimated deforested area per year within a river basin for the given location. To retrieve data for a single point both `lon` and `lon` must be included in the request. To retrieve data within a bounding box all of `min_lon`, `min_lat`, `max_lon`, `max_lat` must be included in the request. - * @param minLon Minimum longitude of the bounding box to retrieve data for. (required) - * @param minLat Minimum latitude of the bounding box to retrieve data for. (required) - * @param maxLon Maximum longitude of the bounding box to retrieve data for. (required) - * @param maxLat Maximum latitude of the bounding box to retrieve data for. (required) - * @param _callback The callback to be executed when the API call finishes (required) - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public okhttp3.Call getLossyearBasinBoundingBoxAsync(BigDecimal minLon, BigDecimal minLat, BigDecimal maxLon, BigDecimal maxLat, final ApiCallback _callback) throws ApiException { - return getLossyearBasinAsync(null, null, minLon, minLat, maxLon, maxLat, null, null, _callback); - } -} diff --git a/src/main/java/io/openepi/deforestation/api/HealthApi.java b/src/main/java/io/openepi/deforestation/api/HealthApi.java deleted file mode 100644 index a92ef07..0000000 --- a/src/main/java/io/openepi/deforestation/api/HealthApi.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation.api; - -import io.openepi.deforestation.ApiClient; -import io.openepi.deforestation.Configuration; -import io.openepi.common.ApiCallback; -import io.openepi.common.ApiException; -import io.openepi.common.ApiResponse; -import io.openepi.common.Pair; -import io.openepi.common.ProgressRequestBody; -import io.openepi.common.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class HealthApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public HealthApi() { - this(Configuration.getDefaultApiClient()); - } - - public HealthApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for livenessHealthGet - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call livenessHealthGetCall(final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/health"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call livenessHealthGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { - return livenessHealthGetCall(_callback); - - } - - /** - * Check if this service is alive - * Returns a simple message to indicate that this service is alive - * @return Map<String, String> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public Map livenessHealthGet() throws ApiException { - ApiResponse> localVarResp = livenessHealthGetWithHttpInfo(); - return localVarResp.getData(); - } - - /** - * Check if this service is alive - * Returns a simple message to indicate that this service is alive - * @return ApiResponse<Map<String, String>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public ApiResponse> livenessHealthGetWithHttpInfo() throws ApiException { - okhttp3.Call localVarCall = livenessHealthGetValidateBeforeCall(null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Check if this service is alive (asynchronously) - * Returns a simple message to indicate that this service is alive - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call livenessHealthGetAsync(final ApiCallback> _callback) throws ApiException { - - okhttp3.Call localVarCall = livenessHealthGetValidateBeforeCall(_callback); - Type localVarReturnType = new TypeToken>(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for readyReadyGet - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call readyReadyGetCall(final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/ready"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call readyReadyGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { - return readyReadyGetCall(_callback); - - } - - /** - * Check if this service is ready to receive requests - * Returns a message describing the status of this service - * @return Object - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public Object readyReadyGet() throws ApiException { - ApiResponse localVarResp = readyReadyGetWithHttpInfo(); - return localVarResp.getData(); - } - - /** - * Check if this service is ready to receive requests - * Returns a message describing the status of this service - * @return ApiResponse<Object> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public ApiResponse readyReadyGetWithHttpInfo() throws ApiException { - okhttp3.Call localVarCall = readyReadyGetValidateBeforeCall(null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Check if this service is ready to receive requests (asynchronously) - * Returns a message describing the status of this service - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call readyReadyGetAsync(final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = readyReadyGetValidateBeforeCall(_callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } -} diff --git a/src/main/java/io/openepi/deforestation/model/AbstractOpenApiSchema.java b/src/main/java/io/openepi/deforestation/model/AbstractOpenApiSchema.java deleted file mode 100644 index 6625b94..0000000 --- a/src/main/java/io/openepi/deforestation/model/AbstractOpenApiSchema.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation.model; - -import io.openepi.common.ApiException; -import java.util.Objects; -import java.lang.reflect.Type; -import java.util.Map; - -/** - * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:55:50.527454+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public abstract class AbstractOpenApiSchema { - - // store the actual instance of the schema/object - private Object instance; - - // is nullable - private Boolean isNullable; - - // schema type (e.g. oneOf, anyOf) - private final String schemaType; - - public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { - this.schemaType = schemaType; - this.isNullable = isNullable; - } - - /** - * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object - * - * @return an instance of the actual schema/object - */ - public abstract Map> getSchemas(); - - /** - * Get the actual instance - * - * @return an instance of the actual schema/object - */ - //@JsonValue - public Object getActualInstance() {return instance;} - - /** - * Set the actual instance - * - * @param instance the actual instance of the schema/object - */ - public void setActualInstance(Object instance) {this.instance = instance;} - - /** - * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well - * - * @return an instance of the actual schema/object - */ - public Object getActualInstanceRecursively() { - return getActualInstanceRecursively(this); - } - - private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { - if (object.getActualInstance() == null) { - return null; - } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { - return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); - } else { - return object.getActualInstance(); - } - } - - /** - * Get the schema type (e.g. anyOf, oneOf) - * - * @return the schema type - */ - public String getSchemaType() { - return schemaType; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ").append(getClass()).append(" {\n"); - sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); - sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); - sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; - return Objects.equals(this.instance, a.instance) && - Objects.equals(this.isNullable, a.isNullable) && - Objects.equals(this.schemaType, a.schemaType); - } - - @Override - public int hashCode() { - return Objects.hash(instance, isNullable, schemaType); - } - - /** - * Is nullable - * - * @return true if it's nullable - */ - public Boolean isNullable() { - if (Boolean.TRUE.equals(isNullable)) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } - - - -} diff --git a/src/main/java/io/openepi/deforestation/model/BasinProperties.java b/src/main/java/io/openepi/deforestation/model/BasinProperties.java deleted file mode 100644 index 2f2d80a..0000000 --- a/src/main/java/io/openepi/deforestation/model/BasinProperties.java +++ /dev/null @@ -1,422 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.deforestation.model.LossYear; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.deforestation.JSON; - -/** - * BasinProperties - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:55:50.527454+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class BasinProperties { - public static final String SERIALIZED_NAME_DOWNSTREAM_ID = "downstream_id"; - @SerializedName(SERIALIZED_NAME_DOWNSTREAM_ID) - private Integer downstreamId; - - public static final String SERIALIZED_NAME_BASIN_AREA = "basin_area"; - @SerializedName(SERIALIZED_NAME_BASIN_AREA) - private BigDecimal basinArea; - - public static final String SERIALIZED_NAME_UPSTREAM_AREA = "upstream_area"; - @SerializedName(SERIALIZED_NAME_UPSTREAM_AREA) - private BigDecimal upstreamArea; - - public static final String SERIALIZED_NAME_START_YEAR = "start_year"; - @SerializedName(SERIALIZED_NAME_START_YEAR) - private Integer startYear; - - public static final String SERIALIZED_NAME_END_YEAR = "end_year"; - @SerializedName(SERIALIZED_NAME_END_YEAR) - private Integer endYear; - - public static final String SERIALIZED_NAME_DATERANGE_TOT_TREELOSS = "daterange_tot_treeloss"; - @SerializedName(SERIALIZED_NAME_DATERANGE_TOT_TREELOSS) - private BigDecimal daterangeTotTreeloss; - - public static final String SERIALIZED_NAME_DATERANGE_REL_TREELOSS = "daterange_rel_treeloss"; - @SerializedName(SERIALIZED_NAME_DATERANGE_REL_TREELOSS) - private BigDecimal daterangeRelTreeloss; - - public static final String SERIALIZED_NAME_TREELOSS_PER_YEAR = "treeloss_per_year"; - @SerializedName(SERIALIZED_NAME_TREELOSS_PER_YEAR) - private List treelossPerYear = new ArrayList<>(); - - public BasinProperties() { - } - - public BasinProperties downstreamId(Integer downstreamId) { - this.downstreamId = downstreamId; - return this; - } - - /** - * Id of the next downstream polygon for the current basin polygon. The value 0 means that there is no downstream connection. - * @return downstreamId - */ - @javax.annotation.Nonnull - public Integer getDownstreamId() { - return downstreamId; - } - - public void setDownstreamId(Integer downstreamId) { - this.downstreamId = downstreamId; - } - - - public BasinProperties basinArea(BigDecimal basinArea) { - this.basinArea = basinArea; - return this; - } - - /** - * Area of the basin polygon in square kilometers. - * @return basinArea - */ - @javax.annotation.Nonnull - public BigDecimal getBasinArea() { - return basinArea; - } - - public void setBasinArea(BigDecimal basinArea) { - this.basinArea = basinArea; - } - - - public BasinProperties upstreamArea(BigDecimal upstreamArea) { - this.upstreamArea = upstreamArea; - return this; - } - - /** - * Total upstream area in square kilometers, including the current polygon. - * @return upstreamArea - */ - @javax.annotation.Nonnull - public BigDecimal getUpstreamArea() { - return upstreamArea; - } - - public void setUpstreamArea(BigDecimal upstreamArea) { - this.upstreamArea = upstreamArea; - } - - - public BasinProperties startYear(Integer startYear) { - this.startYear = startYear; - return this; - } - - /** - * Get startYear - * @return startYear - */ - @javax.annotation.Nonnull - public Integer getStartYear() { - return startYear; - } - - public void setStartYear(Integer startYear) { - this.startYear = startYear; - } - - - public BasinProperties endYear(Integer endYear) { - this.endYear = endYear; - return this; - } - - /** - * Get endYear - * @return endYear - */ - @javax.annotation.Nonnull - public Integer getEndYear() { - return endYear; - } - - public void setEndYear(Integer endYear) { - this.endYear = endYear; - } - - - public BasinProperties daterangeTotTreeloss(BigDecimal daterangeTotTreeloss) { - this.daterangeTotTreeloss = daterangeTotTreeloss; - return this; - } - - /** - * Total tree cover loss, in square kilometers, within the basin polygon over the time period from start_year to end_year (inclusive) - * @return daterangeTotTreeloss - */ - @javax.annotation.Nonnull - public BigDecimal getDaterangeTotTreeloss() { - return daterangeTotTreeloss; - } - - public void setDaterangeTotTreeloss(BigDecimal daterangeTotTreeloss) { - this.daterangeTotTreeloss = daterangeTotTreeloss; - } - - - public BasinProperties daterangeRelTreeloss(BigDecimal daterangeRelTreeloss) { - this.daterangeRelTreeloss = daterangeRelTreeloss; - return this; - } - - /** - * Tree cover loss within the basin polygon relative to the total area of the polygon, over the time period from start_year to end_year (inclusive). Equivalent to `daterange_tot_treeloss / basin_area`. - * @return daterangeRelTreeloss - */ - @javax.annotation.Nonnull - public BigDecimal getDaterangeRelTreeloss() { - return daterangeRelTreeloss; - } - - public void setDaterangeRelTreeloss(BigDecimal daterangeRelTreeloss) { - this.daterangeRelTreeloss = daterangeRelTreeloss; - } - - - public BasinProperties treelossPerYear(List treelossPerYear) { - this.treelossPerYear = treelossPerYear; - return this; - } - - public BasinProperties addTreelossPerYearItem(LossYear treelossPerYearItem) { - if (this.treelossPerYear == null) { - this.treelossPerYear = new ArrayList<>(); - } - this.treelossPerYear.add(treelossPerYearItem); - return this; - } - - /** - * Get treelossPerYear - * @return treelossPerYear - */ - @javax.annotation.Nonnull - public List getTreelossPerYear() { - return treelossPerYear; - } - - public void setTreelossPerYear(List treelossPerYear) { - this.treelossPerYear = treelossPerYear; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - BasinProperties basinProperties = (BasinProperties) o; - return Objects.equals(this.downstreamId, basinProperties.downstreamId) && - Objects.equals(this.basinArea, basinProperties.basinArea) && - Objects.equals(this.upstreamArea, basinProperties.upstreamArea) && - Objects.equals(this.startYear, basinProperties.startYear) && - Objects.equals(this.endYear, basinProperties.endYear) && - Objects.equals(this.daterangeTotTreeloss, basinProperties.daterangeTotTreeloss) && - Objects.equals(this.daterangeRelTreeloss, basinProperties.daterangeRelTreeloss) && - Objects.equals(this.treelossPerYear, basinProperties.treelossPerYear); - } - - @Override - public int hashCode() { - return Objects.hash(downstreamId, basinArea, upstreamArea, startYear, endYear, daterangeTotTreeloss, daterangeRelTreeloss, treelossPerYear); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class BasinProperties {\n"); - sb.append(" downstreamId: ").append(toIndentedString(downstreamId)).append("\n"); - sb.append(" basinArea: ").append(toIndentedString(basinArea)).append("\n"); - sb.append(" upstreamArea: ").append(toIndentedString(upstreamArea)).append("\n"); - sb.append(" startYear: ").append(toIndentedString(startYear)).append("\n"); - sb.append(" endYear: ").append(toIndentedString(endYear)).append("\n"); - sb.append(" daterangeTotTreeloss: ").append(toIndentedString(daterangeTotTreeloss)).append("\n"); - sb.append(" daterangeRelTreeloss: ").append(toIndentedString(daterangeRelTreeloss)).append("\n"); - sb.append(" treelossPerYear: ").append(toIndentedString(treelossPerYear)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("downstream_id"); - openapiFields.add("basin_area"); - openapiFields.add("upstream_area"); - openapiFields.add("start_year"); - openapiFields.add("end_year"); - openapiFields.add("daterange_tot_treeloss"); - openapiFields.add("daterange_rel_treeloss"); - openapiFields.add("treeloss_per_year"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("downstream_id"); - openapiRequiredFields.add("basin_area"); - openapiRequiredFields.add("upstream_area"); - openapiRequiredFields.add("start_year"); - openapiRequiredFields.add("end_year"); - openapiRequiredFields.add("daterange_tot_treeloss"); - openapiRequiredFields.add("daterange_rel_treeloss"); - openapiRequiredFields.add("treeloss_per_year"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to BasinProperties - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!BasinProperties.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in BasinProperties is not found in the empty JSON string", BasinProperties.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!BasinProperties.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `BasinProperties` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : BasinProperties.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the json data is an array - if (!jsonObj.get("treeloss_per_year").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `treeloss_per_year` to be an array in the JSON string but got `%s`", jsonObj.get("treeloss_per_year").toString())); - } - - JsonArray jsonArraytreelossPerYear = jsonObj.getAsJsonArray("treeloss_per_year"); - // validate the required field `treeloss_per_year` (array) - for (int i = 0; i < jsonArraytreelossPerYear.size(); i++) { - LossYear.validateJsonElement(jsonArraytreelossPerYear.get(i)); - }; - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!BasinProperties.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'BasinProperties' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(BasinProperties.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, BasinProperties value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public BasinProperties read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of BasinProperties given an JSON string - * - * @param jsonString JSON string - * @return An instance of BasinProperties - * @throws IOException if the JSON string is invalid with respect to BasinProperties - */ - public static BasinProperties fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, BasinProperties.class); - } - - /** - * Convert an instance of BasinProperties to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/deforestation/model/DeforestationBasinFeature.java b/src/main/java/io/openepi/deforestation/model/DeforestationBasinFeature.java deleted file mode 100644 index 948df49..0000000 --- a/src/main/java/io/openepi/deforestation/model/DeforestationBasinFeature.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.deforestation.model.BasinProperties; -import io.openepi.deforestation.model.Geometry; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.deforestation.JSON; - -/** - * DeforestationBasinFeature - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:55:50.527454+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class DeforestationBasinFeature { - public static final String SERIALIZED_NAME_ID = "id"; - @SerializedName(SERIALIZED_NAME_ID) - private Integer id; - - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_PROPERTIES = "properties"; - @SerializedName(SERIALIZED_NAME_PROPERTIES) - private BasinProperties properties; - - public static final String SERIALIZED_NAME_GEOMETRY = "geometry"; - @SerializedName(SERIALIZED_NAME_GEOMETRY) - private Geometry geometry; - - public DeforestationBasinFeature() { - } - - public DeforestationBasinFeature id(Integer id) { - this.id = id; - return this; - } - - /** - * Unique basin polygon identifier. - * @return id - */ - @javax.annotation.Nonnull - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - - public DeforestationBasinFeature type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public DeforestationBasinFeature properties(BasinProperties properties) { - this.properties = properties; - return this; - } - - /** - * Get properties - * @return properties - */ - @javax.annotation.Nonnull - public BasinProperties getProperties() { - return properties; - } - - public void setProperties(BasinProperties properties) { - this.properties = properties; - } - - - public DeforestationBasinFeature geometry(Geometry geometry) { - this.geometry = geometry; - return this; - } - - /** - * Get geometry - * @return geometry - */ - @javax.annotation.Nonnull - public Geometry getGeometry() { - return geometry; - } - - public void setGeometry(Geometry geometry) { - this.geometry = geometry; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - DeforestationBasinFeature deforestationBasinFeature = (DeforestationBasinFeature) o; - return Objects.equals(this.id, deforestationBasinFeature.id) && - Objects.equals(this.type, deforestationBasinFeature.type) && - Objects.equals(this.properties, deforestationBasinFeature.properties) && - Objects.equals(this.geometry, deforestationBasinFeature.geometry); - } - - @Override - public int hashCode() { - return Objects.hash(id, type, properties, geometry); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class DeforestationBasinFeature {\n"); - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); - sb.append(" geometry: ").append(toIndentedString(geometry)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("id"); - openapiFields.add("type"); - openapiFields.add("properties"); - openapiFields.add("geometry"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("id"); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("properties"); - openapiRequiredFields.add("geometry"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to DeforestationBasinFeature - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!DeforestationBasinFeature.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in DeforestationBasinFeature is not found in the empty JSON string", DeforestationBasinFeature.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!DeforestationBasinFeature.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `DeforestationBasinFeature` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : DeforestationBasinFeature.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `properties` - BasinProperties.validateJsonElement(jsonObj.get("properties")); - // validate the required field `geometry` - Geometry.validateJsonElement(jsonObj.get("geometry")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!DeforestationBasinFeature.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'DeforestationBasinFeature' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(DeforestationBasinFeature.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, DeforestationBasinFeature value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public DeforestationBasinFeature read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of DeforestationBasinFeature given an JSON string - * - * @param jsonString JSON string - * @return An instance of DeforestationBasinFeature - * @throws IOException if the JSON string is invalid with respect to DeforestationBasinFeature - */ - public static DeforestationBasinFeature fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, DeforestationBasinFeature.class); - } - - /** - * Convert an instance of DeforestationBasinFeature to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/deforestation/model/DeforestationBasinGeoJSON.java b/src/main/java/io/openepi/deforestation/model/DeforestationBasinGeoJSON.java deleted file mode 100644 index 5c4eb73..0000000 --- a/src/main/java/io/openepi/deforestation/model/DeforestationBasinGeoJSON.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.deforestation.model.DeforestationBasinFeature; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.deforestation.JSON; - -/** - * DeforestationBasinGeoJSON - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:55:50.527454+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class DeforestationBasinGeoJSON { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_FEATURES = "features"; - @SerializedName(SERIALIZED_NAME_FEATURES) - private List features = new ArrayList<>(); - - public DeforestationBasinGeoJSON() { - } - - public DeforestationBasinGeoJSON type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public DeforestationBasinGeoJSON features(List features) { - this.features = features; - return this; - } - - public DeforestationBasinGeoJSON addFeaturesItem(DeforestationBasinFeature featuresItem) { - if (this.features == null) { - this.features = new ArrayList<>(); - } - this.features.add(featuresItem); - return this; - } - - /** - * Get features - * @return features - */ - @javax.annotation.Nonnull - public List getFeatures() { - return features; - } - - public void setFeatures(List features) { - this.features = features; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - DeforestationBasinGeoJSON deforestationBasinGeoJSON = (DeforestationBasinGeoJSON) o; - return Objects.equals(this.type, deforestationBasinGeoJSON.type) && - Objects.equals(this.features, deforestationBasinGeoJSON.features); - } - - @Override - public int hashCode() { - return Objects.hash(type, features); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class DeforestationBasinGeoJSON {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" features: ").append(toIndentedString(features)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("features"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("features"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to DeforestationBasinGeoJSON - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!DeforestationBasinGeoJSON.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in DeforestationBasinGeoJSON is not found in the empty JSON string", DeforestationBasinGeoJSON.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!DeforestationBasinGeoJSON.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `DeforestationBasinGeoJSON` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : DeforestationBasinGeoJSON.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the json data is an array - if (!jsonObj.get("features").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `features` to be an array in the JSON string but got `%s`", jsonObj.get("features").toString())); - } - - JsonArray jsonArrayfeatures = jsonObj.getAsJsonArray("features"); - // validate the required field `features` (array) - for (int i = 0; i < jsonArrayfeatures.size(); i++) { - DeforestationBasinFeature.validateJsonElement(jsonArrayfeatures.get(i)); - }; - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!DeforestationBasinGeoJSON.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'DeforestationBasinGeoJSON' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(DeforestationBasinGeoJSON.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, DeforestationBasinGeoJSON value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public DeforestationBasinGeoJSON read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of DeforestationBasinGeoJSON given an JSON string - * - * @param jsonString JSON string - * @return An instance of DeforestationBasinGeoJSON - * @throws IOException if the JSON string is invalid with respect to DeforestationBasinGeoJSON - */ - public static DeforestationBasinGeoJSON fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, DeforestationBasinGeoJSON.class); - } - - /** - * Convert an instance of DeforestationBasinGeoJSON to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/deforestation/model/Geometry.java b/src/main/java/io/openepi/deforestation/model/Geometry.java deleted file mode 100644 index cd6f034..0000000 --- a/src/main/java/io/openepi/deforestation/model/Geometry.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.deforestation.model.MultiPolygon; -import io.openepi.deforestation.model.Polygon; - - - -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.JsonPrimitive; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonParseException; - -import io.openepi.deforestation.JSON; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:55:50.527454+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class Geometry extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(Geometry.class.getName()); - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!Geometry.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'Geometry' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter adapterPolygon = gson.getDelegateAdapter(this, TypeToken.get(Polygon.class)); - final TypeAdapter adapterMultiPolygon = gson.getDelegateAdapter(this, TypeToken.get(MultiPolygon.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, Geometry value) throws IOException { - if (value == null || value.getActualInstance() == null) { - elementAdapter.write(out, null); - return; - } - - // check if the actual instance is of the type `Polygon` - if (value.getActualInstance() instanceof Polygon) { - JsonElement element = adapterPolygon.toJsonTree((Polygon)value.getActualInstance()); - elementAdapter.write(out, element); - return; - } - // check if the actual instance is of the type `MultiPolygon` - if (value.getActualInstance() instanceof MultiPolygon) { - JsonElement element = adapterMultiPolygon.toJsonTree((MultiPolygon)value.getActualInstance()); - elementAdapter.write(out, element); - return; - } - throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: MultiPolygon, Polygon"); - } - - @Override - public Geometry read(JsonReader in) throws IOException { - Object deserialized = null; - JsonElement jsonElement = elementAdapter.read(in); - - ArrayList errorMessages = new ArrayList<>(); - TypeAdapter actualAdapter = elementAdapter; - - // deserialize Polygon - try { - // validate the JSON object to see if any exception is thrown - Polygon.validateJsonElement(jsonElement); - actualAdapter = adapterPolygon; - Geometry ret = new Geometry(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for Polygon failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'Polygon'", e); - } - // deserialize MultiPolygon - try { - // validate the JSON object to see if any exception is thrown - MultiPolygon.validateJsonElement(jsonElement); - actualAdapter = adapterMultiPolygon; - Geometry ret = new Geometry(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for MultiPolygon failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'MultiPolygon'", e); - } - - throw new IOException(String.format("Failed deserialization for Geometry: no class matches result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); - } - }.nullSafe(); - } - } - - // store a list of schema names defined in anyOf - public static final Map> schemas = new HashMap>(); - - public Geometry() { - super("anyOf", Boolean.FALSE); - } - - public Geometry(Object o) { - super("anyOf", Boolean.FALSE); - setActualInstance(o); - } - - static { - schemas.put("Polygon", Polygon.class); - schemas.put("MultiPolygon", MultiPolygon.class); - } - - @Override - public Map> getSchemas() { - return Geometry.schemas; - } - - /** - * Set the instance that matches the anyOf child schema, check - * the instance parameter is valid against the anyOf child schemas: - * MultiPolygon, Polygon - * - * It could be an instance of the 'anyOf' schemas. - */ - @Override - public void setActualInstance(Object instance) { - if (instance instanceof Polygon) { - super.setActualInstance(instance); - return; - } - - if (instance instanceof MultiPolygon) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be MultiPolygon, Polygon"); - } - - /** - * Get the actual instance, which can be the following: - * MultiPolygon, Polygon - * - * @return The actual instance (MultiPolygon, Polygon) - */ - @SuppressWarnings("unchecked") - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `Polygon`. If the actual instance is not `Polygon`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Polygon` - * @throws ClassCastException if the instance is not `Polygon` - */ - public Polygon getPolygon() throws ClassCastException { - return (Polygon)super.getActualInstance(); - } - /** - * Get the actual instance of `MultiPolygon`. If the actual instance is not `MultiPolygon`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `MultiPolygon` - * @throws ClassCastException if the instance is not `MultiPolygon` - */ - public MultiPolygon getMultiPolygon() throws ClassCastException { - return (MultiPolygon)super.getActualInstance(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to Geometry - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - // validate anyOf schemas one by one - ArrayList errorMessages = new ArrayList<>(); - // validate the json string with Polygon - try { - Polygon.validateJsonElement(jsonElement); - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for Polygon failed with `%s`.", e.getMessage())); - // continue to the next one - } - // validate the json string with MultiPolygon - try { - MultiPolygon.validateJsonElement(jsonElement); - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for MultiPolygon failed with `%s`.", e.getMessage())); - // continue to the next one - } - throw new IOException(String.format("The JSON string is invalid for Geometry with anyOf schemas: MultiPolygon, Polygon. no class match the result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); - } - - /** - * Create an instance of Geometry given an JSON string - * - * @param jsonString JSON string - * @return An instance of Geometry - * @throws IOException if the JSON string is invalid with respect to Geometry - */ - public static Geometry fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, Geometry.class); - } - - /** - * Convert an instance of Geometry to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/deforestation/model/HTTPValidationError.java b/src/main/java/io/openepi/deforestation/model/HTTPValidationError.java deleted file mode 100644 index d1303eb..0000000 --- a/src/main/java/io/openepi/deforestation/model/HTTPValidationError.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.deforestation.model.ValidationError; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.deforestation.JSON; - -/** - * HTTPValidationError - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:55:50.527454+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class HTTPValidationError { - public static final String SERIALIZED_NAME_DETAIL = "detail"; - @SerializedName(SERIALIZED_NAME_DETAIL) - private List detail = new ArrayList<>(); - - public HTTPValidationError() { - } - - public HTTPValidationError detail(List detail) { - this.detail = detail; - return this; - } - - public HTTPValidationError addDetailItem(ValidationError detailItem) { - if (this.detail == null) { - this.detail = new ArrayList<>(); - } - this.detail.add(detailItem); - return this; - } - - /** - * Get detail - * @return detail - */ - @javax.annotation.Nullable - public List getDetail() { - return detail; - } - - public void setDetail(List detail) { - this.detail = detail; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - HTTPValidationError htTPValidationError = (HTTPValidationError) o; - return Objects.equals(this.detail, htTPValidationError.detail); - } - - @Override - public int hashCode() { - return Objects.hash(detail); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class HTTPValidationError {\n"); - sb.append(" detail: ").append(toIndentedString(detail)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("detail"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to HTTPValidationError - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!HTTPValidationError.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in HTTPValidationError is not found in the empty JSON string", HTTPValidationError.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!HTTPValidationError.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `HTTPValidationError` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("detail") != null && !jsonObj.get("detail").isJsonNull()) { - JsonArray jsonArraydetail = jsonObj.getAsJsonArray("detail"); - if (jsonArraydetail != null) { - // ensure the json data is an array - if (!jsonObj.get("detail").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `detail` to be an array in the JSON string but got `%s`", jsonObj.get("detail").toString())); - } - - // validate the optional field `detail` (array) - for (int i = 0; i < jsonArraydetail.size(); i++) { - ValidationError.validateJsonElement(jsonArraydetail.get(i)); - }; - } - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!HTTPValidationError.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'HTTPValidationError' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(HTTPValidationError.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, HTTPValidationError value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public HTTPValidationError read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of HTTPValidationError given an JSON string - * - * @param jsonString JSON string - * @return An instance of HTTPValidationError - * @throws IOException if the JSON string is invalid with respect to HTTPValidationError - */ - public static HTTPValidationError fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, HTTPValidationError.class); - } - - /** - * Convert an instance of HTTPValidationError to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/deforestation/model/LossYear.java b/src/main/java/io/openepi/deforestation/model/LossYear.java deleted file mode 100644 index 0b0886d..0000000 --- a/src/main/java/io/openepi/deforestation/model/LossYear.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.deforestation.JSON; - -/** - * LossYear - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:55:50.527454+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class LossYear { - public static final String SERIALIZED_NAME_YEAR = "year"; - @SerializedName(SERIALIZED_NAME_YEAR) - private Integer year; - - public static final String SERIALIZED_NAME_AREA = "area"; - @SerializedName(SERIALIZED_NAME_AREA) - private BigDecimal area; - - public static final String SERIALIZED_NAME_RELATIVE_AREA = "relative_area"; - @SerializedName(SERIALIZED_NAME_RELATIVE_AREA) - private BigDecimal relativeArea; - - public LossYear() { - } - - public LossYear year(Integer year) { - this.year = year; - return this; - } - - /** - * Year when the loss was detected. - * @return year - */ - @javax.annotation.Nonnull - public Integer getYear() { - return year; - } - - public void setYear(Integer year) { - this.year = year; - } - - - public LossYear area(BigDecimal area) { - this.area = area; - return this; - } - - /** - * Total tree cover loss within the basin polygon, in square kilometers. - * @return area - */ - @javax.annotation.Nonnull - public BigDecimal getArea() { - return area; - } - - public void setArea(BigDecimal area) { - this.area = area; - } - - - public LossYear relativeArea(BigDecimal relativeArea) { - this.relativeArea = relativeArea; - return this; - } - - /** - * Tree cover loss within the basin polygon relative to the total area of the polygon. - * @return relativeArea - */ - @javax.annotation.Nonnull - public BigDecimal getRelativeArea() { - return relativeArea; - } - - public void setRelativeArea(BigDecimal relativeArea) { - this.relativeArea = relativeArea; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - LossYear lossYear = (LossYear) o; - return Objects.equals(this.year, lossYear.year) && - Objects.equals(this.area, lossYear.area) && - Objects.equals(this.relativeArea, lossYear.relativeArea); - } - - @Override - public int hashCode() { - return Objects.hash(year, area, relativeArea); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class LossYear {\n"); - sb.append(" year: ").append(toIndentedString(year)).append("\n"); - sb.append(" area: ").append(toIndentedString(area)).append("\n"); - sb.append(" relativeArea: ").append(toIndentedString(relativeArea)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("year"); - openapiFields.add("area"); - openapiFields.add("relative_area"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("year"); - openapiRequiredFields.add("area"); - openapiRequiredFields.add("relative_area"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to LossYear - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!LossYear.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in LossYear is not found in the empty JSON string", LossYear.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!LossYear.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `LossYear` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : LossYear.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!LossYear.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'LossYear' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(LossYear.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, LossYear value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public LossYear read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of LossYear given an JSON string - * - * @param jsonString JSON string - * @return An instance of LossYear - * @throws IOException if the JSON string is invalid with respect to LossYear - */ - public static LossYear fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, LossYear.class); - } - - /** - * Convert an instance of LossYear to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/deforestation/model/MultiPolygon.java b/src/main/java/io/openepi/deforestation/model/MultiPolygon.java deleted file mode 100644 index 4fc9445..0000000 --- a/src/main/java/io/openepi/deforestation/model/MultiPolygon.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.deforestation.JSON; - -/** - * MultiPolygon - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:55:50.527454+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class MultiPolygon { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_COORDINATES = "coordinates"; - @SerializedName(SERIALIZED_NAME_COORDINATES) - private List>>> coordinates = new ArrayList<>(); - - public MultiPolygon() { - } - - public MultiPolygon type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public MultiPolygon coordinates(List>>> coordinates) { - this.coordinates = coordinates; - return this; - } - - public MultiPolygon addCoordinatesItem(List>> coordinatesItem) { - if (this.coordinates == null) { - this.coordinates = new ArrayList<>(); - } - this.coordinates.add(coordinatesItem); - return this; - } - - /** - * Get coordinates - * @return coordinates - */ - @javax.annotation.Nonnull - public List>>> getCoordinates() { - return coordinates; - } - - public void setCoordinates(List>>> coordinates) { - this.coordinates = coordinates; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MultiPolygon multiPolygon = (MultiPolygon) o; - return Objects.equals(this.type, multiPolygon.type) && - Objects.equals(this.coordinates, multiPolygon.coordinates); - } - - @Override - public int hashCode() { - return Objects.hash(type, coordinates); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class MultiPolygon {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" coordinates: ").append(toIndentedString(coordinates)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("coordinates"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("coordinates"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to MultiPolygon - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!MultiPolygon.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in MultiPolygon is not found in the empty JSON string", MultiPolygon.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!MultiPolygon.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `MultiPolygon` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : MultiPolygon.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the required json array is present - if (jsonObj.get("coordinates") == null) { - throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); - } else if (!jsonObj.get("coordinates").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `coordinates` to be an array in the JSON string but got `%s`", jsonObj.get("coordinates").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!MultiPolygon.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'MultiPolygon' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(MultiPolygon.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, MultiPolygon value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public MultiPolygon read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of MultiPolygon given an JSON string - * - * @param jsonString JSON string - * @return An instance of MultiPolygon - * @throws IOException if the JSON string is invalid with respect to MultiPolygon - */ - public static MultiPolygon fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, MultiPolygon.class); - } - - /** - * Convert an instance of MultiPolygon to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/deforestation/model/Polygon.java b/src/main/java/io/openepi/deforestation/model/Polygon.java deleted file mode 100644 index 3648d8d..0000000 --- a/src/main/java/io/openepi/deforestation/model/Polygon.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.deforestation.JSON; - -/** - * Polygon - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:55:50.527454+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class Polygon { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_COORDINATES = "coordinates"; - @SerializedName(SERIALIZED_NAME_COORDINATES) - private List>> coordinates = new ArrayList<>(); - - public Polygon() { - } - - public Polygon type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public Polygon coordinates(List>> coordinates) { - this.coordinates = coordinates; - return this; - } - - public Polygon addCoordinatesItem(List> coordinatesItem) { - if (this.coordinates == null) { - this.coordinates = new ArrayList<>(); - } - this.coordinates.add(coordinatesItem); - return this; - } - - /** - * Get coordinates - * @return coordinates - */ - @javax.annotation.Nonnull - public List>> getCoordinates() { - return coordinates; - } - - public void setCoordinates(List>> coordinates) { - this.coordinates = coordinates; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Polygon polygon = (Polygon) o; - return Objects.equals(this.type, polygon.type) && - Objects.equals(this.coordinates, polygon.coordinates); - } - - @Override - public int hashCode() { - return Objects.hash(type, coordinates); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Polygon {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" coordinates: ").append(toIndentedString(coordinates)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("coordinates"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("coordinates"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to Polygon - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!Polygon.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in Polygon is not found in the empty JSON string", Polygon.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!Polygon.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Polygon` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : Polygon.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the required json array is present - if (jsonObj.get("coordinates") == null) { - throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); - } else if (!jsonObj.get("coordinates").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `coordinates` to be an array in the JSON string but got `%s`", jsonObj.get("coordinates").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!Polygon.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'Polygon' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(Polygon.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, Polygon value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public Polygon read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of Polygon given an JSON string - * - * @param jsonString JSON string - * @return An instance of Polygon - * @throws IOException if the JSON string is invalid with respect to Polygon - */ - public static Polygon fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, Polygon.class); - } - - /** - * Convert an instance of Polygon to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/deforestation/model/ValidationError.java b/src/main/java/io/openepi/deforestation/model/ValidationError.java deleted file mode 100644 index a4dd2aa..0000000 --- a/src/main/java/io/openepi/deforestation/model/ValidationError.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.deforestation.model.ValidationErrorLocInner; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.deforestation.JSON; - -/** - * ValidationError - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:55:50.527454+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class ValidationError { - public static final String SERIALIZED_NAME_LOC = "loc"; - @SerializedName(SERIALIZED_NAME_LOC) - private List loc = new ArrayList<>(); - - public static final String SERIALIZED_NAME_MSG = "msg"; - @SerializedName(SERIALIZED_NAME_MSG) - private String msg; - - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private String type; - - public ValidationError() { - } - - public ValidationError loc(List loc) { - this.loc = loc; - return this; - } - - public ValidationError addLocItem(ValidationErrorLocInner locItem) { - if (this.loc == null) { - this.loc = new ArrayList<>(); - } - this.loc.add(locItem); - return this; - } - - /** - * Get loc - * @return loc - */ - @javax.annotation.Nonnull - public List getLoc() { - return loc; - } - - public void setLoc(List loc) { - this.loc = loc; - } - - - public ValidationError msg(String msg) { - this.msg = msg; - return this; - } - - /** - * Get msg - * @return msg - */ - @javax.annotation.Nonnull - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - - public ValidationError type(String type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nonnull - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ValidationError validationError = (ValidationError) o; - return Objects.equals(this.loc, validationError.loc) && - Objects.equals(this.msg, validationError.msg) && - Objects.equals(this.type, validationError.type); - } - - @Override - public int hashCode() { - return Objects.hash(loc, msg, type); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ValidationError {\n"); - sb.append(" loc: ").append(toIndentedString(loc)).append("\n"); - sb.append(" msg: ").append(toIndentedString(msg)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("loc"); - openapiFields.add("msg"); - openapiFields.add("type"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("loc"); - openapiRequiredFields.add("msg"); - openapiRequiredFields.add("type"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to ValidationError - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!ValidationError.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in ValidationError is not found in the empty JSON string", ValidationError.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!ValidationError.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ValidationError` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : ValidationError.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the json data is an array - if (!jsonObj.get("loc").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `loc` to be an array in the JSON string but got `%s`", jsonObj.get("loc").toString())); - } - - JsonArray jsonArrayloc = jsonObj.getAsJsonArray("loc"); - // validate the required field `loc` (array) - for (int i = 0; i < jsonArrayloc.size(); i++) { - ValidationErrorLocInner.validateJsonElement(jsonArrayloc.get(i)); - }; - if (!jsonObj.get("msg").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `msg` to be a primitive type in the JSON string but got `%s`", jsonObj.get("msg").toString())); - } - if (!jsonObj.get("type").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!ValidationError.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ValidationError' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(ValidationError.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, ValidationError value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public ValidationError read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of ValidationError given an JSON string - * - * @param jsonString JSON string - * @return An instance of ValidationError - * @throws IOException if the JSON string is invalid with respect to ValidationError - */ - public static ValidationError fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ValidationError.class); - } - - /** - * Convert an instance of ValidationError to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/deforestation/model/ValidationErrorLocInner.java b/src/main/java/io/openepi/deforestation/model/ValidationErrorLocInner.java deleted file mode 100644 index bb8ffb0..0000000 --- a/src/main/java/io/openepi/deforestation/model/ValidationErrorLocInner.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Deforestation API - * This is a RESTful service that provides aggregated deforestation data over the period from 2001 to 2022 based on data provided by Global Land Analysis and Discovery (GLAD) laboratory at the University of Maryland, in partnership with Global Forest Watch (GFW). The data are freely available for use under a Creative Commons Attribution 4.0 International License.
Citation: Hansen, M. C., P. V. Potapov, R. Moore, M. Hancher, S. A. Turubanova, A. Tyukavina, D. Thau, S. V. Stehman, S. J. Goetz, T. R. Loveland, A. Kommareddy, A. Egorov, L. Chini, C. O. Justice, and J. R. G. Townshend. 2013. High-Resolution Global Maps of 21st-Century Forest Cover Change. Science 342 (15 November): 850-53. Data available on-line from: https://glad.earthengine.app/view/global-forest-change.

The data provided by the `basin` endpoint are aggregated over river basin polygons provided by HydroSHEDS. The basin data are feely available for non-commercial and commercial use under a licence agreement included in the HydroSHEDS Technical Documentation. - * - * The version of the OpenAPI document: 0.3.6 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.deforestation.model; - -import java.util.Objects; - - - -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.JsonPrimitive; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonParseException; - -import io.openepi.deforestation.JSON; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:55:50.527454+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class ValidationErrorLocInner extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(ValidationErrorLocInner.class.getName()); - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!ValidationErrorLocInner.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ValidationErrorLocInner' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); - final TypeAdapter adapterInteger = gson.getDelegateAdapter(this, TypeToken.get(Integer.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, ValidationErrorLocInner value) throws IOException { - if (value == null || value.getActualInstance() == null) { - elementAdapter.write(out, null); - return; - } - - // check if the actual instance is of the type `String` - if (value.getActualInstance() instanceof String) { - JsonPrimitive primitive = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonPrimitive(); - elementAdapter.write(out, primitive); - return; - } - // check if the actual instance is of the type `Integer` - if (value.getActualInstance() instanceof Integer) { - JsonPrimitive primitive = adapterInteger.toJsonTree((Integer)value.getActualInstance()).getAsJsonPrimitive(); - elementAdapter.write(out, primitive); - return; - } - throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: Integer, String"); - } - - @Override - public ValidationErrorLocInner read(JsonReader in) throws IOException { - Object deserialized = null; - JsonElement jsonElement = elementAdapter.read(in); - - ArrayList errorMessages = new ArrayList<>(); - TypeAdapter actualAdapter = elementAdapter; - - // deserialize String - try { - // validate the JSON object to see if any exception is thrown - if (!jsonElement.getAsJsonPrimitive().isString()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); - } - actualAdapter = adapterString; - ValidationErrorLocInner ret = new ValidationErrorLocInner(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'String'", e); - } - // deserialize Integer - try { - // validate the JSON object to see if any exception is thrown - if (!jsonElement.getAsJsonPrimitive().isNumber()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); - } - actualAdapter = adapterInteger; - ValidationErrorLocInner ret = new ValidationErrorLocInner(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'Integer'", e); - } - - throw new IOException(String.format("Failed deserialization for ValidationErrorLocInner: no class matches result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); - } - }.nullSafe(); - } - } - - // store a list of schema names defined in anyOf - public static final Map> schemas = new HashMap>(); - - public ValidationErrorLocInner() { - super("anyOf", Boolean.FALSE); - } - - public ValidationErrorLocInner(Object o) { - super("anyOf", Boolean.FALSE); - setActualInstance(o); - } - - static { - schemas.put("String", String.class); - schemas.put("Integer", Integer.class); - } - - @Override - public Map> getSchemas() { - return ValidationErrorLocInner.schemas; - } - - /** - * Set the instance that matches the anyOf child schema, check - * the instance parameter is valid against the anyOf child schemas: - * Integer, String - * - * It could be an instance of the 'anyOf' schemas. - */ - @Override - public void setActualInstance(Object instance) { - if (instance instanceof String) { - super.setActualInstance(instance); - return; - } - - if (instance instanceof Integer) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be Integer, String"); - } - - /** - * Get the actual instance, which can be the following: - * Integer, String - * - * @return The actual instance (Integer, String) - */ - @SuppressWarnings("unchecked") - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `String`. If the actual instance is not `String`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `String` - * @throws ClassCastException if the instance is not `String` - */ - public String getString() throws ClassCastException { - return (String)super.getActualInstance(); - } - /** - * Get the actual instance of `Integer`. If the actual instance is not `Integer`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Integer` - * @throws ClassCastException if the instance is not `Integer` - */ - public Integer getInteger() throws ClassCastException { - return (Integer)super.getActualInstance(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to ValidationErrorLocInner - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - // validate anyOf schemas one by one - ArrayList errorMessages = new ArrayList<>(); - // validate the json string with String - try { - if (!jsonElement.getAsJsonPrimitive().isString()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); - } - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); - // continue to the next one - } - // validate the json string with Integer - try { - if (!jsonElement.getAsJsonPrimitive().isNumber()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); - } - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); - // continue to the next one - } - throw new IOException(String.format("The JSON string is invalid for ValidationErrorLocInner with anyOf schemas: Integer, String. no class match the result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); - } - - /** - * Create an instance of ValidationErrorLocInner given an JSON string - * - * @param jsonString JSON string - * @return An instance of ValidationErrorLocInner - * @throws IOException if the JSON string is invalid with respect to ValidationErrorLocInner - */ - public static ValidationErrorLocInner fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ValidationErrorLocInner.class); - } - - /** - * Convert an instance of ValidationErrorLocInner to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/ApiClient.java b/src/main/java/io/openepi/flood/ApiClient.java deleted file mode 100644 index 2ebbbf8..0000000 --- a/src/main/java/io/openepi/flood/ApiClient.java +++ /dev/null @@ -1,1566 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood; - -import okhttp3.*; -import okhttp3.internal.http.HttpMethod; -import okhttp3.internal.tls.OkHostnameVerifier; -import okhttp3.logging.HttpLoggingInterceptor; -import okhttp3.logging.HttpLoggingInterceptor.Level; -import okio.Buffer; -import okio.BufferedSink; -import okio.Okio; - -import javax.net.ssl.*; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; -import java.net.URI; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.text.DateFormat; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import io.openepi.common.auth.Authentication; -import io.openepi.common.auth.HttpBasicAuth; -import io.openepi.common.auth.HttpBearerAuth; -import io.openepi.common.auth.ApiKeyAuth; - -import io.openepi.common.*; - -/** - *

ApiClient class.

- */ -public class ApiClient { - - private String basePath = "https://api.openepi.io/flood"; - protected List servers = new ArrayList(Arrays.asList( - new ServerConfiguration( - "https://api.openepi.io/flood", - "No description provided", - new HashMap() - ) - )); - protected Integer serverIndex = 0; - protected Map serverVariables = null; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private Map defaultCookieMap = new HashMap(); - private String tempFolderPath = null; - - private Map authentications; - - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; - - private InputStream sslCaCert; - private boolean verifyingSsl; - private KeyManager[] keyManagers; - - private OkHttpClient httpClient; - private JSON json; - - private HttpLoggingInterceptor loggingInterceptor; - - /** - * Basic constructor for ApiClient - */ - public ApiClient() { - init(); - initHttpClient(); - - // Setup authentications (key: authentication name, value: authentication). - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - /** - * Basic constructor with custom OkHttpClient - * - * @param client a {@link okhttp3.OkHttpClient} object - */ - public ApiClient(OkHttpClient client) { - init(); - - httpClient = client; - - // Setup authentications (key: authentication name, value: authentication). - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - private void initHttpClient() { - initHttpClient(Collections.emptyList()); - } - - private void initHttpClient(List interceptors) { - OkHttpClient.Builder builder = new OkHttpClient.Builder(); - builder.addNetworkInterceptor(getProgressInterceptor()); - for (Interceptor interceptor: interceptors) { - builder.addInterceptor(interceptor); - } - - httpClient = builder.build(); - } - - private void init() { - verifyingSsl = true; - - json = new JSON(); - - // Set default User-Agent. - setUserAgent("OpenAPI-Generator/0.9.10/java"); - - authentications = new HashMap(); - } - - /** - * Get base path - * - * @return Base path - */ - public String getBasePath() { - return basePath; - } - - /** - * Set base path - * - * @param basePath Base path of the URL (e.g https://api.openepi.io/flood - * @return An instance of OkHttpClient - */ - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - this.serverIndex = null; - return this; - } - - public List getServers() { - return servers; - } - - public ApiClient setServers(List servers) { - this.servers = servers; - return this; - } - - public Integer getServerIndex() { - return serverIndex; - } - - public ApiClient setServerIndex(Integer serverIndex) { - this.serverIndex = serverIndex; - return this; - } - - public Map getServerVariables() { - return serverVariables; - } - - public ApiClient setServerVariables(Map serverVariables) { - this.serverVariables = serverVariables; - return this; - } - - /** - * Get HTTP client - * - * @return An instance of OkHttpClient - */ - public OkHttpClient getHttpClient() { - return httpClient; - } - - /** - * Set HTTP client, which must never be null. - * - * @param newHttpClient An instance of OkHttpClient - * @return Api Client - * @throws java.lang.NullPointerException when newHttpClient is null - */ - public ApiClient setHttpClient(OkHttpClient newHttpClient) { - this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!"); - return this; - } - - /** - * Get JSON - * - * @return JSON object - */ - public JSON getJSON() { - return json; - } - - /** - * Set JSON - * - * @param json JSON object - * @return Api client - */ - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - /** - * True if isVerifyingSsl flag is on - * - * @return True if isVerifySsl flag is on - */ - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - * - * @param verifyingSsl True to verify TLS/SSL connection - * @return ApiClient - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - /** - * Get SSL CA cert. - * - * @return Input stream to the SSL CA cert - */ - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - * - * @param sslCaCert input stream for SSL CA cert - * @return ApiClient - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - /** - *

Getter for the field keyManagers.

- * - * @return an array of {@link javax.net.ssl.KeyManager} objects - */ - public KeyManager[] getKeyManagers() { - return keyManagers; - } - - /** - * Configure client keys to use for authorization in an SSL session. - * Use null to reset to default. - * - * @param managers The KeyManagers to use - * @return ApiClient - */ - public ApiClient setKeyManagers(KeyManager[] managers) { - this.keyManagers = managers; - applySslSettings(); - return this; - } - - /** - *

Getter for the field dateFormat.

- * - * @return a {@link java.text.DateFormat} object - */ - public DateFormat getDateFormat() { - return dateFormat; - } - - /** - *

Setter for the field dateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link io.openepi.flood.ApiClient} object - */ - public ApiClient setDateFormat(DateFormat dateFormat) { - JSON.setDateFormat(dateFormat); - return this; - } - - /** - *

Set SqlDateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link io.openepi.flood.ApiClient} object - */ - public ApiClient setSqlDateFormat(DateFormat dateFormat) { - JSON.setSqlDateFormat(dateFormat); - return this; - } - - /** - *

Set OffsetDateTimeFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link io.openepi.flood.ApiClient} object - */ - public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - JSON.setOffsetDateTimeFormat(dateFormat); - return this; - } - - /** - *

Set LocalDateFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link io.openepi.flood.ApiClient} object - */ - public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { - JSON.setLocalDateFormat(dateFormat); - return this; - } - - /** - *

Set LenientOnJson.

- * - * @param lenientOnJson a boolean - * @return a {@link io.openepi.flood.ApiClient} object - */ - public ApiClient setLenientOnJson(boolean lenientOnJson) { - JSON.setLenientOnJson(lenientOnJson); - return this; - } - - /** - * Get authentications (key: authentication name, value: authentication). - * - * @return Map of authentication objects - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - - /** - * Helper method to set username for the first HTTP basic authentication. - * - * @param username Username - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - * - * @param password Password - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - * - * @param apiKey API key - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - * - * @param apiKeyPrefix API key prefix - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - * - * @param accessToken Access token - */ - public void setAccessToken(String accessToken) { - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Helper method to set credentials for AWSV4 Signature - * - * @param accessKey Access Key - * @param secretKey Secret Key - * @param region Region - * @param service Service to access to - */ - public void setAWS4Configuration(String accessKey, String secretKey, String region, String service) { - throw new RuntimeException("No AWS4 authentication configured!"); - } - - /** - * Helper method to set credentials for AWSV4 Signature - * - * @param accessKey Access Key - * @param secretKey Secret Key - * @param sessionToken Session Token - * @param region Region - * @param service Service to access to - */ - public void setAWS4Configuration(String accessKey, String secretKey, String sessionToken, String region, String service) { - throw new RuntimeException("No AWS4 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - * - * @param userAgent HTTP request's user agent - * @return ApiClient - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - * @return ApiClient - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * Add a default cookie. - * - * @param key The cookie's key - * @param value The cookie's value - * @return ApiClient - */ - public ApiClient addDefaultCookie(String key, String value) { - defaultCookieMap.put(key, value); - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - * - * @return True if debugging is enabled, false otherwise. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - * @return ApiClient - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); - } else { - final OkHttpClient.Builder builder = httpClient.newBuilder(); - builder.interceptors().remove(loggingInterceptor); - httpClient = builder.build(); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default temporary folder. - * - * @see createTempFile - * @return Temporary folder path - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - /** - * Set the temporary folder path (for downloading files) - * - * @param tempFolderPath Temporary folder path - * @return ApiClient - */ - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Get connection timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getConnectTimeout() { - return httpClient.connectTimeoutMillis(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param connectionTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - /** - * Get read timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getReadTimeout() { - return httpClient.readTimeoutMillis(); - } - - /** - * Sets the read timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param readTimeout read timeout in milliseconds - * @return Api client - */ - public ApiClient setReadTimeout(int readTimeout) { - httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - /** - * Get write timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getWriteTimeout() { - return httpClient.writeTimeoutMillis(); - } - - /** - * Sets the write timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param writeTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setWriteTimeout(int writeTimeout) { - httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - - /** - * Format the given parameter object into string. - * - * @param param Parameter - * @return String representation of the parameter - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) { - //Serialize to json string and remove the " enclosing characters - String jsonStr = JSON.serialize(param); - return jsonStr.substring(1, jsonStr.length() - 1); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection) param) { - if (b.length() > 0) { - b.append(","); - } - b.append(o); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /** - * Formats the specified query parameter to a list containing a single {@code Pair} object. - * - * Note that {@code value} must not be a collection. - * - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list containing a single {@code Pair} object. - */ - public List parameterToPair(String name, Object value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value instanceof Collection) { - return params; - } - - params.add(new Pair(name, parameterToString(value))); - return params; - } - - /** - * Formats the specified collection query parameters to a list of {@code Pair} objects. - * - * Note that the values of each of the returned Pair objects are percent-encoded. - * - * @param collectionFormat The collection format of the parameter. - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list of {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Collection value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value.isEmpty()) { - return params; - } - - // create the params based on the collection format - if ("multi".equals(collectionFormat)) { - for (Object item : value) { - params.add(new Pair(name, escapeString(parameterToString(item)))); - } - return params; - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - // escape all delimiters except commas, which are URI reserved - // characters - if ("ssv".equals(collectionFormat)) { - delimiter = escapeString(" "); - } else if ("tsv".equals(collectionFormat)) { - delimiter = escapeString("\t"); - } else if ("pipes".equals(collectionFormat)) { - delimiter = escapeString("|"); - } - - StringBuilder sb = new StringBuilder(); - for (Object item : value) { - sb.append(delimiter); - sb.append(escapeString(parameterToString(item))); - } - - params.add(new Pair(name, sb.substring(delimiter.length()))); - - return params; - } - - /** - * Formats the specified collection path parameter to a string value. - * - * @param collectionFormat The collection format of the parameter. - * @param value The value of the parameter. - * @return String representation of the parameter - */ - public String collectionPathParameterToString(String collectionFormat, Collection value) { - // create the value based on the collection format - if ("multi".equals(collectionFormat)) { - // not valid for path params - return parameterToString(value); - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - if ("ssv".equals(collectionFormat)) { - delimiter = " "; - } else if ("tsv".equals(collectionFormat)) { - delimiter = "\t"; - } else if ("pipes".equals(collectionFormat)) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : value) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - return sb.substring(delimiter.length()); - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * application/vnd.company+json - * "* / *" is also default to JSON - * @param mime MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public boolean isJsonMime(String mime) { - String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; - return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * returns null. If it matches "any", JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return null; - } - - if (contentTypes[0].equals("*/*")) { - return "application/json"; - } - - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - * - * @param str String to be escaped - * @return Escaped string - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param Type - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws io.openepi.common.ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - @SuppressWarnings("unchecked") - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; - } - - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); - } - - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); - } - - if (respBody == null || "".equals(respBody)) { - return null; - } - - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return JSON.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } - } - - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws io.openepi.common.ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create((File) obj, MediaType.parse(contentType)); - } else if ("text/plain".equals(contentType) && obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - return RequestBody.create(content, MediaType.parse(contentType)); - } else if (obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } - } - - /** - * Download file from the given response. - * - * @param response An instance of the Response object - * @throws io.openepi.common.ApiException If fail to read file content from response and write to disk - * @return Downloaded file - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * Prepare file for download - * - * @param response An instance of the Response object - * @return Prepared file for the download - * @throws java.io.IOException If fail to prepare file for download - */ - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } - } - - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // Files.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; - } - - if (tempFolderPath == null) - return Files.createTempFile(prefix, suffix).toFile(); - else - return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); - } - - /** - * {@link #execute(Call, Type)} - * - * @param Type - * @param call An instance of the Call object - * @return ApiResponse<T> - * @throws io.openepi.common.ApiException If fail to execute the call - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @param call Call - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws io.openepi.common.ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * {@link #executeAsync(Call, Type, ApiCallback)} - * - * @param Type - * @param call An instance of the Call object - * @param callback ApiCallback<T> - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } - - /** - * Execute HTTP call asynchronously. - * - * @param Type - * @param call The callback to be executed when the API call finishes - * @param returnType Return type - * @param callback ApiCallback - * @see #execute(Call, Type) - */ - @SuppressWarnings("unchecked") - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } - - @Override - public void onResponse(Call call, Response response) throws IOException { - T result; - try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; - } catch (Exception e) { - callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); - return; - } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @param Type - * @param response Response - * @param returnType Return type - * @return Type - * @throws io.openepi.common.ApiException If the response has an unsuccessful status code or - * fail to deserialize the response body - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - if (response.body() != null) { - try { - response.body().close(); - } catch (Exception e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { - try { - respBody = response.body().string(); - } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - - /** - * Build HTTP call with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP call - * @throws io.openepi.common.ApiException If fail to serialize the request body object - */ - public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); - - return httpClient.newCall(request); - } - - /** - * Build an HTTP request with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP request - * @throws io.openepi.common.ApiException If fail to serialize the request body object - */ - public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams - List allQueryParams = new ArrayList(queryParams); - allQueryParams.addAll(collectionQueryParams); - - final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); - - // prepare HTTP request body - RequestBody reqBody; - String contentType = headerParams.get("Content-Type"); - String contentTypePure = contentType; - if (contentTypePure != null && contentTypePure.contains(";")) { - contentTypePure = contentType.substring(0, contentType.indexOf(";")); - } - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentTypePure)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentTypePure)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create("", contentType == null ? null : MediaType.parse(contentType)); - } - } else { - reqBody = serialize(body, contentType); - } - - // update parameters with authentication settings - updateParamsForAuth(authNames, allQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url)); - - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - processCookieParams(cookieParams, reqBuilder); - - // Associate callback with request (if not null) so interceptor can - // access it when creating ProgressResponseBody - reqBuilder.tag(callback); - - Request request = null; - - if (callback != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return request; - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param baseUrl The base URL - * @param path The sub path - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @return The full URL - */ - public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { - final StringBuilder url = new StringBuilder(); - if (baseUrl != null) { - url.append(baseUrl).append(path); - } else { - String baseURL; - if (serverIndex != null) { - if (serverIndex < 0 || serverIndex >= servers.size()) { - throw new ArrayIndexOutOfBoundsException(String.format( - "Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size() - )); - } - baseURL = servers.get(serverIndex).URL(serverVariables); - } else { - baseURL = basePath; - } - url.append(baseURL).append(path); - } - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { - String prefix = url.toString().contains("?") ? "&" : "?"; - for (Pair param : collectionQueryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - // collection query parameter value already escaped as part of parameterToPairs - url.append(escapeString(param.getName())).append("=").append(value); - } - } - } - - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - * - * @param headerParams Header parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Set cookie parameters to the request builder, including default cookies. - * - * @param cookieParams Cookie parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processCookieParams(Map cookieParams, Request.Builder reqBuilder) { - for (Entry param : cookieParams.entrySet()) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - for (Entry param : defaultCookieMap.entrySet()) { - if (!cookieParams.containsKey(param.getKey())) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - * @param cookieParams Map of cookie parameters - * @param payload HTTP request body - * @param method HTTP method - * @param uri URI - * @throws io.openepi.common.ApiException If fails to update the parameters - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, - Map cookieParams, String payload, String method, URI uri) throws ApiException { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) { - throw new RuntimeException("Authentication undefined: " + authName); - } - auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); - } - } - - /** - * Build a form-encoding request body with the given form parameters. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - addPartToMultiPartBuilder(mpBuilder, param.getKey(), file); - } else if (param.getValue() instanceof List) { - List list = (List) param.getValue(); - for (Object item: list) { - if (item instanceof File) { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item); - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The guessed Content-Type - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - - /** - * Add a Content-Disposition Header for the given key and file to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param file The file to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, File file) { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); - } - - /** - * Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param obj The complex object to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) { - RequestBody requestBody; - if (obj instanceof String) { - requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain")); - } else { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - requestBody = RequestBody.create(content, MediaType.parse("application/json")); - } - - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""); - mpBuilder.addPart(partHeaders, requestBody); - } - - /** - * Get network interceptor to add it to the httpClient to track download progress for - * async requests. - */ - private Interceptor getProgressInterceptor() { - return new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - final Request request = chain.request(); - final Response originalResponse = chain.proceed(request); - if (request.tag() instanceof ApiCallback) { - final ApiCallback callback = (ApiCallback) request.tag(); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), callback)) - .build(); - } - return originalResponse; - } - }; - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { - try { - TrustManager[] trustManagers; - HostnameVerifier hostnameVerifier; - if (!verifyingSsl) { - trustManagers = new TrustManager[]{ - new X509TrustManager() { - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[]{}; - } - } - }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - } else { - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - - if (sslCaCert == null) { - trustManagerFactory.init((KeyStore) null); - } else { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); - } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + (index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); - } - trustManagerFactory.init(caKeyStore); - } - trustManagers = trustManagerFactory.getTrustManagers(); - hostnameVerifier = OkHostnameVerifier.INSTANCE; - } - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient = httpClient.newBuilder() - .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) - .hostnameVerifier(hostnameVerifier) - .build(); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); - } - } - - /** - * Convert the HTTP request body to a string. - * - * @param requestBody The HTTP request object - * @return The string representation of the HTTP request body - * @throws io.openepi.common.ApiException If fail to serialize the request body object into a string - */ - private String requestBodyToString(RequestBody requestBody) throws ApiException { - if (requestBody != null) { - try { - final Buffer buffer = new Buffer(); - requestBody.writeTo(buffer); - return buffer.readUtf8(); - } catch (final IOException e) { - throw new ApiException(e); - } - } - - // empty http request body - return ""; - } -} diff --git a/src/main/java/io/openepi/flood/Configuration.java b/src/main/java/io/openepi/flood/Configuration.java deleted file mode 100644 index d906f6d..0000000 --- a/src/main/java/io/openepi/flood/Configuration.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class Configuration { - public static final String VERSION = "0.9.10"; - - private static ApiClient defaultApiClient = new ApiClient(); - - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - * - * @return Default API client - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } - - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - * - * @param apiClient API client - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } -} diff --git a/src/main/java/io/openepi/flood/JSON.java b/src/main/java/io/openepi/flood/JSON.java deleted file mode 100644 index 1ce7f8d..0000000 --- a/src/main/java/io/openepi/flood/JSON.java +++ /dev/null @@ -1,416 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.internal.bind.util.ISO8601Utils; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonElement; -import io.gsonfire.GsonFireBuilder; -import io.gsonfire.TypeSelector; - -import okio.ByteString; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Type; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.ParsePosition; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.Locale; -import java.util.Map; -import java.util.HashMap; - -/* - * A JSON utility class - * - * NOTE: in the future, this class may be converted to static, which may break - * backward-compatibility - */ -public class JSON { - private static Gson gson; - private static boolean isLenientOnJson = false; - private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); - private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); - private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); - private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); - private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - - @SuppressWarnings("unchecked") - public static GsonBuilder createGson() { - GsonFireBuilder fireBuilder = new GsonFireBuilder() - ; - GsonBuilder builder = fireBuilder.createGsonBuilder(); - return builder; - } - - private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { - JsonElement element = readElement.getAsJsonObject().get(discriminatorField); - if (null == element) { - throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); - } - return element.getAsString(); - } - - /** - * Returns the Java class that implements the OpenAPI schema for the specified discriminator value. - * - * @param classByDiscriminatorValue The map of discriminator values to Java classes. - * @param discriminatorValue The value of the OpenAPI discriminator in the input data. - * @return The Java class that implements the OpenAPI schema - */ - private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { - Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue); - if (null == clazz) { - throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); - } - return clazz; - } - - static { - GsonBuilder gsonBuilder = createGson(); - gsonBuilder.registerTypeAdapter(Date.class, dateTypeAdapter); - gsonBuilder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); - gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); - gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); - gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.DetailedFeature.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.DetailedFeatureCollection.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.DetailedProperties.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.DetailedResponseModel.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.Geometry.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.HTTPValidationError.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.SummaryFeature.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.SummaryFeatureCollection.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.SummaryProperties.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.SummaryResponseModel.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.ThresholdFeature.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.ThresholdFeatureCollection.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.ThresholdProperties.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.ThresholdResponseModel.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.ValidationError.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.flood.model.ValidationErrorLocInner.CustomTypeAdapterFactory()); - gson = gsonBuilder.create(); - } - - /** - * Get Gson. - * - * @return Gson - */ - public static Gson getGson() { - return gson; - } - - /** - * Set Gson. - * - * @param gson Gson - */ - public static void setGson(Gson gson) { - JSON.gson = gson; - } - - public static void setLenientOnJson(boolean lenientOnJson) { - isLenientOnJson = lenientOnJson; - } - - /** - * Serialize the given Java object into JSON string. - * - * @param obj Object - * @return String representation of the JSON - */ - public static String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param Type - * @param body The JSON string - * @param returnType The type to deserialize into - * @return The deserialized Java object - */ - @SuppressWarnings("unchecked") - public static T deserialize(String body, Type returnType) { - try { - if (isLenientOnJson) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - if (returnType.equals(String.class)) { - return (T) body; - } else { - throw (e); - } - } - } - - /** - * Gson TypeAdapter for Byte Array type - */ - public static class ByteArrayAdapter extends TypeAdapter { - - @Override - public void write(JsonWriter out, byte[] value) throws IOException { - if (value == null) { - out.nullValue(); - } else { - out.value(ByteString.of(value).base64()); - } - } - - @Override - public byte[] read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String bytesAsBase64 = in.nextString(); - ByteString byteString = ByteString.decodeBase64(bytesAsBase64); - return byteString.toByteArray(); - } - } - } - - /** - * Gson TypeAdapter for JSR310 OffsetDateTime type - */ - public static class OffsetDateTimeTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public OffsetDateTimeTypeAdapter() { - this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); - } - - public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, OffsetDateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public OffsetDateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - if (date.endsWith("+0000")) { - date = date.substring(0, date.length()-5) + "Z"; - } - return OffsetDateTime.parse(date, formatter); - } - } - } - - /** - * Gson TypeAdapter for JSR310 LocalDate type - */ - public static class LocalDateTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public LocalDateTypeAdapter() { - this(DateTimeFormatter.ISO_LOCAL_DATE); - } - - public LocalDateTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return LocalDate.parse(date, formatter); - } - } - } - - public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - offsetDateTimeTypeAdapter.setFormat(dateFormat); - } - - public static void setLocalDateFormat(DateTimeFormatter dateFormat) { - localDateTypeAdapter.setFormat(dateFormat); - } - - /** - * Gson TypeAdapter for java.sql.Date type - * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used - * (more efficient than SimpleDateFormat). - */ - public static class SqlDateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public SqlDateTypeAdapter() {} - - public SqlDateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, java.sql.Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = date.toString(); - } - out.value(value); - } - } - - @Override - public java.sql.Date read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return new java.sql.Date(dateFormat.parse(date).getTime()); - } - return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } - } - - /** - * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, ISO8601Utils will be used. - */ - public static class DateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public DateTypeAdapter() {} - - public DateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = ISO8601Utils.format(date, true); - } - out.value(value); - } - } - - @Override - public Date read(JsonReader in) throws IOException { - try { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return dateFormat.parse(date); - } - return ISO8601Utils.parse(date, new ParsePosition(0)); - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } catch (IllegalArgumentException e) { - throw new JsonParseException(e); - } - } - } - - public static void setDateFormat(DateFormat dateFormat) { - dateTypeAdapter.setFormat(dateFormat); - } - - public static void setSqlDateFormat(DateFormat dateFormat) { - sqlDateTypeAdapter.setFormat(dateFormat); - } -} diff --git a/src/main/java/io/openepi/flood/api/FloodApi.java b/src/main/java/io/openepi/flood/api/FloodApi.java deleted file mode 100644 index 6bea4ae..0000000 --- a/src/main/java/io/openepi/flood/api/FloodApi.java +++ /dev/null @@ -1,780 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.api; - -import io.openepi.flood.ApiClient; -import io.openepi.flood.Configuration; -import io.openepi.common.ApiCallback; -import io.openepi.common.ApiException; -import io.openepi.common.ApiResponse; -import io.openepi.common.Pair; - - -import com.google.gson.reflect.TypeToken; - - -import java.math.BigDecimal; -import io.openepi.flood.model.DetailedResponseModel; - -import java.time.LocalDate; -import io.openepi.flood.model.SummaryResponseModel; -import io.openepi.flood.model.ThresholdResponseModel; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class FloodApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public FloodApi() { - this(Configuration.getDefaultApiClient()); - } - - public FloodApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for detailedDetailedGet - * @param lon Longitude (optional) - * @param lat Latitude (optional) - * @param minLon Minimum longitude (optional) - * @param maxLon Maximum longitude (optional) - * @param minLat Minimum latitude (optional) - * @param maxLat Maximum latitude (optional) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @param startDate Inclusive lower bound for the range of dates to return data for. If omitted the date range will not have a lower bound (optional) - * @param endDate Inclusive upper bound for the range of dates to return data for. If omitted the date range will not have an upper bound (optional) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call detailedDetailedGetCall(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors, LocalDate startDate, LocalDate endDate, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/detailed"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - if (lon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lon", lon)); - } - - if (lat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lat", lat)); - } - - if (minLon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("min_lon", minLon)); - } - - if (maxLon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("max_lon", maxLon)); - } - - if (minLat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("min_lat", minLat)); - } - - if (maxLat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("max_lat", maxLat)); - } - - if (includeNeighbors != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("include_neighbors", includeNeighbors)); - } - - if (startDate != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("start_date", startDate)); - } - - if (endDate != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("end_date", endDate)); - } - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call detailedDetailedGetValidateBeforeCall(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors, LocalDate startDate, LocalDate endDate, final ApiCallback _callback) throws ApiException { - return detailedDetailedGetCall(lon, lat, minLon, maxLon, minLat, maxLat, includeNeighbors, startDate, endDate, _callback); - - } - - /** - * Get detailed forecast for a location - * Returns a detailed forecast of the next 30 days either for the cell at the given coordinates or for the cells within the given bounding box - * @param lon Longitude (optional) - * @param lat Latitude (optional) - * @param minLon Minimum longitude (optional) - * @param maxLon Maximum longitude (optional) - * @param minLat Minimum latitude (optional) - * @param maxLat Maximum latitude (optional) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @param startDate Inclusive lower bound for the range of dates to return data for. If omitted the date range will not have a lower bound (optional) - * @param endDate Inclusive upper bound for the range of dates to return data for. If omitted the date range will not have an upper bound (optional) - * @return DetailedResponseModel - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public DetailedResponseModel getDetailedForecast(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors, LocalDate startDate, LocalDate endDate) throws ApiException { - ApiResponse localVarResp = detailedDetailedGetWithHttpInfo(lon, lat, minLon, maxLon, minLat, maxLat, includeNeighbors, startDate, endDate); - return localVarResp.getData(); - } - - - /** - * Get detailed forecast for a location - * Returns a detailed forecast of the next 30 days either for the cell at the given coordinates or for the cells within the given bounding box - * @param lon Longitude (required) - * @param lat Latitude (required) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @return DetailedResponseModel - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public DetailedResponseModel getDetailedForecastSinglePoint(BigDecimal lon, BigDecimal lat, Boolean includeNeighbors) throws ApiException { - return getDetailedForecast(lon, lat, null, null, null, null, includeNeighbors, null, null); - } - - /** - * Get detailed forecast for a location - * Returns a detailed forecast of the next 30 days either for the cell at the given coordinates or for the cells within the given bounding box - * @param minLon Minimum longitude (required) - * @param maxLon Maximum longitude (required) - * @param minLat Minimum latitude (required) - * @param maxLat Maximum latitude (required) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @return DetailedResponseModel - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public DetailedResponseModel getDetailedForecastBoundingBox(BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors) throws ApiException { - return getDetailedForecast(null, null, minLon, maxLon, minLat, maxLat, includeNeighbors, null, null); - } - - /** - * Get detailed forecast for a location - * Returns a detailed forecast of the next 30 days either for the cell at the given coordinates or for the cells within the given bounding box - * @param lon Longitude (optional) - * @param lat Latitude (optional) - * @param minLon Minimum longitude (optional) - * @param maxLon Maximum longitude (optional) - * @param minLat Minimum latitude (optional) - * @param maxLat Maximum latitude (optional) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @param startDate Inclusive lower bound for the range of dates to return data for. If omitted the date range will not have a lower bound (optional) - * @param endDate Inclusive upper bound for the range of dates to return data for. If omitted the date range will not have an upper bound (optional) - * @return ApiResponse<DetailedResponseModel> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public ApiResponse detailedDetailedGetWithHttpInfo(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors, LocalDate startDate, LocalDate endDate) throws ApiException { - okhttp3.Call localVarCall = detailedDetailedGetValidateBeforeCall(lon, lat, minLon, maxLon, minLat, maxLat, includeNeighbors, startDate, endDate, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Get detailed forecast for a location (asynchronously) - * Returns a detailed forecast of the next 30 days either for the cell at the given coordinates or for the cells within the given bounding box - * @param lon Longitude (optional) - * @param lat Latitude (optional) - * @param minLon Minimum longitude (optional) - * @param maxLon Maximum longitude (optional) - * @param minLat Minimum latitude (optional) - * @param maxLat Maximum latitude (optional) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @param startDate Inclusive lower bound for the range of dates to return data for. If omitted the date range will not have a lower bound (optional) - * @param endDate Inclusive upper bound for the range of dates to return data for. If omitted the date range will not have an upper bound (optional) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call getDetailedForecastAsync(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors, LocalDate startDate, LocalDate endDate, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = detailedDetailedGetValidateBeforeCall(lon, lat, minLon, maxLon, minLat, maxLat, includeNeighbors, startDate, endDate, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - - /** - * Get detailed forecast for a location point (asynchronously) - * Returns a detailed forecast of the next 30 days for the cell at the given coordinates - * @param lon Longitude (required) - * @param lat Latitude (required) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public okhttp3.Call getDetailedForecastSinglePointAsync(BigDecimal lon, BigDecimal lat, Boolean includeNeighbors, final ApiCallback _callback) throws ApiException { - return getDetailedForecastAsync(lon, lat, null, null, null, null, includeNeighbors, null, null, _callback); - } - - /** - * Get detailed forecast for a bounding box (asynchronously) - * Returns a detailed forecast of the next 30 days for the cells within the given bounding box - * @param minLon Minimum longitude (required) - * @param maxLon Maximum longitude (required) - * @param minLat Minimum latitude (required) - * @param maxLat Maximum latitude (required) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public okhttp3.Call getDetailedForecastBoundingBoxAsync(BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors, final ApiCallback _callback) throws ApiException { - return getDetailedForecastAsync(null, null, minLon, maxLon, minLat, maxLat, includeNeighbors, null, null, _callback); - } - - - /** - * Build call for summarySummaryGet - * @param lon Longitude (optional) - * @param lat Latitude (optional) - * @param minLon Minimum longitude (optional) - * @param maxLon Maximum longitude (optional) - * @param minLat Minimum latitude (optional) - * @param maxLat Maximum latitude (optional) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call summarySummaryGetCall(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/summary"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - if (lon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lon", lon)); - } - - if (lat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lat", lat)); - } - - if (minLon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("min_lon", minLon)); - } - - if (maxLon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("max_lon", maxLon)); - } - - if (minLat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("min_lat", minLat)); - } - - if (maxLat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("max_lat", maxLat)); - } - - if (includeNeighbors != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("include_neighbors", includeNeighbors)); - } - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call summarySummaryGetValidateBeforeCall(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors, final ApiCallback _callback) throws ApiException { - return summarySummaryGetCall(lon, lat, minLon, maxLon, minLat, maxLat, includeNeighbors, _callback); - - } - - /** - * Get summary forecast for a location - * Returns a summary forecast of the next 30 days either for the cell at the given coordinates or for the cells within the given bounding box - * @param lon Longitude (optional) - * @param lat Latitude (optional) - * @param minLon Minimum longitude (optional) - * @param maxLon Maximum longitude (optional) - * @param minLat Minimum latitude (optional) - * @param maxLat Maximum latitude (optional) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @return SummaryResponseModel - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public SummaryResponseModel getForecastSummary(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors) throws ApiException { - ApiResponse localVarResp = summarySummaryGetWithHttpInfo(lon, lat, minLon, maxLon, minLat, maxLat, includeNeighbors); - return localVarResp.getData(); - } - - /** - * Get summary forecast for a single point location - * Returns a summary forecast of the next 30 days for the cell at the given coordinates - * @param lon Longitude (required) - * @param lat Latitude (required) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @return SummaryResponseModel - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public SummaryResponseModel getForecastSummarySinglePoint(BigDecimal lon, BigDecimal lat, Boolean includeNeighbors) throws ApiException { - return getForecastSummary(lon, lat, null, null, null, null, includeNeighbors); - } - - /** - * Get summary forecast for a bounding box - * Returns a summary forecast of the next 30 days for the cells within the given bounding box - * @param minLon Minimum longitude (required) - * @param maxLon Maximum longitude (required) - * @param minLat Minimum latitude (required) - * @param maxLat Maximum latitude (required) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @return SummaryResponseModel - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public SummaryResponseModel getForecastSummaryBoundingBox(BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors) throws ApiException { - return getForecastSummary(null, null, minLon, maxLon, minLat, maxLat, includeNeighbors); - } - - /** - * Get summary forecast for a location - * Returns a summary forecast of the next 30 days either for the cell at the given coordinates or for the cells within the given bounding box - * @param lon Longitude (optional) - * @param lat Latitude (optional) - * @param minLon Minimum longitude (optional) - * @param maxLon Maximum longitude (optional) - * @param minLat Minimum latitude (optional) - * @param maxLat Maximum latitude (optional) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @return ApiResponse<SummaryResponseModel> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public ApiResponse summarySummaryGetWithHttpInfo(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors) throws ApiException { - okhttp3.Call localVarCall = summarySummaryGetValidateBeforeCall(lon, lat, minLon, maxLon, minLat, maxLat, includeNeighbors, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Get summary forecast for a location (asynchronously) - * Returns a summary forecast of the next 30 days either for the cell at the given coordinates or for the cells within the given bounding box - * @param lon Longitude (optional) - * @param lat Latitude (optional) - * @param minLon Minimum longitude (optional) - * @param maxLon Maximum longitude (optional) - * @param minLat Minimum latitude (optional) - * @param maxLat Maximum latitude (optional) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call getForecastSummaryAsync(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = summarySummaryGetValidateBeforeCall(lon, lat, minLon, maxLon, minLat, maxLat, includeNeighbors, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - - /** - * Get summary forecast for a location (asynchronously) - * Returns a summary forecast of the next 30 days for the cell at the given coordinates - * @param lon Longitude (optional) - * @param lat Latitude (optional) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - */ - public okhttp3.Call getForecastSummarySinglePointAsync(BigDecimal lon, BigDecimal lat, Boolean includeNeighbors, final ApiCallback _callback) throws ApiException { - return getForecastSummaryAsync(lon, lat, null, null, null, null, includeNeighbors, _callback); - } - - /** - * Get summary forecast for a bounding box (asynchronously) - * Returns a summary forecast of the next 30 days for the cells within the given bounding box - * @param minLon Minimum longitude (optional) - * @param maxLon Maximum longitude (optional) - * @param minLat Minimum latitude (optional) - * @param maxLat Maximum latitude (optional) - * @param includeNeighbors Whether or not to include neighboring cells in the response (optional, default to false) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public okhttp3.Call getForecastSummaryBoundingBoxAsync(BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, Boolean includeNeighbors, final ApiCallback _callback) throws ApiException { - return getForecastSummaryAsync(null, null, minLon, maxLon, minLat, maxLat, includeNeighbors, _callback); - } - - /** - * Build call for thresholdThresholdGet - * @param lon Longitude (optional) - * @param lat Latitude (optional) - * @param minLon Minimum longitude (optional) - * @param maxLon Maximum longitude (optional) - * @param minLat Minimum latitude (optional) - * @param maxLat Maximum latitude (optional) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call thresholdThresholdGetCall(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/threshold"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - if (lon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lon", lon)); - } - - if (lat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lat", lat)); - } - - if (minLon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("min_lon", minLon)); - } - - if (maxLon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("max_lon", maxLon)); - } - - if (minLat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("min_lat", minLat)); - } - - if (maxLat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("max_lat", maxLat)); - } - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call thresholdThresholdGetValidateBeforeCall(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, final ApiCallback _callback) throws ApiException { - return thresholdThresholdGetCall(lon, lat, minLon, maxLon, minLat, maxLat, _callback); - - } - - /** - * Get return period thresholds for a location - * Returns the 2-, 5-, and 20-year return period thresholds either for the cell at the given coordinates or for the cells within the given bounding box - * @param lon Longitude (optional) - * @param lat Latitude (optional) - * @param minLon Minimum longitude (optional) - * @param maxLon Maximum longitude (optional) - * @param minLat Minimum latitude (optional) - * @param maxLat Maximum latitude (optional) - * @return ThresholdResponseModel - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public ThresholdResponseModel getThreshold(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat) throws ApiException { - ApiResponse localVarResp = thresholdThresholdGetWithHttpInfo(lon, lat, minLon, maxLon, minLat, maxLat); - return localVarResp.getData(); - } - - /** - * Get return period thresholds for a location - * Returns the 2-, 5-, and 20-year return period thresholds for the cell at the given coordinates - * @param lon Longitude (required) - * @param lat Latitude (required) - * @return ThresholdResponseModel - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ThresholdResponseModel getThresholdSinglePoint(BigDecimal lon, BigDecimal lat) throws ApiException { - return getThreshold(lon, lat, null, null, null, null); - } - - /** - * Get return period thresholds for a location - * Returns the 2-, 5-, and 20-year return period thresholds for the cells within the given bounding box - * @param minLon Minimum longitude (required) - * @param maxLon Maximum longitude (required) - * @param minLat Minimum latitude (required) - * @param maxLat Maximum latitude (required) - * @return ThresholdResponseModel - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ThresholdResponseModel getThresholdBoundingBox(BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat) throws ApiException { - return getThreshold(null, null, minLon, maxLon, minLat, maxLat); - } - - /** - * Get return period thresholds for a location - * Returns the 2-, 5-, and 20-year return period thresholds either for the cell at the given coordinates or for the cells within the given bounding box - * @param lon Longitude (optional) - * @param lat Latitude (optional) - * @param minLon Minimum longitude (optional) - * @param maxLon Maximum longitude (optional) - * @param minLat Minimum latitude (optional) - * @param maxLat Maximum latitude (optional) - * @return ApiResponse<ThresholdResponseModel> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public ApiResponse thresholdThresholdGetWithHttpInfo(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat) throws ApiException { - okhttp3.Call localVarCall = thresholdThresholdGetValidateBeforeCall(lon, lat, minLon, maxLon, minLat, maxLat, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Get return period thresholds for a location (asynchronously) - * Returns the 2-, 5-, and 20-year return period thresholds either for the cell at the given coordinates or for the cells within the given bounding box - * @param lon Longitude (optional) - * @param lat Latitude (optional) - * @param minLon Minimum longitude (optional) - * @param maxLon Maximum longitude (optional) - * @param minLat Minimum latitude (optional) - * @param maxLat Maximum latitude (optional) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call getThresholdAsync(BigDecimal lon, BigDecimal lat, BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = thresholdThresholdGetValidateBeforeCall(lon, lat, minLon, maxLon, minLat, maxLat, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - - - /** - * Get return period thresholds for a location (asynchronously) - * Returns the 2-, 5-, and 20-year return period thresholds for the cell at the given coordinates - * @param lon Longitude (required) - * @param lat Latitude (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public okhttp3.Call getThresholdSinglePointAsync(BigDecimal lon, BigDecimal lat, final ApiCallback _callback) throws ApiException { - return getThresholdAsync(lon, lat, null, null, null, null, _callback); - } - - /** - * Get return period thresholds for a location (asynchronously) - * Returns the 2-, 5-, and 20-year return period thresholds for the cells within the given bounding box - * @param minLon Minimum longitude (required) - * @param maxLon Maximum longitude (required) - * @param minLat Minimum latitude (required) - * @param maxLat Maximum latitude (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public okhttp3.Call getThresholdBoundingBoxAsync(BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, final ApiCallback _callback) throws ApiException { - return getThresholdAsync(null, null, minLon, maxLon, minLat, maxLat, _callback); - } -} diff --git a/src/main/java/io/openepi/flood/api/HealthApi.java b/src/main/java/io/openepi/flood/api/HealthApi.java deleted file mode 100644 index 2e19521..0000000 --- a/src/main/java/io/openepi/flood/api/HealthApi.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.api; - -import io.openepi.flood.ApiClient; -import io.openepi.flood.Configuration; -import io.openepi.common.ApiCallback; -import io.openepi.common.ApiException; -import io.openepi.common.ApiResponse; -import io.openepi.common.Pair; -import io.openepi.common.ProgressRequestBody; -import io.openepi.common.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class HealthApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public HealthApi() { - this(Configuration.getDefaultApiClient()); - } - - public HealthApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for livenessHealthGet - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call livenessHealthGetCall(final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/health"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call livenessHealthGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { - return livenessHealthGetCall(_callback); - - } - - /** - * Check if this service is alive - * Returns a simple message to indicate that this service is alive - * @return Map<String, String> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public Map livenessHealthGet() throws ApiException { - ApiResponse> localVarResp = livenessHealthGetWithHttpInfo(); - return localVarResp.getData(); - } - - /** - * Check if this service is alive - * Returns a simple message to indicate that this service is alive - * @return ApiResponse<Map<String, String>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public ApiResponse> livenessHealthGetWithHttpInfo() throws ApiException { - okhttp3.Call localVarCall = livenessHealthGetValidateBeforeCall(null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Check if this service is alive (asynchronously) - * Returns a simple message to indicate that this service is alive - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call livenessHealthGetAsync(final ApiCallback> _callback) throws ApiException { - - okhttp3.Call localVarCall = livenessHealthGetValidateBeforeCall(_callback); - Type localVarReturnType = new TypeToken>(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for readyReadyGet - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call readyReadyGetCall(final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/ready"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call readyReadyGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { - return readyReadyGetCall(_callback); - - } - - /** - * Check if this service is ready to receive requests - * Returns a message describing the status of this service - * @return Object - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public Object readyReadyGet() throws ApiException { - ApiResponse localVarResp = readyReadyGetWithHttpInfo(); - return localVarResp.getData(); - } - - /** - * Check if this service is ready to receive requests - * Returns a message describing the status of this service - * @return ApiResponse<Object> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public ApiResponse readyReadyGetWithHttpInfo() throws ApiException { - okhttp3.Call localVarCall = readyReadyGetValidateBeforeCall(null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Check if this service is ready to receive requests (asynchronously) - * Returns a message describing the status of this service - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call readyReadyGetAsync(final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = readyReadyGetValidateBeforeCall(_callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } -} diff --git a/src/main/java/io/openepi/flood/model/AbstractOpenApiSchema.java b/src/main/java/io/openepi/flood/model/AbstractOpenApiSchema.java deleted file mode 100644 index 359516c..0000000 --- a/src/main/java/io/openepi/flood/model/AbstractOpenApiSchema.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import io.openepi.common.ApiException; - -import java.util.Objects; -import java.lang.reflect.Type; -import java.util.Map; - -/** - * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public abstract class AbstractOpenApiSchema { - - // store the actual instance of the schema/object - private Object instance; - - // is nullable - private Boolean isNullable; - - // schema type (e.g. oneOf, anyOf) - private final String schemaType; - - public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { - this.schemaType = schemaType; - this.isNullable = isNullable; - } - - /** - * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object - * - * @return an instance of the actual schema/object - */ - public abstract Map> getSchemas(); - - /** - * Get the actual instance - * - * @return an instance of the actual schema/object - */ - //@JsonValue - public Object getActualInstance() {return instance;} - - /** - * Set the actual instance - * - * @param instance the actual instance of the schema/object - */ - public void setActualInstance(Object instance) {this.instance = instance;} - - /** - * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well - * - * @return an instance of the actual schema/object - */ - public Object getActualInstanceRecursively() { - return getActualInstanceRecursively(this); - } - - private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { - if (object.getActualInstance() == null) { - return null; - } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { - return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); - } else { - return object.getActualInstance(); - } - } - - /** - * Get the schema type (e.g. anyOf, oneOf) - * - * @return the schema type - */ - public String getSchemaType() { - return schemaType; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ").append(getClass()).append(" {\n"); - sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); - sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); - sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; - return Objects.equals(this.instance, a.instance) && - Objects.equals(this.isNullable, a.isNullable) && - Objects.equals(this.schemaType, a.schemaType); - } - - @Override - public int hashCode() { - return Objects.hash(instance, isNullable, schemaType); - } - - /** - * Is nullable - * - * @return true if it's nullable - */ - public Boolean isNullable() { - if (Boolean.TRUE.equals(isNullable)) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } - - - -} diff --git a/src/main/java/io/openepi/flood/model/DetailedFeature.java b/src/main/java/io/openepi/flood/model/DetailedFeature.java deleted file mode 100644 index f7abbc9..0000000 --- a/src/main/java/io/openepi/flood/model/DetailedFeature.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.flood.model.DetailedProperties; -import io.openepi.flood.model.Geometry; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * DetailedFeature - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class DetailedFeature { - public static final String SERIALIZED_NAME_ID = "id"; - @SerializedName(SERIALIZED_NAME_ID) - private String id; - - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_GEOMETRY = "geometry"; - @SerializedName(SERIALIZED_NAME_GEOMETRY) - private Geometry geometry; - - public static final String SERIALIZED_NAME_PROPERTIES = "properties"; - @SerializedName(SERIALIZED_NAME_PROPERTIES) - private DetailedProperties properties; - - public DetailedFeature() { - } - - public DetailedFeature id(String id) { - this.id = id; - return this; - } - - /** - * A unique identifier for the feature. - * @return id - */ - @javax.annotation.Nonnull - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - - public DetailedFeature type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public DetailedFeature geometry(Geometry geometry) { - this.geometry = geometry; - return this; - } - - /** - * The geometric details of the feature, including its type and coordinates. - * @return geometry - */ - @javax.annotation.Nonnull - public Geometry getGeometry() { - return geometry; - } - - public void setGeometry(Geometry geometry) { - this.geometry = geometry; - } - - - public DetailedFeature properties(DetailedProperties properties) { - this.properties = properties; - return this; - } - - /** - * Specific properties of the detailed forecast, including probabilities for different return periods and discharge statistics. - * @return properties - */ - @javax.annotation.Nonnull - public DetailedProperties getProperties() { - return properties; - } - - public void setProperties(DetailedProperties properties) { - this.properties = properties; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - DetailedFeature detailedFeature = (DetailedFeature) o; - return Objects.equals(this.id, detailedFeature.id) && - Objects.equals(this.type, detailedFeature.type) && - Objects.equals(this.geometry, detailedFeature.geometry) && - Objects.equals(this.properties, detailedFeature.properties); - } - - @Override - public int hashCode() { - return Objects.hash(id, type, geometry, properties); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class DetailedFeature {\n"); - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" geometry: ").append(toIndentedString(geometry)).append("\n"); - sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("id"); - openapiFields.add("type"); - openapiFields.add("geometry"); - openapiFields.add("properties"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("id"); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("geometry"); - openapiRequiredFields.add("properties"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to DetailedFeature - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!DetailedFeature.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in DetailedFeature is not found in the empty JSON string", DetailedFeature.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!DetailedFeature.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `DetailedFeature` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : DetailedFeature.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (!jsonObj.get("id").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("id").toString())); - } - // validate the required field `geometry` - Geometry.validateJsonElement(jsonObj.get("geometry")); - // validate the required field `properties` - DetailedProperties.validateJsonElement(jsonObj.get("properties")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!DetailedFeature.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'DetailedFeature' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(DetailedFeature.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, DetailedFeature value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public DetailedFeature read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of DetailedFeature given an JSON string - * - * @param jsonString JSON string - * @return An instance of DetailedFeature - * @throws IOException if the JSON string is invalid with respect to DetailedFeature - */ - public static DetailedFeature fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, DetailedFeature.class); - } - - /** - * Convert an instance of DetailedFeature to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/DetailedFeatureCollection.java b/src/main/java/io/openepi/flood/model/DetailedFeatureCollection.java deleted file mode 100644 index 9f048df..0000000 --- a/src/main/java/io/openepi/flood/model/DetailedFeatureCollection.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.flood.model.DetailedFeature; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * DetailedFeatureCollection - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class DetailedFeatureCollection { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_FEATURES = "features"; - @SerializedName(SERIALIZED_NAME_FEATURES) - private List features = new ArrayList<>(); - - public DetailedFeatureCollection() { - } - - public DetailedFeatureCollection type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public DetailedFeatureCollection features(List features) { - this.features = features; - return this; - } - - public DetailedFeatureCollection addFeaturesItem(DetailedFeature featuresItem) { - if (this.features == null) { - this.features = new ArrayList<>(); - } - this.features.add(featuresItem); - return this; - } - - /** - * A collection of detailed forecasts, providing extensive forecast data including detailed probabilities and discharge information. - * @return features - */ - @javax.annotation.Nonnull - public List getFeatures() { - return features; - } - - public void setFeatures(List features) { - this.features = features; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - DetailedFeatureCollection detailedFeatureCollection = (DetailedFeatureCollection) o; - return Objects.equals(this.type, detailedFeatureCollection.type) && - Objects.equals(this.features, detailedFeatureCollection.features); - } - - @Override - public int hashCode() { - return Objects.hash(type, features); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class DetailedFeatureCollection {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" features: ").append(toIndentedString(features)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("features"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("features"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to DetailedFeatureCollection - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!DetailedFeatureCollection.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in DetailedFeatureCollection is not found in the empty JSON string", DetailedFeatureCollection.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!DetailedFeatureCollection.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `DetailedFeatureCollection` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : DetailedFeatureCollection.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the json data is an array - if (!jsonObj.get("features").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `features` to be an array in the JSON string but got `%s`", jsonObj.get("features").toString())); - } - - JsonArray jsonArrayfeatures = jsonObj.getAsJsonArray("features"); - // validate the required field `features` (array) - for (int i = 0; i < jsonArrayfeatures.size(); i++) { - DetailedFeature.validateJsonElement(jsonArrayfeatures.get(i)); - }; - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!DetailedFeatureCollection.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'DetailedFeatureCollection' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(DetailedFeatureCollection.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, DetailedFeatureCollection value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public DetailedFeatureCollection read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of DetailedFeatureCollection given an JSON string - * - * @param jsonString JSON string - * @return An instance of DetailedFeatureCollection - * @throws IOException if the JSON string is invalid with respect to DetailedFeatureCollection - */ - public static DetailedFeatureCollection fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, DetailedFeatureCollection.class); - } - - /** - * Convert an instance of DetailedFeatureCollection to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/DetailedProperties.java b/src/main/java/io/openepi/flood/model/DetailedProperties.java deleted file mode 100644 index 4c404ff..0000000 --- a/src/main/java/io/openepi/flood/model/DetailedProperties.java +++ /dev/null @@ -1,496 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * DetailedProperties - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class DetailedProperties { - public static final String SERIALIZED_NAME_ISSUED_ON = "issued_on"; - @SerializedName(SERIALIZED_NAME_ISSUED_ON) - private LocalDate issuedOn; - - public static final String SERIALIZED_NAME_VALID_FOR = "valid_for"; - @SerializedName(SERIALIZED_NAME_VALID_FOR) - private LocalDate validFor; - - public static final String SERIALIZED_NAME_STEP = "step"; - @SerializedName(SERIALIZED_NAME_STEP) - private Integer step; - - public static final String SERIALIZED_NAME_P_ABOVE2Y = "p_above_2y"; - @SerializedName(SERIALIZED_NAME_P_ABOVE2Y) - private BigDecimal pAbove2y; - - public static final String SERIALIZED_NAME_P_ABOVE5Y = "p_above_5y"; - @SerializedName(SERIALIZED_NAME_P_ABOVE5Y) - private BigDecimal pAbove5y; - - public static final String SERIALIZED_NAME_P_ABOVE20Y = "p_above_20y"; - @SerializedName(SERIALIZED_NAME_P_ABOVE20Y) - private BigDecimal pAbove20y; - - public static final String SERIALIZED_NAME_MIN_DIS = "min_dis"; - @SerializedName(SERIALIZED_NAME_MIN_DIS) - private BigDecimal minDis; - - public static final String SERIALIZED_NAME_Q1_DIS = "q1_dis"; - @SerializedName(SERIALIZED_NAME_Q1_DIS) - private BigDecimal q1Dis; - - public static final String SERIALIZED_NAME_MEDIAN_DIS = "median_dis"; - @SerializedName(SERIALIZED_NAME_MEDIAN_DIS) - private BigDecimal medianDis; - - public static final String SERIALIZED_NAME_Q3_DIS = "q3_dis"; - @SerializedName(SERIALIZED_NAME_Q3_DIS) - private BigDecimal q3Dis; - - public static final String SERIALIZED_NAME_MAX_DIS = "max_dis"; - @SerializedName(SERIALIZED_NAME_MAX_DIS) - private BigDecimal maxDis; - - public DetailedProperties() { - } - - public DetailedProperties issuedOn(LocalDate issuedOn) { - this.issuedOn = issuedOn; - return this; - } - - /** - * The date the summary forecast was issued on. The GloFAS hydrological model is run every day at 00:00 UTC. - * @return issuedOn - */ - @javax.annotation.Nonnull - public LocalDate getIssuedOn() { - return issuedOn; - } - - public void setIssuedOn(LocalDate issuedOn) { - this.issuedOn = issuedOn; - } - - - public DetailedProperties validFor(LocalDate validFor) { - this.validFor = validFor; - return this; - } - - /** - * The date of the 24-hour forecast period for the flood. The forecast uses the discharge expected between 00:00 UTC and 23:59 UTC of that day. - * @return validFor - */ - @javax.annotation.Nonnull - public LocalDate getValidFor() { - return validFor; - } - - public void setValidFor(LocalDate validFor) { - this.validFor = validFor; - } - - - public DetailedProperties step(Integer step) { - this.step = step; - return this; - } - - /** - * The time step number of the forecast data. - * minimum: 1 - * maximum: 30 - * @return step - */ - @javax.annotation.Nonnull - public Integer getStep() { - return step; - } - - public void setStep(Integer step) { - this.step = step; - } - - - public DetailedProperties pAbove2y(BigDecimal pAbove2y) { - this.pAbove2y = pAbove2y; - return this; - } - - /** - * Probability of exceedance over the 2-year return period threshold. - * minimum: 0.0 - * maximum: 1.0 - * @return pAbove2y - */ - @javax.annotation.Nonnull - public BigDecimal getpAbove2y() { - return pAbove2y; - } - - public void setpAbove2y(BigDecimal pAbove2y) { - this.pAbove2y = pAbove2y; - } - - - public DetailedProperties pAbove5y(BigDecimal pAbove5y) { - this.pAbove5y = pAbove5y; - return this; - } - - /** - * Probability of exceedance over the 5-year return period threshold. - * minimum: 0.0 - * maximum: 1.0 - * @return pAbove5y - */ - @javax.annotation.Nonnull - public BigDecimal getpAbove5y() { - return pAbove5y; - } - - public void setpAbove5y(BigDecimal pAbove5y) { - this.pAbove5y = pAbove5y; - } - - - public DetailedProperties pAbove20y(BigDecimal pAbove20y) { - this.pAbove20y = pAbove20y; - return this; - } - - /** - * Probability of exceedance over the 20-year return period threshold. - * minimum: 0.0 - * maximum: 1.0 - * @return pAbove20y - */ - @javax.annotation.Nonnull - public BigDecimal getpAbove20y() { - return pAbove20y; - } - - public void setpAbove20y(BigDecimal pAbove20y) { - this.pAbove20y = pAbove20y; - } - - - public DetailedProperties minDis(BigDecimal minDis) { - this.minDis = minDis; - return this; - } - - /** - * Minimum forecasted discharge in m^3/s. - * minimum: 0.0 - * @return minDis - */ - @javax.annotation.Nonnull - public BigDecimal getMinDis() { - return minDis; - } - - public void setMinDis(BigDecimal minDis) { - this.minDis = minDis; - } - - - public DetailedProperties q1Dis(BigDecimal q1Dis) { - this.q1Dis = q1Dis; - return this; - } - - /** - * First quartile of forecasted discharge in m^3/s. - * minimum: 0.0 - * @return q1Dis - */ - @javax.annotation.Nonnull - public BigDecimal getQ1Dis() { - return q1Dis; - } - - public void setQ1Dis(BigDecimal q1Dis) { - this.q1Dis = q1Dis; - } - - - public DetailedProperties medianDis(BigDecimal medianDis) { - this.medianDis = medianDis; - return this; - } - - /** - * Median forecasted discharge in m^3/s. - * minimum: 0.0 - * @return medianDis - */ - @javax.annotation.Nonnull - public BigDecimal getMedianDis() { - return medianDis; - } - - public void setMedianDis(BigDecimal medianDis) { - this.medianDis = medianDis; - } - - - public DetailedProperties q3Dis(BigDecimal q3Dis) { - this.q3Dis = q3Dis; - return this; - } - - /** - * Third quartile of forecasted discharge in m^3/s. - * minimum: 0.0 - * @return q3Dis - */ - @javax.annotation.Nonnull - public BigDecimal getQ3Dis() { - return q3Dis; - } - - public void setQ3Dis(BigDecimal q3Dis) { - this.q3Dis = q3Dis; - } - - - public DetailedProperties maxDis(BigDecimal maxDis) { - this.maxDis = maxDis; - return this; - } - - /** - * Maximum forecasted discharge in m^3/s. - * minimum: 0.0 - * @return maxDis - */ - @javax.annotation.Nonnull - public BigDecimal getMaxDis() { - return maxDis; - } - - public void setMaxDis(BigDecimal maxDis) { - this.maxDis = maxDis; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - DetailedProperties detailedProperties = (DetailedProperties) o; - return Objects.equals(this.issuedOn, detailedProperties.issuedOn) && - Objects.equals(this.validFor, detailedProperties.validFor) && - Objects.equals(this.step, detailedProperties.step) && - Objects.equals(this.pAbove2y, detailedProperties.pAbove2y) && - Objects.equals(this.pAbove5y, detailedProperties.pAbove5y) && - Objects.equals(this.pAbove20y, detailedProperties.pAbove20y) && - Objects.equals(this.minDis, detailedProperties.minDis) && - Objects.equals(this.q1Dis, detailedProperties.q1Dis) && - Objects.equals(this.medianDis, detailedProperties.medianDis) && - Objects.equals(this.q3Dis, detailedProperties.q3Dis) && - Objects.equals(this.maxDis, detailedProperties.maxDis); - } - - @Override - public int hashCode() { - return Objects.hash(issuedOn, validFor, step, pAbove2y, pAbove5y, pAbove20y, minDis, q1Dis, medianDis, q3Dis, maxDis); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class DetailedProperties {\n"); - sb.append(" issuedOn: ").append(toIndentedString(issuedOn)).append("\n"); - sb.append(" validFor: ").append(toIndentedString(validFor)).append("\n"); - sb.append(" step: ").append(toIndentedString(step)).append("\n"); - sb.append(" pAbove2y: ").append(toIndentedString(pAbove2y)).append("\n"); - sb.append(" pAbove5y: ").append(toIndentedString(pAbove5y)).append("\n"); - sb.append(" pAbove20y: ").append(toIndentedString(pAbove20y)).append("\n"); - sb.append(" minDis: ").append(toIndentedString(minDis)).append("\n"); - sb.append(" q1Dis: ").append(toIndentedString(q1Dis)).append("\n"); - sb.append(" medianDis: ").append(toIndentedString(medianDis)).append("\n"); - sb.append(" q3Dis: ").append(toIndentedString(q3Dis)).append("\n"); - sb.append(" maxDis: ").append(toIndentedString(maxDis)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("issued_on"); - openapiFields.add("valid_for"); - openapiFields.add("step"); - openapiFields.add("p_above_2y"); - openapiFields.add("p_above_5y"); - openapiFields.add("p_above_20y"); - openapiFields.add("min_dis"); - openapiFields.add("q1_dis"); - openapiFields.add("median_dis"); - openapiFields.add("q3_dis"); - openapiFields.add("max_dis"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("issued_on"); - openapiRequiredFields.add("valid_for"); - openapiRequiredFields.add("step"); - openapiRequiredFields.add("p_above_2y"); - openapiRequiredFields.add("p_above_5y"); - openapiRequiredFields.add("p_above_20y"); - openapiRequiredFields.add("min_dis"); - openapiRequiredFields.add("q1_dis"); - openapiRequiredFields.add("median_dis"); - openapiRequiredFields.add("q3_dis"); - openapiRequiredFields.add("max_dis"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to DetailedProperties - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!DetailedProperties.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in DetailedProperties is not found in the empty JSON string", DetailedProperties.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!DetailedProperties.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `DetailedProperties` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : DetailedProperties.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!DetailedProperties.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'DetailedProperties' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(DetailedProperties.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, DetailedProperties value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public DetailedProperties read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of DetailedProperties given an JSON string - * - * @param jsonString JSON string - * @return An instance of DetailedProperties - * @throws IOException if the JSON string is invalid with respect to DetailedProperties - */ - public static DetailedProperties fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, DetailedProperties.class); - } - - /** - * Convert an instance of DetailedProperties to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/DetailedResponseModel.java b/src/main/java/io/openepi/flood/model/DetailedResponseModel.java deleted file mode 100644 index a511c09..0000000 --- a/src/main/java/io/openepi/flood/model/DetailedResponseModel.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.flood.model.DetailedFeatureCollection; -import org.openapitools.jackson.nullable.JsonNullable; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * DetailedResponseModel - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class DetailedResponseModel { - public static final String SERIALIZED_NAME_QUERIED_LOCATION = "queried_location"; - @SerializedName(SERIALIZED_NAME_QUERIED_LOCATION) - private DetailedFeatureCollection queriedLocation; - - public static final String SERIALIZED_NAME_NEIGHBORING_LOCATION = "neighboring_location"; - @SerializedName(SERIALIZED_NAME_NEIGHBORING_LOCATION) - private DetailedFeatureCollection neighboringLocation; - - public DetailedResponseModel() { - } - - public DetailedResponseModel queriedLocation(DetailedFeatureCollection queriedLocation) { - this.queriedLocation = queriedLocation; - return this; - } - - /** - * A feature collection representing the queried location's detailed forecast data. - * @return queriedLocation - */ - @javax.annotation.Nonnull - public DetailedFeatureCollection getQueriedLocation() { - return queriedLocation; - } - - public void setQueriedLocation(DetailedFeatureCollection queriedLocation) { - this.queriedLocation = queriedLocation; - } - - - public DetailedResponseModel neighboringLocation(DetailedFeatureCollection neighboringLocation) { - this.neighboringLocation = neighboringLocation; - return this; - } - - /** - * Get neighboringLocation - * @return neighboringLocation - */ - @javax.annotation.Nullable - public DetailedFeatureCollection getNeighboringLocation() { - return neighboringLocation; - } - - public void setNeighboringLocation(DetailedFeatureCollection neighboringLocation) { - this.neighboringLocation = neighboringLocation; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - DetailedResponseModel detailedResponseModel = (DetailedResponseModel) o; - return Objects.equals(this.queriedLocation, detailedResponseModel.queriedLocation) && - Objects.equals(this.neighboringLocation, detailedResponseModel.neighboringLocation); - } - - private static boolean equalsNullable(JsonNullable a, JsonNullable b) { - return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); - } - - @Override - public int hashCode() { - return Objects.hash(queriedLocation, neighboringLocation); - } - - private static int hashCodeNullable(JsonNullable a) { - if (a == null) { - return 1; - } - return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class DetailedResponseModel {\n"); - sb.append(" queriedLocation: ").append(toIndentedString(queriedLocation)).append("\n"); - sb.append(" neighboringLocation: ").append(toIndentedString(neighboringLocation)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("queried_location"); - openapiFields.add("neighboring_location"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("queried_location"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to DetailedResponseModel - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!DetailedResponseModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in DetailedResponseModel is not found in the empty JSON string", DetailedResponseModel.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!DetailedResponseModel.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `DetailedResponseModel` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : DetailedResponseModel.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `queried_location` - DetailedFeatureCollection.validateJsonElement(jsonObj.get("queried_location")); - // validate the optional field `neighboring_location` - if (jsonObj.get("neighboring_location") != null && !jsonObj.get("neighboring_location").isJsonNull()) { - DetailedFeatureCollection.validateJsonElement(jsonObj.get("neighboring_location")); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!DetailedResponseModel.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'DetailedResponseModel' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(DetailedResponseModel.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, DetailedResponseModel value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public DetailedResponseModel read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of DetailedResponseModel given an JSON string - * - * @param jsonString JSON string - * @return An instance of DetailedResponseModel - * @throws IOException if the JSON string is invalid with respect to DetailedResponseModel - */ - public static DetailedResponseModel fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, DetailedResponseModel.class); - } - - /** - * Convert an instance of DetailedResponseModel to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/Geometry.java b/src/main/java/io/openepi/flood/model/Geometry.java deleted file mode 100644 index d9da98c..0000000 --- a/src/main/java/io/openepi/flood/model/Geometry.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * Geometry - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class Geometry { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private String type; - - public static final String SERIALIZED_NAME_COORDINATES = "coordinates"; - @SerializedName(SERIALIZED_NAME_COORDINATES) - private List>> coordinates = new ArrayList<>(); - - public Geometry() { - } - - public Geometry type(String type) { - this.type = type; - return this; - } - - /** - * The nature of the geometry type, which is 'Polygon' for this model. - * @return type - */ - @javax.annotation.Nonnull - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - - public Geometry coordinates(List>> coordinates) { - this.coordinates = coordinates; - return this; - } - - public Geometry addCoordinatesItem(List> coordinatesItem) { - if (this.coordinates == null) { - this.coordinates = new ArrayList<>(); - } - this.coordinates.add(coordinatesItem); - return this; - } - - /** - * Coordinates for the Polygon geometry type, defined according to a 0.05-degree resolution grid. Each polygon's coordinates are provided as an array of points, with each point specifying its longitude and latitude in decimal degrees. The array forms a closed linear ring that defines the polygon's boundary, with the first and last point being identical to close the ring. - * @return coordinates - */ - @javax.annotation.Nonnull - public List>> getCoordinates() { - return coordinates; - } - - public void setCoordinates(List>> coordinates) { - this.coordinates = coordinates; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Geometry geometry = (Geometry) o; - return Objects.equals(this.type, geometry.type) && - Objects.equals(this.coordinates, geometry.coordinates); - } - - @Override - public int hashCode() { - return Objects.hash(type, coordinates); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Geometry {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" coordinates: ").append(toIndentedString(coordinates)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("coordinates"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("coordinates"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to Geometry - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!Geometry.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in Geometry is not found in the empty JSON string", Geometry.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!Geometry.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Geometry` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : Geometry.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (!jsonObj.get("type").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); - } - // ensure the required json array is present - if (jsonObj.get("coordinates") == null) { - throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); - } else if (!jsonObj.get("coordinates").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `coordinates` to be an array in the JSON string but got `%s`", jsonObj.get("coordinates").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!Geometry.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'Geometry' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(Geometry.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, Geometry value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public Geometry read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of Geometry given an JSON string - * - * @param jsonString JSON string - * @return An instance of Geometry - * @throws IOException if the JSON string is invalid with respect to Geometry - */ - public static Geometry fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, Geometry.class); - } - - /** - * Convert an instance of Geometry to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/HTTPValidationError.java b/src/main/java/io/openepi/flood/model/HTTPValidationError.java deleted file mode 100644 index d6289d6..0000000 --- a/src/main/java/io/openepi/flood/model/HTTPValidationError.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.flood.model.ValidationError; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * HTTPValidationError - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class HTTPValidationError { - public static final String SERIALIZED_NAME_DETAIL = "detail"; - @SerializedName(SERIALIZED_NAME_DETAIL) - private List detail = new ArrayList<>(); - - public HTTPValidationError() { - } - - public HTTPValidationError detail(List detail) { - this.detail = detail; - return this; - } - - public HTTPValidationError addDetailItem(ValidationError detailItem) { - if (this.detail == null) { - this.detail = new ArrayList<>(); - } - this.detail.add(detailItem); - return this; - } - - /** - * Get detail - * @return detail - */ - @javax.annotation.Nullable - public List getDetail() { - return detail; - } - - public void setDetail(List detail) { - this.detail = detail; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - HTTPValidationError htTPValidationError = (HTTPValidationError) o; - return Objects.equals(this.detail, htTPValidationError.detail); - } - - @Override - public int hashCode() { - return Objects.hash(detail); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class HTTPValidationError {\n"); - sb.append(" detail: ").append(toIndentedString(detail)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("detail"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to HTTPValidationError - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!HTTPValidationError.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in HTTPValidationError is not found in the empty JSON string", HTTPValidationError.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!HTTPValidationError.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `HTTPValidationError` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("detail") != null && !jsonObj.get("detail").isJsonNull()) { - JsonArray jsonArraydetail = jsonObj.getAsJsonArray("detail"); - if (jsonArraydetail != null) { - // ensure the json data is an array - if (!jsonObj.get("detail").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `detail` to be an array in the JSON string but got `%s`", jsonObj.get("detail").toString())); - } - - // validate the optional field `detail` (array) - for (int i = 0; i < jsonArraydetail.size(); i++) { - ValidationError.validateJsonElement(jsonArraydetail.get(i)); - }; - } - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!HTTPValidationError.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'HTTPValidationError' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(HTTPValidationError.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, HTTPValidationError value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public HTTPValidationError read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of HTTPValidationError given an JSON string - * - * @param jsonString JSON string - * @return An instance of HTTPValidationError - * @throws IOException if the JSON string is invalid with respect to HTTPValidationError - */ - public static HTTPValidationError fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, HTTPValidationError.class); - } - - /** - * Convert an instance of HTTPValidationError to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/IntensityEnum.java b/src/main/java/io/openepi/flood/model/IntensityEnum.java deleted file mode 100644 index cea0087..0000000 --- a/src/main/java/io/openepi/flood/model/IntensityEnum.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets IntensityEnum - */ -@JsonAdapter(IntensityEnum.Adapter.class) -public enum IntensityEnum { - - P("P"), - - R("R"), - - Y("Y"), - - G("G"); - - private String value; - - IntensityEnum(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static IntensityEnum fromValue(String value) { - for (IntensityEnum b : IntensityEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final IntensityEnum enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public IntensityEnum read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return IntensityEnum.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - IntensityEnum.fromValue(value); - } -} - diff --git a/src/main/java/io/openepi/flood/model/PeakTimingEnum.java b/src/main/java/io/openepi/flood/model/PeakTimingEnum.java deleted file mode 100644 index c263d1c..0000000 --- a/src/main/java/io/openepi/flood/model/PeakTimingEnum.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets PeakTimingEnum - */ -@JsonAdapter(PeakTimingEnum.Adapter.class) -public enum PeakTimingEnum { - - BB("BB"), - - GC("GC"), - - GB("GB"); - - private String value; - - PeakTimingEnum(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static PeakTimingEnum fromValue(String value) { - for (PeakTimingEnum b : PeakTimingEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final PeakTimingEnum enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public PeakTimingEnum read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return PeakTimingEnum.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - PeakTimingEnum.fromValue(value); - } -} - diff --git a/src/main/java/io/openepi/flood/model/SummaryFeature.java b/src/main/java/io/openepi/flood/model/SummaryFeature.java deleted file mode 100644 index 4a9bd5a..0000000 --- a/src/main/java/io/openepi/flood/model/SummaryFeature.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.flood.model.Geometry; -import io.openepi.flood.model.SummaryProperties; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * SummaryFeature - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SummaryFeature { - public static final String SERIALIZED_NAME_ID = "id"; - @SerializedName(SERIALIZED_NAME_ID) - private String id; - - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_GEOMETRY = "geometry"; - @SerializedName(SERIALIZED_NAME_GEOMETRY) - private Geometry geometry; - - public static final String SERIALIZED_NAME_PROPERTIES = "properties"; - @SerializedName(SERIALIZED_NAME_PROPERTIES) - private SummaryProperties properties; - - public SummaryFeature() { - } - - public SummaryFeature id(String id) { - this.id = id; - return this; - } - - /** - * A unique identifier for the feature. - * @return id - */ - @javax.annotation.Nonnull - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - - public SummaryFeature type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public SummaryFeature geometry(Geometry geometry) { - this.geometry = geometry; - return this; - } - - /** - * The geometric details of the feature, including its type and coordinates. - * @return geometry - */ - @javax.annotation.Nonnull - public Geometry getGeometry() { - return geometry; - } - - public void setGeometry(Geometry geometry) { - this.geometry = geometry; - } - - - public SummaryFeature properties(SummaryProperties properties) { - this.properties = properties; - return this; - } - - /** - * Specific properties of the summary forecast, including various attributes like tendency, peak step, and intensity. - * @return properties - */ - @javax.annotation.Nonnull - public SummaryProperties getProperties() { - return properties; - } - - public void setProperties(SummaryProperties properties) { - this.properties = properties; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SummaryFeature summaryFeature = (SummaryFeature) o; - return Objects.equals(this.id, summaryFeature.id) && - Objects.equals(this.type, summaryFeature.type) && - Objects.equals(this.geometry, summaryFeature.geometry) && - Objects.equals(this.properties, summaryFeature.properties); - } - - @Override - public int hashCode() { - return Objects.hash(id, type, geometry, properties); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SummaryFeature {\n"); - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" geometry: ").append(toIndentedString(geometry)).append("\n"); - sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("id"); - openapiFields.add("type"); - openapiFields.add("geometry"); - openapiFields.add("properties"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("id"); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("geometry"); - openapiRequiredFields.add("properties"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SummaryFeature - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SummaryFeature.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SummaryFeature is not found in the empty JSON string", SummaryFeature.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SummaryFeature.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SummaryFeature` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SummaryFeature.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (!jsonObj.get("id").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("id").toString())); - } - // validate the required field `geometry` - Geometry.validateJsonElement(jsonObj.get("geometry")); - // validate the required field `properties` - SummaryProperties.validateJsonElement(jsonObj.get("properties")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SummaryFeature.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SummaryFeature' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SummaryFeature.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SummaryFeature value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SummaryFeature read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SummaryFeature given an JSON string - * - * @param jsonString JSON string - * @return An instance of SummaryFeature - * @throws IOException if the JSON string is invalid with respect to SummaryFeature - */ - public static SummaryFeature fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SummaryFeature.class); - } - - /** - * Convert an instance of SummaryFeature to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/SummaryFeatureCollection.java b/src/main/java/io/openepi/flood/model/SummaryFeatureCollection.java deleted file mode 100644 index 94acb75..0000000 --- a/src/main/java/io/openepi/flood/model/SummaryFeatureCollection.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.flood.model.SummaryFeature; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * SummaryFeatureCollection - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SummaryFeatureCollection { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_FEATURES = "features"; - @SerializedName(SERIALIZED_NAME_FEATURES) - private List features = new ArrayList<>(); - - public SummaryFeatureCollection() { - } - - public SummaryFeatureCollection type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public SummaryFeatureCollection features(List features) { - this.features = features; - return this; - } - - public SummaryFeatureCollection addFeaturesItem(SummaryFeature featuresItem) { - if (this.features == null) { - this.features = new ArrayList<>(); - } - this.features.add(featuresItem); - return this; - } - - /** - * A collection of summary forecasts, each containing specific forecast information for a queried location. - * @return features - */ - @javax.annotation.Nonnull - public List getFeatures() { - return features; - } - - public void setFeatures(List features) { - this.features = features; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SummaryFeatureCollection summaryFeatureCollection = (SummaryFeatureCollection) o; - return Objects.equals(this.type, summaryFeatureCollection.type) && - Objects.equals(this.features, summaryFeatureCollection.features); - } - - @Override - public int hashCode() { - return Objects.hash(type, features); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SummaryFeatureCollection {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" features: ").append(toIndentedString(features)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("features"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("features"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SummaryFeatureCollection - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SummaryFeatureCollection.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SummaryFeatureCollection is not found in the empty JSON string", SummaryFeatureCollection.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SummaryFeatureCollection.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SummaryFeatureCollection` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SummaryFeatureCollection.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the json data is an array - if (!jsonObj.get("features").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `features` to be an array in the JSON string but got `%s`", jsonObj.get("features").toString())); - } - - JsonArray jsonArrayfeatures = jsonObj.getAsJsonArray("features"); - // validate the required field `features` (array) - for (int i = 0; i < jsonArrayfeatures.size(); i++) { - SummaryFeature.validateJsonElement(jsonArrayfeatures.get(i)); - }; - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SummaryFeatureCollection.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SummaryFeatureCollection' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SummaryFeatureCollection.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SummaryFeatureCollection value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SummaryFeatureCollection read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SummaryFeatureCollection given an JSON string - * - * @param jsonString JSON string - * @return An instance of SummaryFeatureCollection - * @throws IOException if the JSON string is invalid with respect to SummaryFeatureCollection - */ - public static SummaryFeatureCollection fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SummaryFeatureCollection.class); - } - - /** - * Convert an instance of SummaryFeatureCollection to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/SummaryProperties.java b/src/main/java/io/openepi/flood/model/SummaryProperties.java deleted file mode 100644 index 972408b..0000000 --- a/src/main/java/io/openepi/flood/model/SummaryProperties.java +++ /dev/null @@ -1,586 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.math.BigDecimal; -import java.time.LocalDate; -import java.util.Arrays; -import io.openepi.flood.model.IntensityEnum; -import io.openepi.flood.model.PeakTimingEnum; -import io.openepi.flood.model.TendencyEnum; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * SummaryProperties - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SummaryProperties { - public static final String SERIALIZED_NAME_ISSUED_ON = "issued_on"; - @SerializedName(SERIALIZED_NAME_ISSUED_ON) - private LocalDate issuedOn; - - public static final String SERIALIZED_NAME_PEAK_STEP = "peak_step"; - @SerializedName(SERIALIZED_NAME_PEAK_STEP) - private Integer peakStep; - - public static final String SERIALIZED_NAME_PEAK_DAY = "peak_day"; - @SerializedName(SERIALIZED_NAME_PEAK_DAY) - private LocalDate peakDay; - - public static final String SERIALIZED_NAME_PEAK_TIMING = "peak_timing"; - @SerializedName(SERIALIZED_NAME_PEAK_TIMING) - private PeakTimingEnum peakTiming; - - public static final String SERIALIZED_NAME_MAX_MEDIAN_DIS = "max_median_dis"; - @SerializedName(SERIALIZED_NAME_MAX_MEDIAN_DIS) - private BigDecimal maxMedianDis; - - public static final String SERIALIZED_NAME_MIN_MEDIAN_DIS = "min_median_dis"; - @SerializedName(SERIALIZED_NAME_MIN_MEDIAN_DIS) - private BigDecimal minMedianDis; - - public static final String SERIALIZED_NAME_CONTROL_DIS = "control_dis"; - @SerializedName(SERIALIZED_NAME_CONTROL_DIS) - private BigDecimal controlDis; - - public static final String SERIALIZED_NAME_MAX_MAX_DIS = "max_max_dis"; - @SerializedName(SERIALIZED_NAME_MAX_MAX_DIS) - private BigDecimal maxMaxDis; - - public static final String SERIALIZED_NAME_MIN_MIN_DIS = "min_min_dis"; - @SerializedName(SERIALIZED_NAME_MIN_MIN_DIS) - private BigDecimal minMinDis; - - public static final String SERIALIZED_NAME_TENDENCY = "tendency"; - @SerializedName(SERIALIZED_NAME_TENDENCY) - private TendencyEnum tendency; - - public static final String SERIALIZED_NAME_MAX_P_ABOVE20Y = "max_p_above_20y"; - @SerializedName(SERIALIZED_NAME_MAX_P_ABOVE20Y) - private BigDecimal maxPAbove20y; - - public static final String SERIALIZED_NAME_MAX_P_ABOVE5Y = "max_p_above_5y"; - @SerializedName(SERIALIZED_NAME_MAX_P_ABOVE5Y) - private BigDecimal maxPAbove5y; - - public static final String SERIALIZED_NAME_MAX_P_ABOVE2Y = "max_p_above_2y"; - @SerializedName(SERIALIZED_NAME_MAX_P_ABOVE2Y) - private BigDecimal maxPAbove2y; - - public static final String SERIALIZED_NAME_INTENSITY = "intensity"; - @SerializedName(SERIALIZED_NAME_INTENSITY) - private IntensityEnum intensity; - - public SummaryProperties() { - } - - public SummaryProperties issuedOn(LocalDate issuedOn) { - this.issuedOn = issuedOn; - return this; - } - - /** - * The date the summary forecast was issued on. The GloFAS hydrological model is run every day at 00:00 UTC. - * @return issuedOn - */ - @javax.annotation.Nonnull - public LocalDate getIssuedOn() { - return issuedOn; - } - - public void setIssuedOn(LocalDate issuedOn) { - this.issuedOn = issuedOn; - } - - - public SummaryProperties peakStep(Integer peakStep) { - this.peakStep = peakStep; - return this; - } - - /** - * The step number at which the peak occurs, ranging from 1 to 30. - * minimum: 1 - * maximum: 30 - * @return peakStep - */ - @javax.annotation.Nonnull - public Integer getPeakStep() { - return peakStep; - } - - public void setPeakStep(Integer peakStep) { - this.peakStep = peakStep; - } - - - public SummaryProperties peakDay(LocalDate peakDay) { - this.peakDay = peakDay; - return this; - } - - /** - * The date on which the flood peak is forecasted to occur, assuming UTC timezone. - * @return peakDay - */ - @javax.annotation.Nonnull - public LocalDate getPeakDay() { - return peakDay; - } - - public void setPeakDay(LocalDate peakDay) { - this.peakDay = peakDay; - } - - - public SummaryProperties peakTiming(PeakTimingEnum peakTiming) { - this.peakTiming = peakTiming; - return this; - } - - /** - * The timing of the flood peak indicated by border and grayed colors. BB: Black border, peak forecasted within days 1-3. GC: Grayed color, peak forecasted after day 10 with <30% probability of exceeding the 2-year return period threshold in first 10 days. GB: Gray border, floods of some severity in first 10 days and peak after day 3. - * @return peakTiming - */ - @javax.annotation.Nonnull - public PeakTimingEnum getPeakTiming() { - return peakTiming; - } - - public void setPeakTiming(PeakTimingEnum peakTiming) { - this.peakTiming = peakTiming; - } - - - public SummaryProperties maxMedianDis(BigDecimal maxMedianDis) { - this.maxMedianDis = maxMedianDis; - return this; - } - - /** - * The maximum of the median discharges over the forecast horizon in m^3/s. - * minimum: 0.0 - * @return maxMedianDis - */ - @javax.annotation.Nonnull - public BigDecimal getMaxMedianDis() { - return maxMedianDis; - } - - public void setMaxMedianDis(BigDecimal maxMedianDis) { - this.maxMedianDis = maxMedianDis; - } - - - public SummaryProperties minMedianDis(BigDecimal minMedianDis) { - this.minMedianDis = minMedianDis; - return this; - } - - /** - * The minimum of the median discharges over the forecast horizon in m^3/s. - * minimum: 0.0 - * @return minMedianDis - */ - @javax.annotation.Nonnull - public BigDecimal getMinMedianDis() { - return minMedianDis; - } - - public void setMinMedianDis(BigDecimal minMedianDis) { - this.minMedianDis = minMedianDis; - } - - - public SummaryProperties controlDis(BigDecimal controlDis) { - this.controlDis = controlDis; - return this; - } - - /** - * The control discharge in m^3/s. Currently taken to be the median discharge of the first day in forecasted. - * minimum: 0.0 - * @return controlDis - */ - @javax.annotation.Nonnull - public BigDecimal getControlDis() { - return controlDis; - } - - public void setControlDis(BigDecimal controlDis) { - this.controlDis = controlDis; - } - - - public SummaryProperties maxMaxDis(BigDecimal maxMaxDis) { - this.maxMaxDis = maxMaxDis; - return this; - } - - /** - * The maximum of the maximum discharges over the forecast horizon in m^3/s. - * minimum: 0.0 - * @return maxMaxDis - */ - @javax.annotation.Nonnull - public BigDecimal getMaxMaxDis() { - return maxMaxDis; - } - - public void setMaxMaxDis(BigDecimal maxMaxDis) { - this.maxMaxDis = maxMaxDis; - } - - - public SummaryProperties minMinDis(BigDecimal minMinDis) { - this.minMinDis = minMinDis; - return this; - } - - /** - * The minimum of the minimum discharges over the forecast horizon in m^3/s. - * minimum: 0.0 - * @return minMinDis - */ - @javax.annotation.Nonnull - public BigDecimal getMinMinDis() { - return minMinDis; - } - - public void setMinMinDis(BigDecimal minMinDis) { - this.minMinDis = minMinDis; - } - - - public SummaryProperties tendency(TendencyEnum tendency) { - this.tendency = tendency; - return this; - } - - /** - * The flood tendency (indicated by shape) according to the evolution of flood intensity signal over the forecast horizon. U: Upward triangle, increasing trend over the next 30-days with 30-day max median exceeding initial (control) discharge by >10%. D: Downward triangle, decreasing trend over the next 30-days with 30-day max median not exceeding initial discharge by >10% and min median is >=10% below initial discharge. C: Circle, stagnant flow with no significant trend detected. - * @return tendency - */ - @javax.annotation.Nonnull - public TendencyEnum getTendency() { - return tendency; - } - - public void setTendency(TendencyEnum tendency) { - this.tendency = tendency; - } - - - public SummaryProperties maxPAbove20y(BigDecimal maxPAbove20y) { - this.maxPAbove20y = maxPAbove20y; - return this; - } - - /** - * The maximum probability of exceeding the 20-year return period threshold over the forecast horizon. - * minimum: 0.0 - * maximum: 1.0 - * @return maxPAbove20y - */ - @javax.annotation.Nonnull - public BigDecimal getMaxPAbove20y() { - return maxPAbove20y; - } - - public void setMaxPAbove20y(BigDecimal maxPAbove20y) { - this.maxPAbove20y = maxPAbove20y; - } - - - public SummaryProperties maxPAbove5y(BigDecimal maxPAbove5y) { - this.maxPAbove5y = maxPAbove5y; - return this; - } - - /** - * The maximum probability of exceeding the 5-year return period threshold over the forecast horizon. - * minimum: 0.0 - * maximum: 1.0 - * @return maxPAbove5y - */ - @javax.annotation.Nonnull - public BigDecimal getMaxPAbove5y() { - return maxPAbove5y; - } - - public void setMaxPAbove5y(BigDecimal maxPAbove5y) { - this.maxPAbove5y = maxPAbove5y; - } - - - public SummaryProperties maxPAbove2y(BigDecimal maxPAbove2y) { - this.maxPAbove2y = maxPAbove2y; - return this; - } - - /** - * The maximum probability of exceeding the 2-year return period threshold over the forecast horizon. - * minimum: 0.0 - * maximum: 1.0 - * @return maxPAbove2y - */ - @javax.annotation.Nonnull - public BigDecimal getMaxPAbove2y() { - return maxPAbove2y; - } - - public void setMaxPAbove2y(BigDecimal maxPAbove2y) { - this.maxPAbove2y = maxPAbove2y; - } - - - public SummaryProperties intensity(IntensityEnum intensity) { - this.intensity = intensity; - return this; - } - - /** - * The flood intensity (indicated by color) relating to maximum return period threshold exceedance probabilities over the forecast horizon. P: Purple, maximum 20-year exceedance probability >=30%; R: Red, maximum for 20-year <30% and 5-year >=30%; Y: Yellow, maximum for 5-year <30% and 2-year >=30%; G: Gray, no flood signal (2-year <30%). - * @return intensity - */ - @javax.annotation.Nonnull - public IntensityEnum getIntensity() { - return intensity; - } - - public void setIntensity(IntensityEnum intensity) { - this.intensity = intensity; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SummaryProperties summaryProperties = (SummaryProperties) o; - return Objects.equals(this.issuedOn, summaryProperties.issuedOn) && - Objects.equals(this.peakStep, summaryProperties.peakStep) && - Objects.equals(this.peakDay, summaryProperties.peakDay) && - Objects.equals(this.peakTiming, summaryProperties.peakTiming) && - Objects.equals(this.maxMedianDis, summaryProperties.maxMedianDis) && - Objects.equals(this.minMedianDis, summaryProperties.minMedianDis) && - Objects.equals(this.controlDis, summaryProperties.controlDis) && - Objects.equals(this.maxMaxDis, summaryProperties.maxMaxDis) && - Objects.equals(this.minMinDis, summaryProperties.minMinDis) && - Objects.equals(this.tendency, summaryProperties.tendency) && - Objects.equals(this.maxPAbove20y, summaryProperties.maxPAbove20y) && - Objects.equals(this.maxPAbove5y, summaryProperties.maxPAbove5y) && - Objects.equals(this.maxPAbove2y, summaryProperties.maxPAbove2y) && - Objects.equals(this.intensity, summaryProperties.intensity); - } - - @Override - public int hashCode() { - return Objects.hash(issuedOn, peakStep, peakDay, peakTiming, maxMedianDis, minMedianDis, controlDis, maxMaxDis, minMinDis, tendency, maxPAbove20y, maxPAbove5y, maxPAbove2y, intensity); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SummaryProperties {\n"); - sb.append(" issuedOn: ").append(toIndentedString(issuedOn)).append("\n"); - sb.append(" peakStep: ").append(toIndentedString(peakStep)).append("\n"); - sb.append(" peakDay: ").append(toIndentedString(peakDay)).append("\n"); - sb.append(" peakTiming: ").append(toIndentedString(peakTiming)).append("\n"); - sb.append(" maxMedianDis: ").append(toIndentedString(maxMedianDis)).append("\n"); - sb.append(" minMedianDis: ").append(toIndentedString(minMedianDis)).append("\n"); - sb.append(" controlDis: ").append(toIndentedString(controlDis)).append("\n"); - sb.append(" maxMaxDis: ").append(toIndentedString(maxMaxDis)).append("\n"); - sb.append(" minMinDis: ").append(toIndentedString(minMinDis)).append("\n"); - sb.append(" tendency: ").append(toIndentedString(tendency)).append("\n"); - sb.append(" maxPAbove20y: ").append(toIndentedString(maxPAbove20y)).append("\n"); - sb.append(" maxPAbove5y: ").append(toIndentedString(maxPAbove5y)).append("\n"); - sb.append(" maxPAbove2y: ").append(toIndentedString(maxPAbove2y)).append("\n"); - sb.append(" intensity: ").append(toIndentedString(intensity)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("issued_on"); - openapiFields.add("peak_step"); - openapiFields.add("peak_day"); - openapiFields.add("peak_timing"); - openapiFields.add("max_median_dis"); - openapiFields.add("min_median_dis"); - openapiFields.add("control_dis"); - openapiFields.add("max_max_dis"); - openapiFields.add("min_min_dis"); - openapiFields.add("tendency"); - openapiFields.add("max_p_above_20y"); - openapiFields.add("max_p_above_5y"); - openapiFields.add("max_p_above_2y"); - openapiFields.add("intensity"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("issued_on"); - openapiRequiredFields.add("peak_step"); - openapiRequiredFields.add("peak_day"); - openapiRequiredFields.add("peak_timing"); - openapiRequiredFields.add("max_median_dis"); - openapiRequiredFields.add("min_median_dis"); - openapiRequiredFields.add("control_dis"); - openapiRequiredFields.add("max_max_dis"); - openapiRequiredFields.add("min_min_dis"); - openapiRequiredFields.add("tendency"); - openapiRequiredFields.add("max_p_above_20y"); - openapiRequiredFields.add("max_p_above_5y"); - openapiRequiredFields.add("max_p_above_2y"); - openapiRequiredFields.add("intensity"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SummaryProperties - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SummaryProperties.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SummaryProperties is not found in the empty JSON string", SummaryProperties.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SummaryProperties.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SummaryProperties` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SummaryProperties.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `peak_timing` - PeakTimingEnum.validateJsonElement(jsonObj.get("peak_timing")); - // validate the required field `tendency` - TendencyEnum.validateJsonElement(jsonObj.get("tendency")); - // validate the required field `intensity` - IntensityEnum.validateJsonElement(jsonObj.get("intensity")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SummaryProperties.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SummaryProperties' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SummaryProperties.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SummaryProperties value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SummaryProperties read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SummaryProperties given an JSON string - * - * @param jsonString JSON string - * @return An instance of SummaryProperties - * @throws IOException if the JSON string is invalid with respect to SummaryProperties - */ - public static SummaryProperties fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SummaryProperties.class); - } - - /** - * Convert an instance of SummaryProperties to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/SummaryResponseModel.java b/src/main/java/io/openepi/flood/model/SummaryResponseModel.java deleted file mode 100644 index be5639f..0000000 --- a/src/main/java/io/openepi/flood/model/SummaryResponseModel.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.flood.model.SummaryFeatureCollection; -import org.openapitools.jackson.nullable.JsonNullable; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * SummaryResponseModel - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SummaryResponseModel { - public static final String SERIALIZED_NAME_QUERIED_LOCATION = "queried_location"; - @SerializedName(SERIALIZED_NAME_QUERIED_LOCATION) - private SummaryFeatureCollection queriedLocation; - - public static final String SERIALIZED_NAME_NEIGHBORING_LOCATION = "neighboring_location"; - @SerializedName(SERIALIZED_NAME_NEIGHBORING_LOCATION) - private SummaryFeatureCollection neighboringLocation; - - public SummaryResponseModel() { - } - - public SummaryResponseModel queriedLocation(SummaryFeatureCollection queriedLocation) { - this.queriedLocation = queriedLocation; - return this; - } - - /** - * A feature collection representing the queried location's summary forecast data. - * @return queriedLocation - */ - @javax.annotation.Nonnull - public SummaryFeatureCollection getQueriedLocation() { - return queriedLocation; - } - - public void setQueriedLocation(SummaryFeatureCollection queriedLocation) { - this.queriedLocation = queriedLocation; - } - - - public SummaryResponseModel neighboringLocation(SummaryFeatureCollection neighboringLocation) { - this.neighboringLocation = neighboringLocation; - return this; - } - - /** - * Get neighboringLocation - * @return neighboringLocation - */ - @javax.annotation.Nullable - public SummaryFeatureCollection getNeighboringLocation() { - return neighboringLocation; - } - - public void setNeighboringLocation(SummaryFeatureCollection neighboringLocation) { - this.neighboringLocation = neighboringLocation; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SummaryResponseModel summaryResponseModel = (SummaryResponseModel) o; - return Objects.equals(this.queriedLocation, summaryResponseModel.queriedLocation) && - Objects.equals(this.neighboringLocation, summaryResponseModel.neighboringLocation); - } - - private static boolean equalsNullable(JsonNullable a, JsonNullable b) { - return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); - } - - @Override - public int hashCode() { - return Objects.hash(queriedLocation, neighboringLocation); - } - - private static int hashCodeNullable(JsonNullable a) { - if (a == null) { - return 1; - } - return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SummaryResponseModel {\n"); - sb.append(" queriedLocation: ").append(toIndentedString(queriedLocation)).append("\n"); - sb.append(" neighboringLocation: ").append(toIndentedString(neighboringLocation)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("queried_location"); - openapiFields.add("neighboring_location"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("queried_location"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SummaryResponseModel - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SummaryResponseModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SummaryResponseModel is not found in the empty JSON string", SummaryResponseModel.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SummaryResponseModel.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SummaryResponseModel` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SummaryResponseModel.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `queried_location` - SummaryFeatureCollection.validateJsonElement(jsonObj.get("queried_location")); - // validate the optional field `neighboring_location` - if (jsonObj.get("neighboring_location") != null && !jsonObj.get("neighboring_location").isJsonNull()) { - SummaryFeatureCollection.validateJsonElement(jsonObj.get("neighboring_location")); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SummaryResponseModel.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SummaryResponseModel' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SummaryResponseModel.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SummaryResponseModel value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SummaryResponseModel read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SummaryResponseModel given an JSON string - * - * @param jsonString JSON string - * @return An instance of SummaryResponseModel - * @throws IOException if the JSON string is invalid with respect to SummaryResponseModel - */ - public static SummaryResponseModel fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SummaryResponseModel.class); - } - - /** - * Convert an instance of SummaryResponseModel to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/TendencyEnum.java b/src/main/java/io/openepi/flood/model/TendencyEnum.java deleted file mode 100644 index 3507fbb..0000000 --- a/src/main/java/io/openepi/flood/model/TendencyEnum.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets TendencyEnum - */ -@JsonAdapter(TendencyEnum.Adapter.class) -public enum TendencyEnum { - - U("U"), - - D("D"), - - C("C"); - - private String value; - - TendencyEnum(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static TendencyEnum fromValue(String value) { - for (TendencyEnum b : TendencyEnum.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final TendencyEnum enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public TendencyEnum read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return TendencyEnum.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - TendencyEnum.fromValue(value); - } -} - diff --git a/src/main/java/io/openepi/flood/model/ThresholdFeature.java b/src/main/java/io/openepi/flood/model/ThresholdFeature.java deleted file mode 100644 index a8644f9..0000000 --- a/src/main/java/io/openepi/flood/model/ThresholdFeature.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.flood.model.Geometry; -import io.openepi.flood.model.ThresholdProperties; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * ThresholdFeature - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class ThresholdFeature { - public static final String SERIALIZED_NAME_ID = "id"; - @SerializedName(SERIALIZED_NAME_ID) - private String id; - - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_GEOMETRY = "geometry"; - @SerializedName(SERIALIZED_NAME_GEOMETRY) - private Geometry geometry; - - public static final String SERIALIZED_NAME_PROPERTIES = "properties"; - @SerializedName(SERIALIZED_NAME_PROPERTIES) - private ThresholdProperties properties; - - public ThresholdFeature() { - } - - public ThresholdFeature id(String id) { - this.id = id; - return this; - } - - /** - * A unique identifier for the feature. - * @return id - */ - @javax.annotation.Nonnull - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - - public ThresholdFeature type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public ThresholdFeature geometry(Geometry geometry) { - this.geometry = geometry; - return this; - } - - /** - * The geometric details of the feature, including its type and coordinates. - * @return geometry - */ - @javax.annotation.Nonnull - public Geometry getGeometry() { - return geometry; - } - - public void setGeometry(Geometry geometry) { - this.geometry = geometry; - } - - - public ThresholdFeature properties(ThresholdProperties properties) { - this.properties = properties; - return this; - } - - /** - * Properties defining flood thresholds for various return periods, used to categorize flood risk. - * @return properties - */ - @javax.annotation.Nonnull - public ThresholdProperties getProperties() { - return properties; - } - - public void setProperties(ThresholdProperties properties) { - this.properties = properties; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ThresholdFeature thresholdFeature = (ThresholdFeature) o; - return Objects.equals(this.id, thresholdFeature.id) && - Objects.equals(this.type, thresholdFeature.type) && - Objects.equals(this.geometry, thresholdFeature.geometry) && - Objects.equals(this.properties, thresholdFeature.properties); - } - - @Override - public int hashCode() { - return Objects.hash(id, type, geometry, properties); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ThresholdFeature {\n"); - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" geometry: ").append(toIndentedString(geometry)).append("\n"); - sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("id"); - openapiFields.add("type"); - openapiFields.add("geometry"); - openapiFields.add("properties"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("id"); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("geometry"); - openapiRequiredFields.add("properties"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to ThresholdFeature - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!ThresholdFeature.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in ThresholdFeature is not found in the empty JSON string", ThresholdFeature.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!ThresholdFeature.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ThresholdFeature` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : ThresholdFeature.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (!jsonObj.get("id").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("id").toString())); - } - // validate the required field `geometry` - Geometry.validateJsonElement(jsonObj.get("geometry")); - // validate the required field `properties` - ThresholdProperties.validateJsonElement(jsonObj.get("properties")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!ThresholdFeature.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ThresholdFeature' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(ThresholdFeature.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, ThresholdFeature value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public ThresholdFeature read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of ThresholdFeature given an JSON string - * - * @param jsonString JSON string - * @return An instance of ThresholdFeature - * @throws IOException if the JSON string is invalid with respect to ThresholdFeature - */ - public static ThresholdFeature fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ThresholdFeature.class); - } - - /** - * Convert an instance of ThresholdFeature to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/ThresholdFeatureCollection.java b/src/main/java/io/openepi/flood/model/ThresholdFeatureCollection.java deleted file mode 100644 index 300e6c3..0000000 --- a/src/main/java/io/openepi/flood/model/ThresholdFeatureCollection.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.flood.model.ThresholdFeature; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * ThresholdFeatureCollection - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class ThresholdFeatureCollection { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_FEATURES = "features"; - @SerializedName(SERIALIZED_NAME_FEATURES) - private List features = new ArrayList<>(); - - public ThresholdFeatureCollection() { - } - - public ThresholdFeatureCollection type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public ThresholdFeatureCollection features(List features) { - this.features = features; - return this; - } - - public ThresholdFeatureCollection addFeaturesItem(ThresholdFeature featuresItem) { - if (this.features == null) { - this.features = new ArrayList<>(); - } - this.features.add(featuresItem); - return this; - } - - /** - * A collection of threshold features, each outlining the specific discharge thresholds associated with different return period flood risks. - * @return features - */ - @javax.annotation.Nonnull - public List getFeatures() { - return features; - } - - public void setFeatures(List features) { - this.features = features; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ThresholdFeatureCollection thresholdFeatureCollection = (ThresholdFeatureCollection) o; - return Objects.equals(this.type, thresholdFeatureCollection.type) && - Objects.equals(this.features, thresholdFeatureCollection.features); - } - - @Override - public int hashCode() { - return Objects.hash(type, features); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ThresholdFeatureCollection {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" features: ").append(toIndentedString(features)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("features"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("features"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to ThresholdFeatureCollection - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!ThresholdFeatureCollection.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in ThresholdFeatureCollection is not found in the empty JSON string", ThresholdFeatureCollection.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!ThresholdFeatureCollection.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ThresholdFeatureCollection` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : ThresholdFeatureCollection.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the json data is an array - if (!jsonObj.get("features").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `features` to be an array in the JSON string but got `%s`", jsonObj.get("features").toString())); - } - - JsonArray jsonArrayfeatures = jsonObj.getAsJsonArray("features"); - // validate the required field `features` (array) - for (int i = 0; i < jsonArrayfeatures.size(); i++) { - ThresholdFeature.validateJsonElement(jsonArrayfeatures.get(i)); - }; - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!ThresholdFeatureCollection.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ThresholdFeatureCollection' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(ThresholdFeatureCollection.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, ThresholdFeatureCollection value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public ThresholdFeatureCollection read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of ThresholdFeatureCollection given an JSON string - * - * @param jsonString JSON string - * @return An instance of ThresholdFeatureCollection - * @throws IOException if the JSON string is invalid with respect to ThresholdFeatureCollection - */ - public static ThresholdFeatureCollection fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ThresholdFeatureCollection.class); - } - - /** - * Convert an instance of ThresholdFeatureCollection to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/ThresholdProperties.java b/src/main/java/io/openepi/flood/model/ThresholdProperties.java deleted file mode 100644 index bbcccae..0000000 --- a/src/main/java/io/openepi/flood/model/ThresholdProperties.java +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * ThresholdProperties - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class ThresholdProperties { - public static final String SERIALIZED_NAME_THRESHOLD2Y = "threshold_2y"; - @SerializedName(SERIALIZED_NAME_THRESHOLD2Y) - private BigDecimal threshold2y; - - public static final String SERIALIZED_NAME_THRESHOLD5Y = "threshold_5y"; - @SerializedName(SERIALIZED_NAME_THRESHOLD5Y) - private BigDecimal threshold5y; - - public static final String SERIALIZED_NAME_THRESHOLD20Y = "threshold_20y"; - @SerializedName(SERIALIZED_NAME_THRESHOLD20Y) - private BigDecimal threshold20y; - - public ThresholdProperties() { - } - - public ThresholdProperties threshold2y(BigDecimal threshold2y) { - this.threshold2y = threshold2y; - return this; - } - - /** - * The 2-year return period threshold in m^3/s. - * minimum: 0.0 - * @return threshold2y - */ - @javax.annotation.Nonnull - public BigDecimal getThreshold2y() { - return threshold2y; - } - - public void setThreshold2y(BigDecimal threshold2y) { - this.threshold2y = threshold2y; - } - - - public ThresholdProperties threshold5y(BigDecimal threshold5y) { - this.threshold5y = threshold5y; - return this; - } - - /** - * The 5-year return period threshold in m^3/s. - * minimum: 0.0 - * @return threshold5y - */ - @javax.annotation.Nonnull - public BigDecimal getThreshold5y() { - return threshold5y; - } - - public void setThreshold5y(BigDecimal threshold5y) { - this.threshold5y = threshold5y; - } - - - public ThresholdProperties threshold20y(BigDecimal threshold20y) { - this.threshold20y = threshold20y; - return this; - } - - /** - * The 20-year return period threshold in m^3/s. - * minimum: 0.0 - * @return threshold20y - */ - @javax.annotation.Nonnull - public BigDecimal getThreshold20y() { - return threshold20y; - } - - public void setThreshold20y(BigDecimal threshold20y) { - this.threshold20y = threshold20y; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ThresholdProperties thresholdProperties = (ThresholdProperties) o; - return Objects.equals(this.threshold2y, thresholdProperties.threshold2y) && - Objects.equals(this.threshold5y, thresholdProperties.threshold5y) && - Objects.equals(this.threshold20y, thresholdProperties.threshold20y); - } - - @Override - public int hashCode() { - return Objects.hash(threshold2y, threshold5y, threshold20y); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ThresholdProperties {\n"); - sb.append(" threshold2y: ").append(toIndentedString(threshold2y)).append("\n"); - sb.append(" threshold5y: ").append(toIndentedString(threshold5y)).append("\n"); - sb.append(" threshold20y: ").append(toIndentedString(threshold20y)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("threshold_2y"); - openapiFields.add("threshold_5y"); - openapiFields.add("threshold_20y"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("threshold_2y"); - openapiRequiredFields.add("threshold_5y"); - openapiRequiredFields.add("threshold_20y"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to ThresholdProperties - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!ThresholdProperties.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in ThresholdProperties is not found in the empty JSON string", ThresholdProperties.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!ThresholdProperties.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ThresholdProperties` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : ThresholdProperties.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!ThresholdProperties.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ThresholdProperties' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(ThresholdProperties.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, ThresholdProperties value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public ThresholdProperties read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of ThresholdProperties given an JSON string - * - * @param jsonString JSON string - * @return An instance of ThresholdProperties - * @throws IOException if the JSON string is invalid with respect to ThresholdProperties - */ - public static ThresholdProperties fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ThresholdProperties.class); - } - - /** - * Convert an instance of ThresholdProperties to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/ThresholdResponseModel.java b/src/main/java/io/openepi/flood/model/ThresholdResponseModel.java deleted file mode 100644 index dc3033d..0000000 --- a/src/main/java/io/openepi/flood/model/ThresholdResponseModel.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.flood.model.ThresholdFeatureCollection; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * ThresholdResponseModel - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class ThresholdResponseModel { - public static final String SERIALIZED_NAME_QUERIED_LOCATION = "queried_location"; - @SerializedName(SERIALIZED_NAME_QUERIED_LOCATION) - private ThresholdFeatureCollection queriedLocation; - - public ThresholdResponseModel() { - } - - public ThresholdResponseModel queriedLocation(ThresholdFeatureCollection queriedLocation) { - this.queriedLocation = queriedLocation; - return this; - } - - /** - * A feature collection representing the queried location's threshold data for flood risk analysis. - * @return queriedLocation - */ - @javax.annotation.Nonnull - public ThresholdFeatureCollection getQueriedLocation() { - return queriedLocation; - } - - public void setQueriedLocation(ThresholdFeatureCollection queriedLocation) { - this.queriedLocation = queriedLocation; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ThresholdResponseModel thresholdResponseModel = (ThresholdResponseModel) o; - return Objects.equals(this.queriedLocation, thresholdResponseModel.queriedLocation); - } - - @Override - public int hashCode() { - return Objects.hash(queriedLocation); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ThresholdResponseModel {\n"); - sb.append(" queriedLocation: ").append(toIndentedString(queriedLocation)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("queried_location"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("queried_location"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to ThresholdResponseModel - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!ThresholdResponseModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in ThresholdResponseModel is not found in the empty JSON string", ThresholdResponseModel.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!ThresholdResponseModel.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ThresholdResponseModel` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : ThresholdResponseModel.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `queried_location` - ThresholdFeatureCollection.validateJsonElement(jsonObj.get("queried_location")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!ThresholdResponseModel.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ThresholdResponseModel' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(ThresholdResponseModel.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, ThresholdResponseModel value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public ThresholdResponseModel read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of ThresholdResponseModel given an JSON string - * - * @param jsonString JSON string - * @return An instance of ThresholdResponseModel - * @throws IOException if the JSON string is invalid with respect to ThresholdResponseModel - */ - public static ThresholdResponseModel fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ThresholdResponseModel.class); - } - - /** - * Convert an instance of ThresholdResponseModel to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/ValidationError.java b/src/main/java/io/openepi/flood/model/ValidationError.java deleted file mode 100644 index 471f945..0000000 --- a/src/main/java/io/openepi/flood/model/ValidationError.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.flood.model.ValidationErrorLocInner; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.flood.JSON; - -/** - * ValidationError - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class ValidationError { - public static final String SERIALIZED_NAME_LOC = "loc"; - @SerializedName(SERIALIZED_NAME_LOC) - private List loc = new ArrayList<>(); - - public static final String SERIALIZED_NAME_MSG = "msg"; - @SerializedName(SERIALIZED_NAME_MSG) - private String msg; - - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private String type; - - public ValidationError() { - } - - public ValidationError loc(List loc) { - this.loc = loc; - return this; - } - - public ValidationError addLocItem(ValidationErrorLocInner locItem) { - if (this.loc == null) { - this.loc = new ArrayList<>(); - } - this.loc.add(locItem); - return this; - } - - /** - * Get loc - * @return loc - */ - @javax.annotation.Nonnull - public List getLoc() { - return loc; - } - - public void setLoc(List loc) { - this.loc = loc; - } - - - public ValidationError msg(String msg) { - this.msg = msg; - return this; - } - - /** - * Get msg - * @return msg - */ - @javax.annotation.Nonnull - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - - public ValidationError type(String type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nonnull - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ValidationError validationError = (ValidationError) o; - return Objects.equals(this.loc, validationError.loc) && - Objects.equals(this.msg, validationError.msg) && - Objects.equals(this.type, validationError.type); - } - - @Override - public int hashCode() { - return Objects.hash(loc, msg, type); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ValidationError {\n"); - sb.append(" loc: ").append(toIndentedString(loc)).append("\n"); - sb.append(" msg: ").append(toIndentedString(msg)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("loc"); - openapiFields.add("msg"); - openapiFields.add("type"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("loc"); - openapiRequiredFields.add("msg"); - openapiRequiredFields.add("type"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to ValidationError - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!ValidationError.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in ValidationError is not found in the empty JSON string", ValidationError.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!ValidationError.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ValidationError` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : ValidationError.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the json data is an array - if (!jsonObj.get("loc").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `loc` to be an array in the JSON string but got `%s`", jsonObj.get("loc").toString())); - } - - JsonArray jsonArrayloc = jsonObj.getAsJsonArray("loc"); - // validate the required field `loc` (array) - for (int i = 0; i < jsonArrayloc.size(); i++) { - ValidationErrorLocInner.validateJsonElement(jsonArrayloc.get(i)); - }; - if (!jsonObj.get("msg").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `msg` to be a primitive type in the JSON string but got `%s`", jsonObj.get("msg").toString())); - } - if (!jsonObj.get("type").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!ValidationError.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ValidationError' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(ValidationError.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, ValidationError value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public ValidationError read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of ValidationError given an JSON string - * - * @param jsonString JSON string - * @return An instance of ValidationError - * @throws IOException if the JSON string is invalid with respect to ValidationError - */ - public static ValidationError fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ValidationError.class); - } - - /** - * Convert an instance of ValidationError to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/flood/model/ValidationErrorLocInner.java b/src/main/java/io/openepi/flood/model/ValidationErrorLocInner.java deleted file mode 100644 index 6c82083..0000000 --- a/src/main/java/io/openepi/flood/model/ValidationErrorLocInner.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Flood API - * This is a RESTful service that provides accurate and up-to-date flood information for the geographic region bounded by the following coordinates: `min_lon=-18.0`, `min_lat=-6.0`, `max_lon=52.0`, `max_lat=17.0`.
The data are produced for the Global Flood Awareness System and sourced from the Copernicus Climate Data Store.
Please note that the datasets are licensed under the CEMS-FLOODS datasets licence, which is not a standard open license. We use them in our pre-project to explore relevant data. - * - * The version of the OpenAPI document: 0.9.10 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.flood.model; - -import java.util.Objects; - - - -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.JsonPrimitive; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonParseException; - -import io.openepi.flood.JSON; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-24T13:54:08.842155+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class ValidationErrorLocInner extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(ValidationErrorLocInner.class.getName()); - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!ValidationErrorLocInner.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ValidationErrorLocInner' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); - final TypeAdapter adapterInteger = gson.getDelegateAdapter(this, TypeToken.get(Integer.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, ValidationErrorLocInner value) throws IOException { - if (value == null || value.getActualInstance() == null) { - elementAdapter.write(out, null); - return; - } - - // check if the actual instance is of the type `String` - if (value.getActualInstance() instanceof String) { - JsonPrimitive primitive = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonPrimitive(); - elementAdapter.write(out, primitive); - return; - } - // check if the actual instance is of the type `Integer` - if (value.getActualInstance() instanceof Integer) { - JsonPrimitive primitive = adapterInteger.toJsonTree((Integer)value.getActualInstance()).getAsJsonPrimitive(); - elementAdapter.write(out, primitive); - return; - } - throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: Integer, String"); - } - - @Override - public ValidationErrorLocInner read(JsonReader in) throws IOException { - Object deserialized = null; - JsonElement jsonElement = elementAdapter.read(in); - - ArrayList errorMessages = new ArrayList<>(); - TypeAdapter actualAdapter = elementAdapter; - - // deserialize String - try { - // validate the JSON object to see if any exception is thrown - if (!jsonElement.getAsJsonPrimitive().isString()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); - } - actualAdapter = adapterString; - ValidationErrorLocInner ret = new ValidationErrorLocInner(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'String'", e); - } - // deserialize Integer - try { - // validate the JSON object to see if any exception is thrown - if (!jsonElement.getAsJsonPrimitive().isNumber()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); - } - actualAdapter = adapterInteger; - ValidationErrorLocInner ret = new ValidationErrorLocInner(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'Integer'", e); - } - - throw new IOException(String.format("Failed deserialization for ValidationErrorLocInner: no class matches result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); - } - }.nullSafe(); - } - } - - // store a list of schema names defined in anyOf - public static final Map> schemas = new HashMap>(); - - public ValidationErrorLocInner() { - super("anyOf", Boolean.FALSE); - } - - public ValidationErrorLocInner(Object o) { - super("anyOf", Boolean.FALSE); - setActualInstance(o); - } - - static { - schemas.put("String", String.class); - schemas.put("Integer", Integer.class); - } - - @Override - public Map> getSchemas() { - return ValidationErrorLocInner.schemas; - } - - /** - * Set the instance that matches the anyOf child schema, check - * the instance parameter is valid against the anyOf child schemas: - * Integer, String - * - * It could be an instance of the 'anyOf' schemas. - */ - @Override - public void setActualInstance(Object instance) { - if (instance instanceof String) { - super.setActualInstance(instance); - return; - } - - if (instance instanceof Integer) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be Integer, String"); - } - - /** - * Get the actual instance, which can be the following: - * Integer, String - * - * @return The actual instance (Integer, String) - */ - @SuppressWarnings("unchecked") - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `String`. If the actual instance is not `String`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `String` - * @throws ClassCastException if the instance is not `String` - */ - public String getString() throws ClassCastException { - return (String)super.getActualInstance(); - } - /** - * Get the actual instance of `Integer`. If the actual instance is not `Integer`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Integer` - * @throws ClassCastException if the instance is not `Integer` - */ - public Integer getInteger() throws ClassCastException { - return (Integer)super.getActualInstance(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to ValidationErrorLocInner - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - // validate anyOf schemas one by one - ArrayList errorMessages = new ArrayList<>(); - // validate the json string with String - try { - if (!jsonElement.getAsJsonPrimitive().isString()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); - } - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); - // continue to the next one - } - // validate the json string with Integer - try { - if (!jsonElement.getAsJsonPrimitive().isNumber()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); - } - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); - // continue to the next one - } - throw new IOException(String.format("The JSON string is invalid for ValidationErrorLocInner with anyOf schemas: Integer, String. no class match the result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); - } - - /** - * Create an instance of ValidationErrorLocInner given an JSON string - * - * @param jsonString JSON string - * @return An instance of ValidationErrorLocInner - * @throws IOException if the JSON string is invalid with respect to ValidationErrorLocInner - */ - public static ValidationErrorLocInner fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ValidationErrorLocInner.class); - } - - /** - * Convert an instance of ValidationErrorLocInner to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/geocoding/ApiClient.java b/src/main/java/io/openepi/geocoding/ApiClient.java deleted file mode 100644 index 4c77c50..0000000 --- a/src/main/java/io/openepi/geocoding/ApiClient.java +++ /dev/null @@ -1,1565 +0,0 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.geocoding; - -import okhttp3.*; -import okhttp3.internal.http.HttpMethod; -import okhttp3.internal.tls.OkHostnameVerifier; -import okhttp3.logging.HttpLoggingInterceptor; -import okhttp3.logging.HttpLoggingInterceptor.Level; -import okio.Buffer; -import okio.BufferedSink; -import okio.Okio; - -import javax.net.ssl.*; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; -import java.net.URI; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.text.DateFormat; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import io.openepi.common.auth.Authentication; -import io.openepi.common.auth.HttpBasicAuth; -import io.openepi.common.auth.HttpBearerAuth; -import io.openepi.common.auth.ApiKeyAuth; -import io.openepi.common.*; - -/** - *

ApiClient class.

- */ -public class ApiClient { - - private String basePath = "https://api.openepi.io/geocoding"; - protected List servers = new ArrayList(Arrays.asList( - new ServerConfiguration( - "https://api.openepi.io/geocoding", - "No description provided", - new HashMap() - ) - )); - protected Integer serverIndex = 0; - protected Map serverVariables = null; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private Map defaultCookieMap = new HashMap(); - private String tempFolderPath = null; - - private Map authentications; - - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; - - private InputStream sslCaCert; - private boolean verifyingSsl; - private KeyManager[] keyManagers; - - private OkHttpClient httpClient; - private JSON json; - - private HttpLoggingInterceptor loggingInterceptor; - - /** - * Basic constructor for ApiClient - */ - public ApiClient() { - init(); - initHttpClient(); - - // Setup authentications (key: authentication name, value: authentication). - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - /** - * Basic constructor with custom OkHttpClient - * - * @param client a {@link okhttp3.OkHttpClient} object - */ - public ApiClient(OkHttpClient client) { - init(); - - httpClient = client; - - // Setup authentications (key: authentication name, value: authentication). - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - private void initHttpClient() { - initHttpClient(Collections.emptyList()); - } - - private void initHttpClient(List interceptors) { - OkHttpClient.Builder builder = new OkHttpClient.Builder(); - builder.addNetworkInterceptor(getProgressInterceptor()); - for (Interceptor interceptor: interceptors) { - builder.addInterceptor(interceptor); - } - - httpClient = builder.build(); - } - - private void init() { - verifyingSsl = true; - - json = new JSON(); - - // Set default User-Agent. - setUserAgent("OpenAPI-Generator/0.4.3/java"); - - authentications = new HashMap(); - } - - /** - * Get base path - * - * @return Base path - */ - public String getBasePath() { - return basePath; - } - - /** - * Set base path - * - * @param basePath Base path of the URL (e.g https://api.openepi.io/geocoding - * @return An instance of OkHttpClient - */ - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - this.serverIndex = null; - return this; - } - - public List getServers() { - return servers; - } - - public ApiClient setServers(List servers) { - this.servers = servers; - return this; - } - - public Integer getServerIndex() { - return serverIndex; - } - - public ApiClient setServerIndex(Integer serverIndex) { - this.serverIndex = serverIndex; - return this; - } - - public Map getServerVariables() { - return serverVariables; - } - - public ApiClient setServerVariables(Map serverVariables) { - this.serverVariables = serverVariables; - return this; - } - - /** - * Get HTTP client - * - * @return An instance of OkHttpClient - */ - public OkHttpClient getHttpClient() { - return httpClient; - } - - /** - * Set HTTP client, which must never be null. - * - * @param newHttpClient An instance of OkHttpClient - * @return Api Client - * @throws java.lang.NullPointerException when newHttpClient is null - */ - public ApiClient setHttpClient(OkHttpClient newHttpClient) { - this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!"); - return this; - } - - /** - * Get JSON - * - * @return JSON object - */ - public JSON getJSON() { - return json; - } - - /** - * Set JSON - * - * @param json JSON object - * @return Api client - */ - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - /** - * True if isVerifyingSsl flag is on - * - * @return True if isVerifySsl flag is on - */ - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - * - * @param verifyingSsl True to verify TLS/SSL connection - * @return ApiClient - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - /** - * Get SSL CA cert. - * - * @return Input stream to the SSL CA cert - */ - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - * - * @param sslCaCert input stream for SSL CA cert - * @return ApiClient - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - /** - *

Getter for the field keyManagers.

- * - * @return an array of {@link javax.net.ssl.KeyManager} objects - */ - public KeyManager[] getKeyManagers() { - return keyManagers; - } - - /** - * Configure client keys to use for authorization in an SSL session. - * Use null to reset to default. - * - * @param managers The KeyManagers to use - * @return ApiClient - */ - public ApiClient setKeyManagers(KeyManager[] managers) { - this.keyManagers = managers; - applySslSettings(); - return this; - } - - /** - *

Getter for the field dateFormat.

- * - * @return a {@link java.text.DateFormat} object - */ - public DateFormat getDateFormat() { - return dateFormat; - } - - /** - *

Setter for the field dateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link io.openepi.geocoding.ApiClient} object - */ - public ApiClient setDateFormat(DateFormat dateFormat) { - JSON.setDateFormat(dateFormat); - return this; - } - - /** - *

Set SqlDateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link io.openepi.geocoding.ApiClient} object - */ - public ApiClient setSqlDateFormat(DateFormat dateFormat) { - JSON.setSqlDateFormat(dateFormat); - return this; - } - - /** - *

Set OffsetDateTimeFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link io.openepi.geocoding.ApiClient} object - */ - public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - JSON.setOffsetDateTimeFormat(dateFormat); - return this; - } - - /** - *

Set LocalDateFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link io.openepi.geocoding.ApiClient} object - */ - public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { - JSON.setLocalDateFormat(dateFormat); - return this; - } - - /** - *

Set LenientOnJson.

- * - * @param lenientOnJson a boolean - * @return a {@link io.openepi.geocoding.ApiClient} object - */ - public ApiClient setLenientOnJson(boolean lenientOnJson) { - JSON.setLenientOnJson(lenientOnJson); - return this; - } - - /** - * Get authentications (key: authentication name, value: authentication). - * - * @return Map of authentication objects - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - - /** - * Helper method to set username for the first HTTP basic authentication. - * - * @param username Username - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - * - * @param password Password - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - * - * @param apiKey API key - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - * - * @param apiKeyPrefix API key prefix - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - * - * @param accessToken Access token - */ - public void setAccessToken(String accessToken) { - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Helper method to set credentials for AWSV4 Signature - * - * @param accessKey Access Key - * @param secretKey Secret Key - * @param region Region - * @param service Service to access to - */ - public void setAWS4Configuration(String accessKey, String secretKey, String region, String service) { - throw new RuntimeException("No AWS4 authentication configured!"); - } - - /** - * Helper method to set credentials for AWSV4 Signature - * - * @param accessKey Access Key - * @param secretKey Secret Key - * @param sessionToken Session Token - * @param region Region - * @param service Service to access to - */ - public void setAWS4Configuration(String accessKey, String secretKey, String sessionToken, String region, String service) { - throw new RuntimeException("No AWS4 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - * - * @param userAgent HTTP request's user agent - * @return ApiClient - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - * @return ApiClient - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * Add a default cookie. - * - * @param key The cookie's key - * @param value The cookie's value - * @return ApiClient - */ - public ApiClient addDefaultCookie(String key, String value) { - defaultCookieMap.put(key, value); - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - * - * @return True if debugging is enabled, false otherwise. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - * @return ApiClient - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); - } else { - final OkHttpClient.Builder builder = httpClient.newBuilder(); - builder.interceptors().remove(loggingInterceptor); - httpClient = builder.build(); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default temporary folder. - * - * @see createTempFile - * @return Temporary folder path - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - /** - * Set the temporary folder path (for downloading files) - * - * @param tempFolderPath Temporary folder path - * @return ApiClient - */ - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Get connection timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getConnectTimeout() { - return httpClient.connectTimeoutMillis(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param connectionTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - /** - * Get read timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getReadTimeout() { - return httpClient.readTimeoutMillis(); - } - - /** - * Sets the read timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param readTimeout read timeout in milliseconds - * @return Api client - */ - public ApiClient setReadTimeout(int readTimeout) { - httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - /** - * Get write timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getWriteTimeout() { - return httpClient.writeTimeoutMillis(); - } - - /** - * Sets the write timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param writeTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setWriteTimeout(int writeTimeout) { - httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - - /** - * Format the given parameter object into string. - * - * @param param Parameter - * @return String representation of the parameter - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) { - //Serialize to json string and remove the " enclosing characters - String jsonStr = JSON.serialize(param); - return jsonStr.substring(1, jsonStr.length() - 1); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection) param) { - if (b.length() > 0) { - b.append(","); - } - b.append(o); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /** - * Formats the specified query parameter to a list containing a single {@code Pair} object. - * - * Note that {@code value} must not be a collection. - * - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list containing a single {@code Pair} object. - */ - public List parameterToPair(String name, Object value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value instanceof Collection) { - return params; - } - - params.add(new Pair(name, parameterToString(value))); - return params; - } - - /** - * Formats the specified collection query parameters to a list of {@code Pair} objects. - * - * Note that the values of each of the returned Pair objects are percent-encoded. - * - * @param collectionFormat The collection format of the parameter. - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list of {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Collection value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value.isEmpty()) { - return params; - } - - // create the params based on the collection format - if ("multi".equals(collectionFormat)) { - for (Object item : value) { - params.add(new Pair(name, escapeString(parameterToString(item)))); - } - return params; - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - // escape all delimiters except commas, which are URI reserved - // characters - if ("ssv".equals(collectionFormat)) { - delimiter = escapeString(" "); - } else if ("tsv".equals(collectionFormat)) { - delimiter = escapeString("\t"); - } else if ("pipes".equals(collectionFormat)) { - delimiter = escapeString("|"); - } - - StringBuilder sb = new StringBuilder(); - for (Object item : value) { - sb.append(delimiter); - sb.append(escapeString(parameterToString(item))); - } - - params.add(new Pair(name, sb.substring(delimiter.length()))); - - return params; - } - - /** - * Formats the specified collection path parameter to a string value. - * - * @param collectionFormat The collection format of the parameter. - * @param value The value of the parameter. - * @return String representation of the parameter - */ - public String collectionPathParameterToString(String collectionFormat, Collection value) { - // create the value based on the collection format - if ("multi".equals(collectionFormat)) { - // not valid for path params - return parameterToString(value); - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - if ("ssv".equals(collectionFormat)) { - delimiter = " "; - } else if ("tsv".equals(collectionFormat)) { - delimiter = "\t"; - } else if ("pipes".equals(collectionFormat)) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : value) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - return sb.substring(delimiter.length()); - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * application/vnd.company+json - * "* / *" is also default to JSON - * @param mime MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public boolean isJsonMime(String mime) { - String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; - return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * returns null. If it matches "any", JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return null; - } - - if (contentTypes[0].equals("*/*")) { - return "application/json"; - } - - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - * - * @param str String to be escaped - * @return Escaped string - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param Type - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws io.openepi.common.ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - @SuppressWarnings("unchecked") - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; - } - - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); - } - - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); - } - - if (respBody == null || "".equals(respBody)) { - return null; - } - - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return JSON.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } - } - - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws io.openepi.common.ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create((File) obj, MediaType.parse(contentType)); - } else if ("text/plain".equals(contentType) && obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - return RequestBody.create(content, MediaType.parse(contentType)); - } else if (obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } - } - - /** - * Download file from the given response. - * - * @param response An instance of the Response object - * @throws io.openepi.common.ApiException If fail to read file content from response and write to disk - * @return Downloaded file - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * Prepare file for download - * - * @param response An instance of the Response object - * @return Prepared file for the download - * @throws java.io.IOException If fail to prepare file for download - */ - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } - } - - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // Files.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; - } - - if (tempFolderPath == null) - return Files.createTempFile(prefix, suffix).toFile(); - else - return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); - } - - /** - * {@link #execute(Call, Type)} - * - * @param Type - * @param call An instance of the Call object - * @return ApiResponse<T> - * @throws io.openepi.common.ApiException If fail to execute the call - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @param call Call - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws io.openepi.common.ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * {@link #executeAsync(Call, Type, ApiCallback)} - * - * @param Type - * @param call An instance of the Call object - * @param callback ApiCallback<T> - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } - - /** - * Execute HTTP call asynchronously. - * - * @param Type - * @param call The callback to be executed when the API call finishes - * @param returnType Return type - * @param callback ApiCallback - * @see #execute(Call, Type) - */ - @SuppressWarnings("unchecked") - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } - - @Override - public void onResponse(Call call, Response response) throws IOException { - T result; - try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; - } catch (Exception e) { - callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); - return; - } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @param Type - * @param response Response - * @param returnType Return type - * @return Type - * @throws io.openepi.common.ApiException If the response has an unsuccessful status code or - * fail to deserialize the response body - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - if (response.body() != null) { - try { - response.body().close(); - } catch (Exception e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { - try { - respBody = response.body().string(); - } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - - /** - * Build HTTP call with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP call - * @throws io.openepi.common.ApiException If fail to serialize the request body object - */ - public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); - - return httpClient.newCall(request); - } - - /** - * Build an HTTP request with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP request - * @throws io.openepi.common.ApiException If fail to serialize the request body object - */ - public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams - List allQueryParams = new ArrayList(queryParams); - allQueryParams.addAll(collectionQueryParams); - - final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); - - // prepare HTTP request body - RequestBody reqBody; - String contentType = headerParams.get("Content-Type"); - String contentTypePure = contentType; - if (contentTypePure != null && contentTypePure.contains(";")) { - contentTypePure = contentType.substring(0, contentType.indexOf(";")); - } - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentTypePure)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentTypePure)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create("", contentType == null ? null : MediaType.parse(contentType)); - } - } else { - reqBody = serialize(body, contentType); - } - - // update parameters with authentication settings - updateParamsForAuth(authNames, allQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url)); - - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - processCookieParams(cookieParams, reqBuilder); - - // Associate callback with request (if not null) so interceptor can - // access it when creating ProgressResponseBody - reqBuilder.tag(callback); - - Request request = null; - - if (callback != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return request; - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param baseUrl The base URL - * @param path The sub path - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @return The full URL - */ - public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { - final StringBuilder url = new StringBuilder(); - if (baseUrl != null) { - url.append(baseUrl).append(path); - } else { - String baseURL; - if (serverIndex != null) { - if (serverIndex < 0 || serverIndex >= servers.size()) { - throw new ArrayIndexOutOfBoundsException(String.format( - "Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size() - )); - } - baseURL = servers.get(serverIndex).URL(serverVariables); - } else { - baseURL = basePath; - } - url.append(baseURL).append(path); - } - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { - String prefix = url.toString().contains("?") ? "&" : "?"; - for (Pair param : collectionQueryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - // collection query parameter value already escaped as part of parameterToPairs - url.append(escapeString(param.getName())).append("=").append(value); - } - } - } - - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - * - * @param headerParams Header parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Set cookie parameters to the request builder, including default cookies. - * - * @param cookieParams Cookie parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processCookieParams(Map cookieParams, Request.Builder reqBuilder) { - for (Entry param : cookieParams.entrySet()) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - for (Entry param : defaultCookieMap.entrySet()) { - if (!cookieParams.containsKey(param.getKey())) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - * @param cookieParams Map of cookie parameters - * @param payload HTTP request body - * @param method HTTP method - * @param uri URI - * @throws io.openepi.common.ApiException If fails to update the parameters - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, - Map cookieParams, String payload, String method, URI uri) throws ApiException { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) { - throw new RuntimeException("Authentication undefined: " + authName); - } - auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); - } - } - - /** - * Build a form-encoding request body with the given form parameters. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - addPartToMultiPartBuilder(mpBuilder, param.getKey(), file); - } else if (param.getValue() instanceof List) { - List list = (List) param.getValue(); - for (Object item: list) { - if (item instanceof File) { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item); - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The guessed Content-Type - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - - /** - * Add a Content-Disposition Header for the given key and file to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param file The file to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, File file) { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); - } - - /** - * Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param obj The complex object to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) { - RequestBody requestBody; - if (obj instanceof String) { - requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain")); - } else { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - requestBody = RequestBody.create(content, MediaType.parse("application/json")); - } - - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""); - mpBuilder.addPart(partHeaders, requestBody); - } - - /** - * Get network interceptor to add it to the httpClient to track download progress for - * async requests. - */ - private Interceptor getProgressInterceptor() { - return new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - final Request request = chain.request(); - final Response originalResponse = chain.proceed(request); - if (request.tag() instanceof ApiCallback) { - final ApiCallback callback = (ApiCallback) request.tag(); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), callback)) - .build(); - } - return originalResponse; - } - }; - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { - try { - TrustManager[] trustManagers; - HostnameVerifier hostnameVerifier; - if (!verifyingSsl) { - trustManagers = new TrustManager[]{ - new X509TrustManager() { - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[]{}; - } - } - }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - } else { - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - - if (sslCaCert == null) { - trustManagerFactory.init((KeyStore) null); - } else { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); - } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + (index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); - } - trustManagerFactory.init(caKeyStore); - } - trustManagers = trustManagerFactory.getTrustManagers(); - hostnameVerifier = OkHostnameVerifier.INSTANCE; - } - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient = httpClient.newBuilder() - .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) - .hostnameVerifier(hostnameVerifier) - .build(); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); - } - } - - /** - * Convert the HTTP request body to a string. - * - * @param requestBody The HTTP request object - * @return The string representation of the HTTP request body - * @throws io.openepi.common.ApiException If fail to serialize the request body object into a string - */ - private String requestBodyToString(RequestBody requestBody) throws ApiException { - if (requestBody != null) { - try { - final Buffer buffer = new Buffer(); - requestBody.writeTo(buffer); - return buffer.readUtf8(); - } catch (final IOException e) { - throw new ApiException(e); - } - } - - // empty http request body - return ""; - } -} diff --git a/src/main/java/io/openepi/geocoding/Configuration.java b/src/main/java/io/openepi/geocoding/Configuration.java deleted file mode 100644 index 607529f..0000000 --- a/src/main/java/io/openepi/geocoding/Configuration.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.geocoding; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class Configuration { - public static final String VERSION = "0.4.3"; - - private static ApiClient defaultApiClient = new ApiClient(); - - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - * - * @return Default API client - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } - - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - * - * @param apiClient API client - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } -} diff --git a/src/main/java/io/openepi/geocoding/GeocodingClient.java b/src/main/java/io/openepi/geocoding/GeocodingClient.java new file mode 100644 index 0000000..2491e37 --- /dev/null +++ b/src/main/java/io/openepi/geocoding/GeocodingClient.java @@ -0,0 +1,131 @@ +package io.openepi.geocoding; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import io.openepi.geocoding.model.FeatureCollection; +import io.openepi.geocoding.model.GeocodeException; +import io.openepi.geocoding.model.Geometry; +import okhttp3.*; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.util.concurrent.CompletableFuture; + +public class GeocodingClient { + private final String scheme = "https"; + private final String host = "photon.komoot.io"; + private final OkHttpClient httpClient; + private static final Gson gson = new GsonBuilder().registerTypeAdapter(Geometry.class, new GeometryDeserializer()).create(); + + public GeocodingClient() { + this.httpClient = new OkHttpClient(); + } + + public FeatureCollection geocode(String query) { + try (Response response = this.httpClient.newCall(buildGeocodeRequest(query)).execute()) { + return handleResponse(response); + } catch (IOException e) { + throw new GeocodeException(e); + } + } + + public CompletableFuture geocodeAsync(String query) { + CompletableFuture future = new CompletableFuture<>(); + this.httpClient.newCall(buildGeocodeRequest(query)).enqueue(handleCallback(future)); + + return future; + } + + public FeatureCollection reverse(double lat, double lon, Integer limit, String lang) { + try (Response response = this.httpClient.newCall(buildReverseRequest(lat, lon, limit, lang)).execute()) { + return handleResponse(response); + } catch (IOException e) { + throw new GeocodeException(e); + } + } + + public FeatureCollection reverse(double lat, double lon) { + return reverse(lat, lon, null, null); + } + + public FeatureCollection reverse(double lat, double lon, Integer limit) { + return reverse(lat, lon, limit, null); + } + + public CompletableFuture reverseAsync(double lat, double lon, Integer limit, String lang) { + CompletableFuture future = new CompletableFuture<>(); + this.httpClient.newCall(buildReverseRequest(lat, lon, limit, lang)).enqueue(handleCallback(future)); + + return future; + } + + public CompletableFuture reverseAsync(double lat, double lon, Integer limit) { + return reverseAsync(lat, lon, limit, null); + } + + public CompletableFuture reverseAsync(double lat, double lon) { + return reverseAsync(lat, lon, null, null); + } + + @NotNull + private Callback handleCallback(CompletableFuture future) { + return new Callback() { + + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + future.complete(handleResponse(response)); + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new GeocodeException(e)); + } + }; + } + + private FeatureCollection handleResponse(Response response) { + try { + if (!response.isSuccessful()) { + throw new GeocodeException("Request failed: " + response); + } + ResponseBody body = response.body(); + if (body == null) { + throw new GeocodeException("Response body is null: " + response); + } + + return gson.fromJson(body.string(), FeatureCollection.class); + } catch (IOException e) { + throw new GeocodeException(e); + } + } + + private Request buildGeocodeRequest(String query) { + HttpUrl url = new HttpUrl.Builder() + .scheme(scheme) + .host(host) + .addPathSegment("api") + .addQueryParameter("q", query) + .build(); + + return new Request.Builder() + .url(url) + .build(); + } + + private Request buildReverseRequest(double lat, double lon, Integer limit, String lang) { + HttpUrl.Builder builder = new HttpUrl.Builder() + .scheme(scheme) + .host(host) + .addPathSegment("reverse") + .addQueryParameter("lat", String.valueOf(lat)) + .addQueryParameter("lon", String.valueOf(lon)); + + if (lang != null && !lang.isEmpty()) + builder.addQueryParameter("lang", lang); + + if (limit != null) + builder.addQueryParameter("limit", String.valueOf(limit)); + + return new Request.Builder().url(builder.build()).build(); + } +} diff --git a/src/main/java/io/openepi/geocoding/GeometryDeserializer.java b/src/main/java/io/openepi/geocoding/GeometryDeserializer.java new file mode 100644 index 0000000..7520f5a --- /dev/null +++ b/src/main/java/io/openepi/geocoding/GeometryDeserializer.java @@ -0,0 +1,33 @@ +package io.openepi.geocoding; + +import com.google.gson.*; +import io.openepi.geocoding.model.*; +import java.lang.reflect.Type; + +public class GeometryDeserializer implements JsonDeserializer { + + @Override + public Geometry deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + + JsonObject obj = json.getAsJsonObject(); + String geoType = obj.get("type").getAsString(); + + switch (geoType) { + case "Point": + return context.deserialize(obj, Point.class); + case "MultiPoint": + return context.deserialize(obj, MultiPoint.class); + case "LineString": + return context.deserialize(obj, LineString.class); + case "MultiLineString": + return context.deserialize(obj, MultiLineString.class); + case "Polygon": + return context.deserialize(obj, Polygon.class); + case "MultiPolygon": + return context.deserialize(obj, MultiPolygon.class); + default: + throw new JsonParseException("Unknown geometry type: " + geoType); + } + } +} \ No newline at end of file diff --git a/src/main/java/io/openepi/geocoding/JSON.java b/src/main/java/io/openepi/geocoding/JSON.java deleted file mode 100644 index 954d1df..0000000 --- a/src/main/java/io/openepi/geocoding/JSON.java +++ /dev/null @@ -1,413 +0,0 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.geocoding; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.internal.bind.util.ISO8601Utils; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonElement; -import io.gsonfire.GsonFireBuilder; -import io.gsonfire.TypeSelector; - -import okio.ByteString; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Type; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.ParsePosition; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.Locale; -import java.util.Map; -import java.util.HashMap; - -/* - * A JSON utility class - * - * NOTE: in the future, this class may be converted to static, which may break - * backward-compatibility - */ -public class JSON { - private static Gson gson; - private static boolean isLenientOnJson = false; - private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); - private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); - private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); - private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); - private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - - @SuppressWarnings("unchecked") - public static GsonBuilder createGson() { - GsonFireBuilder fireBuilder = new GsonFireBuilder() - ; - GsonBuilder builder = fireBuilder.createGsonBuilder(); - return builder; - } - - private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { - JsonElement element = readElement.getAsJsonObject().get(discriminatorField); - if (null == element) { - throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); - } - return element.getAsString(); - } - - /** - * Returns the Java class that implements the OpenAPI schema for the specified discriminator value. - * - * @param classByDiscriminatorValue The map of discriminator values to Java classes. - * @param discriminatorValue The value of the OpenAPI discriminator in the input data. - * @return The Java class that implements the OpenAPI schema - */ - private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { - Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue); - if (null == clazz) { - throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); - } - return clazz; - } - - static { - GsonBuilder gsonBuilder = createGson(); - gsonBuilder.registerTypeAdapter(Date.class, dateTypeAdapter); - gsonBuilder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); - gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); - gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); - gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.geocoding.model.Feature.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.geocoding.model.FeatureCollection.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.geocoding.model.Geometry.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.geocoding.model.HTTPValidationError.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.geocoding.model.LineString.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.geocoding.model.MultiLineString.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.geocoding.model.MultiPoint.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.geocoding.model.MultiPolygon.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.geocoding.model.Point.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.geocoding.model.Polygon.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.geocoding.model.Properties.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.geocoding.model.ValidationError.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.geocoding.model.ValidationErrorLocInner.CustomTypeAdapterFactory()); - gson = gsonBuilder.create(); - } - - /** - * Get Gson. - * - * @return Gson - */ - public static Gson getGson() { - return gson; - } - - /** - * Set Gson. - * - * @param gson Gson - */ - public static void setGson(Gson gson) { - JSON.gson = gson; - } - - public static void setLenientOnJson(boolean lenientOnJson) { - isLenientOnJson = lenientOnJson; - } - - /** - * Serialize the given Java object into JSON string. - * - * @param obj Object - * @return String representation of the JSON - */ - public static String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param Type - * @param body The JSON string - * @param returnType The type to deserialize into - * @return The deserialized Java object - */ - @SuppressWarnings("unchecked") - public static T deserialize(String body, Type returnType) { - try { - if (isLenientOnJson) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - if (returnType.equals(String.class)) { - return (T) body; - } else { - throw (e); - } - } - } - - /** - * Gson TypeAdapter for Byte Array type - */ - public static class ByteArrayAdapter extends TypeAdapter { - - @Override - public void write(JsonWriter out, byte[] value) throws IOException { - if (value == null) { - out.nullValue(); - } else { - out.value(ByteString.of(value).base64()); - } - } - - @Override - public byte[] read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String bytesAsBase64 = in.nextString(); - ByteString byteString = ByteString.decodeBase64(bytesAsBase64); - return byteString.toByteArray(); - } - } - } - - /** - * Gson TypeAdapter for JSR310 OffsetDateTime type - */ - public static class OffsetDateTimeTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public OffsetDateTimeTypeAdapter() { - this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); - } - - public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, OffsetDateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public OffsetDateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - if (date.endsWith("+0000")) { - date = date.substring(0, date.length()-5) + "Z"; - } - return OffsetDateTime.parse(date, formatter); - } - } - } - - /** - * Gson TypeAdapter for JSR310 LocalDate type - */ - public static class LocalDateTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public LocalDateTypeAdapter() { - this(DateTimeFormatter.ISO_LOCAL_DATE); - } - - public LocalDateTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return LocalDate.parse(date, formatter); - } - } - } - - public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - offsetDateTimeTypeAdapter.setFormat(dateFormat); - } - - public static void setLocalDateFormat(DateTimeFormatter dateFormat) { - localDateTypeAdapter.setFormat(dateFormat); - } - - /** - * Gson TypeAdapter for java.sql.Date type - * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used - * (more efficient than SimpleDateFormat). - */ - public static class SqlDateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public SqlDateTypeAdapter() {} - - public SqlDateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, java.sql.Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = date.toString(); - } - out.value(value); - } - } - - @Override - public java.sql.Date read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return new java.sql.Date(dateFormat.parse(date).getTime()); - } - return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } - } - - /** - * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, ISO8601Utils will be used. - */ - public static class DateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public DateTypeAdapter() {} - - public DateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = ISO8601Utils.format(date, true); - } - out.value(value); - } - } - - @Override - public Date read(JsonReader in) throws IOException { - try { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return dateFormat.parse(date); - } - return ISO8601Utils.parse(date, new ParsePosition(0)); - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } catch (IllegalArgumentException e) { - throw new JsonParseException(e); - } - } - } - - public static void setDateFormat(DateFormat dateFormat) { - dateTypeAdapter.setFormat(dateFormat); - } - - public static void setSqlDateFormat(DateFormat dateFormat) { - sqlDateTypeAdapter.setFormat(dateFormat); - } -} diff --git a/src/main/java/io/openepi/geocoding/api/GeocodingApi.java b/src/main/java/io/openepi/geocoding/api/GeocodingApi.java deleted file mode 100644 index c3f471a..0000000 --- a/src/main/java/io/openepi/geocoding/api/GeocodingApi.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.geocoding.api; - -import io.openepi.geocoding.ApiClient; -import io.openepi.geocoding.Configuration; -import io.openepi.common.ApiCallback; -import io.openepi.common.ApiException; -import io.openepi.common.ApiResponse; -import io.openepi.common.Pair; - -import com.google.gson.reflect.TypeToken; - - -import java.math.BigDecimal; -import io.openepi.geocoding.model.FeatureCollection; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class GeocodingApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public GeocodingApi() { - this(Configuration.getDefaultApiClient()); - } - - public GeocodingApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for geocodingGet - * @param q Search query (required) - * @param lat Geocode with priority to this latitude (optional) - * @param lon Geocode with priority to this longitude (optional) - * @param lang Set preferred language (e.g. \"default\", \"en\", \"de\", \"fr\") (optional) - * @param limit Limit number of results (optional) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call geocodingGetCall(String q, BigDecimal lat, BigDecimal lon, String lang, Integer limit, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - if (q != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("q", q)); - } - - if (lat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lat", lat)); - } - - if (lon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lon", lon)); - } - - if (lang != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lang", lang)); - } - - if (limit != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("limit", limit)); - } - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call geocodingGetValidateBeforeCall(String q, BigDecimal lat, BigDecimal lon, String lang, Integer limit, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'q' is set - if (q == null) { - throw new ApiException("Missing the required parameter 'q' when calling geocodingGet(Async)"); - } - - return geocodingGetCall(q, lat, lon, lang, limit, _callback); - - } - - /** - * Geocoding - * Returns a GeoJSON FeatureCollection of places matching the search query - * @param q Search query (required) - * @param lat Geocode with priority to this latitude (optional) - * @param lon Geocode with priority to this longitude (optional) - * @param lang Set preferred language (e.g. \"default\", \"en\", \"de\", \"fr\") (optional) - * @param limit Limit number of results (optional) - * @return FeatureCollection - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public FeatureCollection getGeocoding(String q, BigDecimal lat, BigDecimal lon, String lang, Integer limit) throws ApiException { - ApiResponse localVarResp = geocodingGetWithHttpInfo(q, lat, lon, lang, limit); - return localVarResp.getData(); - } - - /** - * Geocoding - * Returns a GeoJSON FeatureCollection of places matching the search query - * @param q Search query (required) - * @return FeatureCollection - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public FeatureCollection getGeocoding(String q) throws ApiException { - return getGeocoding(q, null, null, null, null); - } - - - - /** - * Geocoding - * Returns a GeoJSON FeatureCollection of places matching the search query - * @param q Search query (required) - * @param lat Geocode with priority to this latitude (optional) - * @param lon Geocode with priority to this longitude (optional) - * @param lang Set preferred language (e.g. \"default\", \"en\", \"de\", \"fr\") (optional) - * @param limit Limit number of results (optional) - * @return ApiResponse<FeatureCollection> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public ApiResponse geocodingGetWithHttpInfo(String q, BigDecimal lat, BigDecimal lon, String lang, Integer limit) throws ApiException { - okhttp3.Call localVarCall = geocodingGetValidateBeforeCall(q, lat, lon, lang, limit, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Geocoding (asynchronously) - * Returns a GeoJSON FeatureCollection of places matching the search query - * @param q Search query (required) - * @param lat Geocode with priority to this latitude (optional) - * @param lon Geocode with priority to this longitude (optional) - * @param lang Set preferred language (e.g. \"default\", \"en\", \"de\", \"fr\") (optional) - * @param limit Limit number of results (optional) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call getGeocodingAsync(String q, BigDecimal lat, BigDecimal lon, String lang, Integer limit, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = geocodingGetValidateBeforeCall(q, lat, lon, lang, limit, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - - /** - * Geocoding (asynchronously) - * Returns a GeoJSON FeatureCollection of places matching the search query - * @param q Search query (required) - * @return FeatureCollection - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public okhttp3.Call getGeocodingAsync(String q, final ApiCallback _callback) throws ApiException { - return getGeocodingAsync(q, null, null, null, null, _callback); - } - - - /** - * Build call for reverseGeocodingReverseGet - * @param lat Latitude (required) - * @param lon Longitude (required) - * @param lang Set preferred language (e.g. \"default\", \"en\", \"de\", \"fr\") (optional) - * @param limit Limit number of results (optional) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call reverseGeocodingReverseGetCall(BigDecimal lat, BigDecimal lon, String lang, Integer limit, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/reverse"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - if (lat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lat", lat)); - } - - if (lon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lon", lon)); - } - - if (lang != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lang", lang)); - } - - if (limit != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("limit", limit)); - } - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call reverseGeocodingReverseGetValidateBeforeCall(BigDecimal lat, BigDecimal lon, String lang, Integer limit, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'lat' is set - if (lat == null) { - throw new ApiException("Missing the required parameter 'lat' when calling reverseGeocodingReverseGet(Async)"); - } - - // verify the required parameter 'lon' is set - if (lon == null) { - throw new ApiException("Missing the required parameter 'lon' when calling reverseGeocodingReverseGet(Async)"); - } - - return reverseGeocodingReverseGetCall(lat, lon, lang, limit, _callback); - - } - - /** - * Reverse Geocoding - * Returns a GeoJSON FeatureCollection of places near the provided coordinate - * @param lat Latitude (required) - * @param lon Longitude (required) - * @param lang Set preferred language (e.g. \"default\", \"en\", \"de\", \"fr\") (optional) - * @param limit Limit number of results (optional) - * @return FeatureCollection - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public FeatureCollection getReverseGeocoding(BigDecimal lat, BigDecimal lon, String lang, Integer limit) throws ApiException { - ApiResponse localVarResp = reverseGeocodingReverseGetWithHttpInfo(lat, lon, lang, limit); - return localVarResp.getData(); - } - - - /** - * Reverse Geocoding - * Returns a GeoJSON FeatureCollection of places near the provided coordinate - * @param lat Latitude (required) - * @param lon Longitude (required) - * @param lang Set preferred language (e.g. \"default\", \"en\", \"de\", \"fr\") (optional) - * @param limit Limit number of results (optional) - * @return ApiResponse<FeatureCollection> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public ApiResponse reverseGeocodingReverseGetWithHttpInfo(BigDecimal lat, BigDecimal lon, String lang, Integer limit) throws ApiException { - okhttp3.Call localVarCall = reverseGeocodingReverseGetValidateBeforeCall(lat, lon, lang, limit, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Reverse Geocoding (asynchronously) - * Returns a GeoJSON FeatureCollection of places near the provided coordinate - * @param lat Latitude (required) - * @param lon Longitude (required) - * @param lang Set preferred language (e.g. \"default\", \"en\", \"de\", \"fr\") (optional) - * @param limit Limit number of results (optional) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call getReverseGeocodingAsync(BigDecimal lat, BigDecimal lon, String lang, Integer limit, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = reverseGeocodingReverseGetValidateBeforeCall(lat, lon, lang, limit, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } -} diff --git a/src/main/java/io/openepi/geocoding/api/HealthApi.java b/src/main/java/io/openepi/geocoding/api/HealthApi.java deleted file mode 100644 index 9b2c00f..0000000 --- a/src/main/java/io/openepi/geocoding/api/HealthApi.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.geocoding.api; - -import io.openepi.geocoding.ApiClient; -import io.openepi.geocoding.Configuration; -import io.openepi.common.ApiCallback; -import io.openepi.common.ApiException; -import io.openepi.common.ApiResponse; -import io.openepi.common.Pair; -import io.openepi.common.ProgressRequestBody; -import io.openepi.common.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class HealthApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public HealthApi() { - this(Configuration.getDefaultApiClient()); - } - - public HealthApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for livenessHealthGet - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call livenessHealthGetCall(final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/health"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call livenessHealthGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { - return livenessHealthGetCall(_callback); - - } - - /** - * Liveness - * - * @return Map<String, String> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public Map livenessHealthGet() throws ApiException { - ApiResponse> localVarResp = livenessHealthGetWithHttpInfo(); - return localVarResp.getData(); - } - - /** - * Liveness - * - * @return ApiResponse<Map<String, String>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public ApiResponse> livenessHealthGetWithHttpInfo() throws ApiException { - okhttp3.Call localVarCall = livenessHealthGetValidateBeforeCall(null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Liveness (asynchronously) - * - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call livenessHealthGetAsync(final ApiCallback> _callback) throws ApiException { - - okhttp3.Call localVarCall = livenessHealthGetValidateBeforeCall(_callback); - Type localVarReturnType = new TypeToken>(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for readinessReadyGet - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call readinessReadyGetCall(final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/ready"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call readinessReadyGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { - return readinessReadyGetCall(_callback); - - } - - /** - * Readiness - * - * @return Object - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public Object readinessReadyGet() throws ApiException { - ApiResponse localVarResp = readinessReadyGetWithHttpInfo(); - return localVarResp.getData(); - } - - /** - * Readiness - * - * @return ApiResponse<Object> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public ApiResponse readinessReadyGetWithHttpInfo() throws ApiException { - okhttp3.Call localVarCall = readinessReadyGetValidateBeforeCall(null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Readiness (asynchronously) - * - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call readinessReadyGetAsync(final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = readinessReadyGetValidateBeforeCall(_callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } -} diff --git a/src/main/java/io/openepi/geocoding/model/AbstractOpenApiSchema.java b/src/main/java/io/openepi/geocoding/model/AbstractOpenApiSchema.java deleted file mode 100644 index 05ce699..0000000 --- a/src/main/java/io/openepi/geocoding/model/AbstractOpenApiSchema.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.geocoding.model; - -import io.openepi.common.ApiException; -import java.util.Objects; -import java.lang.reflect.Type; -import java.util.Map; - -/** - * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public abstract class AbstractOpenApiSchema { - - // store the actual instance of the schema/object - private Object instance; - - // is nullable - private Boolean isNullable; - - // schema type (e.g. oneOf, anyOf) - private final String schemaType; - - public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { - this.schemaType = schemaType; - this.isNullable = isNullable; - } - - /** - * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object - * - * @return an instance of the actual schema/object - */ - public abstract Map> getSchemas(); - - /** - * Get the actual instance - * - * @return an instance of the actual schema/object - */ - //@JsonValue - public Object getActualInstance() {return instance;} - - /** - * Set the actual instance - * - * @param instance the actual instance of the schema/object - */ - public void setActualInstance(Object instance) {this.instance = instance;} - - /** - * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well - * - * @return an instance of the actual schema/object - */ - public Object getActualInstanceRecursively() { - return getActualInstanceRecursively(this); - } - - private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { - if (object.getActualInstance() == null) { - return null; - } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { - return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); - } else { - return object.getActualInstance(); - } - } - - /** - * Get the schema type (e.g. anyOf, oneOf) - * - * @return the schema type - */ - public String getSchemaType() { - return schemaType; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ").append(getClass()).append(" {\n"); - sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); - sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); - sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; - return Objects.equals(this.instance, a.instance) && - Objects.equals(this.isNullable, a.isNullable) && - Objects.equals(this.schemaType, a.schemaType); - } - - @Override - public int hashCode() { - return Objects.hash(instance, isNullable, schemaType); - } - - /** - * Is nullable - * - * @return true if it's nullable - */ - public Boolean isNullable() { - if (Boolean.TRUE.equals(isNullable)) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } - - - -} diff --git a/src/main/java/io/openepi/geocoding/model/Feature.java b/src/main/java/io/openepi/geocoding/model/Feature.java index e01acb2..3e6f298 100644 --- a/src/main/java/io/openepi/geocoding/model/Feature.java +++ b/src/main/java/io/openepi/geocoding/model/Feature.java @@ -1,269 +1,33 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - package io.openepi.geocoding.model; -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.geocoding.model.Geometry; -import io.openepi.geocoding.model.Properties; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.geocoding.JSON; - -/** - * Feature - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") public class Feature { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_GEOMETRY = "geometry"; - @SerializedName(SERIALIZED_NAME_GEOMETRY) - private Geometry geometry; - - public static final String SERIALIZED_NAME_PROPERTIES = "properties"; - @SerializedName(SERIALIZED_NAME_PROPERTIES) - private Properties properties; - - public Feature() { - } - - public Feature type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public Feature geometry(Geometry geometry) { - this.geometry = geometry; - return this; - } - - /** - * Get geometry - * @return geometry - */ - @javax.annotation.Nonnull - public Geometry getGeometry() { - return geometry; - } - - public void setGeometry(Geometry geometry) { - this.geometry = geometry; - } - - - public Feature properties(Properties properties) { - this.properties = properties; - return this; - } - - /** - * Get properties - * @return properties - */ - @javax.annotation.Nonnull - public Properties getProperties() { - return properties; - } - - public void setProperties(Properties properties) { - this.properties = properties; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + private String type; + private Geometry geometry; + private Properties properties; + + public String getType() { return type; } + public Geometry getGeometry() { return geometry; } + public Properties getProperties() { return properties; } + + public Feature(Geometry geometry, Properties properties) { + this.type = "Feature"; + this.geometry = geometry; + this.properties = properties; } - if (o == null || getClass() != o.getClass()) { - return false; - } - Feature feature = (Feature) o; - return Objects.equals(this.type, feature.type) && - Objects.equals(this.geometry, feature.geometry) && - Objects.equals(this.properties, feature.properties); - } - - @Override - public int hashCode() { - return Objects.hash(type, geometry, properties); - } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Feature {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" geometry: ").append(toIndentedString(geometry)).append("\n"); - sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; + public Feature() { + this.type = "Feature"; } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("geometry"); - openapiFields.add("properties"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("geometry"); - openapiRequiredFields.add("properties"); - } - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to Feature - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!Feature.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in Feature is not found in the empty JSON string", Feature.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!Feature.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Feature` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : Feature.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `geometry` - Geometry.validateJsonElement(jsonObj.get("geometry")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!Feature.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'Feature' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(Feature.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, Feature value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public Feature read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); + public void setType(String type) { + this.type = type; } - } - - /** - * Create an instance of Feature given an JSON string - * - * @param jsonString JSON string - * @return An instance of Feature - * @throws IOException if the JSON string is invalid with respect to Feature - */ - public static Feature fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, Feature.class); - } - /** - * Convert an instance of Feature to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} + public void setGeometry(Geometry geometry) { + this.geometry = geometry; + } + public void setProperties(Properties properties) { + this.properties = properties; + } +} \ No newline at end of file diff --git a/src/main/java/io/openepi/geocoding/model/FeatureCollection.java b/src/main/java/io/openepi/geocoding/model/FeatureCollection.java index 9e59492..ef38efa 100644 --- a/src/main/java/io/openepi/geocoding/model/FeatureCollection.java +++ b/src/main/java/io/openepi/geocoding/model/FeatureCollection.java @@ -1,259 +1,24 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - package io.openepi.geocoding.model; -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.geocoding.model.Feature; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Set; -import io.openepi.geocoding.JSON; - -/** - * FeatureCollection - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") public class FeatureCollection { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_FEATURES = "features"; - @SerializedName(SERIALIZED_NAME_FEATURES) - private List features = new ArrayList<>(); - - public FeatureCollection() { - } - - public FeatureCollection type(Object type) { - this.type = type; - return this; - } + private String type; + private List features; - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } + public String getType() { return type; } + public List getFeatures() { return features; } - public void setType(Object type) { - this.type = type; - } - - - public FeatureCollection features(List features) { - this.features = features; - return this; - } - - public FeatureCollection addFeaturesItem(Feature featuresItem) { - if (this.features == null) { - this.features = new ArrayList<>(); + public FeatureCollection(List features) { + this(); + this.features = features; } - this.features.add(featuresItem); - return this; - } - - /** - * Get features - * @return features - */ - @javax.annotation.Nonnull - public List getFeatures() { - return features; - } - - public void setFeatures(List features) { - this.features = features; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + public FeatureCollection() { + this.type = "FeatureCollection"; } - if (o == null || getClass() != o.getClass()) { - return false; - } - FeatureCollection featureCollection = (FeatureCollection) o; - return Objects.equals(this.type, featureCollection.type) && - Objects.equals(this.features, featureCollection.features); - } - - @Override - public int hashCode() { - return Objects.hash(type, features); - } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class FeatureCollection {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" features: ").append(toIndentedString(features)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; + public void setFeatures(List features) { + this.features = features; } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("features"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("features"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to FeatureCollection - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!FeatureCollection.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in FeatureCollection is not found in the empty JSON string", FeatureCollection.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!FeatureCollection.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `FeatureCollection` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : FeatureCollection.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the json data is an array - if (!jsonObj.get("features").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `features` to be an array in the JSON string but got `%s`", jsonObj.get("features").toString())); - } - - JsonArray jsonArrayfeatures = jsonObj.getAsJsonArray("features"); - // validate the required field `features` (array) - for (int i = 0; i < jsonArrayfeatures.size(); i++) { - Feature.validateJsonElement(jsonArrayfeatures.get(i)); - }; - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!FeatureCollection.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'FeatureCollection' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(FeatureCollection.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, FeatureCollection value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public FeatureCollection read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of FeatureCollection given an JSON string - * - * @param jsonString JSON string - * @return An instance of FeatureCollection - * @throws IOException if the JSON string is invalid with respect to FeatureCollection - */ - public static FeatureCollection fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, FeatureCollection.class); - } - - /** - * Convert an instance of FeatureCollection to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - +} \ No newline at end of file diff --git a/src/main/java/io/openepi/geocoding/model/GeocodeException.java b/src/main/java/io/openepi/geocoding/model/GeocodeException.java new file mode 100644 index 0000000..f9a3f2c --- /dev/null +++ b/src/main/java/io/openepi/geocoding/model/GeocodeException.java @@ -0,0 +1,11 @@ +package io.openepi.geocoding.model; + +public class GeocodeException extends RuntimeException { + public GeocodeException(Throwable cause) { + super(cause); + } + + public GeocodeException(String message) { + super(message); + } +} diff --git a/src/main/java/io/openepi/geocoding/model/Geometry.java b/src/main/java/io/openepi/geocoding/model/Geometry.java index 6c970c4..463870c 100644 --- a/src/main/java/io/openepi/geocoding/model/Geometry.java +++ b/src/main/java/io/openepi/geocoding/model/Geometry.java @@ -1,448 +1,5 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - package io.openepi.geocoding.model; -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.geocoding.model.LineString; -import io.openepi.geocoding.model.MultiLineString; -import io.openepi.geocoding.model.MultiPoint; -import io.openepi.geocoding.model.MultiPolygon; -import io.openepi.geocoding.model.Point; -import io.openepi.geocoding.model.Polygon; - - - -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.JsonPrimitive; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonParseException; - -import io.openepi.geocoding.JSON; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class Geometry extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(Geometry.class.getName()); - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!Geometry.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'Geometry' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter adapterPoint = gson.getDelegateAdapter(this, TypeToken.get(Point.class)); - final TypeAdapter adapterMultiPoint = gson.getDelegateAdapter(this, TypeToken.get(MultiPoint.class)); - final TypeAdapter adapterLineString = gson.getDelegateAdapter(this, TypeToken.get(LineString.class)); - final TypeAdapter adapterMultiLineString = gson.getDelegateAdapter(this, TypeToken.get(MultiLineString.class)); - final TypeAdapter adapterPolygon = gson.getDelegateAdapter(this, TypeToken.get(Polygon.class)); - final TypeAdapter adapterMultiPolygon = gson.getDelegateAdapter(this, TypeToken.get(MultiPolygon.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, Geometry value) throws IOException { - if (value == null || value.getActualInstance() == null) { - elementAdapter.write(out, null); - return; - } - - // check if the actual instance is of the type `Point` - if (value.getActualInstance() instanceof Point) { - JsonElement element = adapterPoint.toJsonTree((Point)value.getActualInstance()); - elementAdapter.write(out, element); - return; - } - // check if the actual instance is of the type `MultiPoint` - if (value.getActualInstance() instanceof MultiPoint) { - JsonElement element = adapterMultiPoint.toJsonTree((MultiPoint)value.getActualInstance()); - elementAdapter.write(out, element); - return; - } - // check if the actual instance is of the type `LineString` - if (value.getActualInstance() instanceof LineString) { - JsonElement element = adapterLineString.toJsonTree((LineString)value.getActualInstance()); - elementAdapter.write(out, element); - return; - } - // check if the actual instance is of the type `MultiLineString` - if (value.getActualInstance() instanceof MultiLineString) { - JsonElement element = adapterMultiLineString.toJsonTree((MultiLineString)value.getActualInstance()); - elementAdapter.write(out, element); - return; - } - // check if the actual instance is of the type `Polygon` - if (value.getActualInstance() instanceof Polygon) { - JsonElement element = adapterPolygon.toJsonTree((Polygon)value.getActualInstance()); - elementAdapter.write(out, element); - return; - } - // check if the actual instance is of the type `MultiPolygon` - if (value.getActualInstance() instanceof MultiPolygon) { - JsonElement element = adapterMultiPolygon.toJsonTree((MultiPolygon)value.getActualInstance()); - elementAdapter.write(out, element); - return; - } - throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon"); - } - - @Override - public Geometry read(JsonReader in) throws IOException { - Object deserialized = null; - JsonElement jsonElement = elementAdapter.read(in); - - ArrayList errorMessages = new ArrayList<>(); - TypeAdapter actualAdapter = elementAdapter; - - // deserialize Point - try { - // validate the JSON object to see if any exception is thrown - Point.validateJsonElement(jsonElement); - actualAdapter = adapterPoint; - Geometry ret = new Geometry(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for Point failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'Point'", e); - } - // deserialize MultiPoint - try { - // validate the JSON object to see if any exception is thrown - MultiPoint.validateJsonElement(jsonElement); - actualAdapter = adapterMultiPoint; - Geometry ret = new Geometry(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for MultiPoint failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'MultiPoint'", e); - } - // deserialize LineString - try { - // validate the JSON object to see if any exception is thrown - LineString.validateJsonElement(jsonElement); - actualAdapter = adapterLineString; - Geometry ret = new Geometry(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for LineString failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'LineString'", e); - } - // deserialize MultiLineString - try { - // validate the JSON object to see if any exception is thrown - MultiLineString.validateJsonElement(jsonElement); - actualAdapter = adapterMultiLineString; - Geometry ret = new Geometry(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for MultiLineString failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'MultiLineString'", e); - } - // deserialize Polygon - try { - // validate the JSON object to see if any exception is thrown - Polygon.validateJsonElement(jsonElement); - actualAdapter = adapterPolygon; - Geometry ret = new Geometry(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for Polygon failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'Polygon'", e); - } - // deserialize MultiPolygon - try { - // validate the JSON object to see if any exception is thrown - MultiPolygon.validateJsonElement(jsonElement); - actualAdapter = adapterMultiPolygon; - Geometry ret = new Geometry(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for MultiPolygon failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'MultiPolygon'", e); - } - - throw new IOException(String.format("Failed deserialization for Geometry: no class matches result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); - } - }.nullSafe(); - } - } - - // store a list of schema names defined in anyOf - public static final Map> schemas = new HashMap>(); - - public Geometry() { - super("anyOf", Boolean.FALSE); - } - - public Geometry(Object o) { - super("anyOf", Boolean.FALSE); - setActualInstance(o); - } - - static { - schemas.put("Point", Point.class); - schemas.put("MultiPoint", MultiPoint.class); - schemas.put("LineString", LineString.class); - schemas.put("MultiLineString", MultiLineString.class); - schemas.put("Polygon", Polygon.class); - schemas.put("MultiPolygon", MultiPolygon.class); - } - - @Override - public Map> getSchemas() { - return Geometry.schemas; - } - - /** - * Set the instance that matches the anyOf child schema, check - * the instance parameter is valid against the anyOf child schemas: - * LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon - * - * It could be an instance of the 'anyOf' schemas. - */ - @Override - public void setActualInstance(Object instance) { - if (instance instanceof Point) { - super.setActualInstance(instance); - return; - } - - if (instance instanceof MultiPoint) { - super.setActualInstance(instance); - return; - } - - if (instance instanceof LineString) { - super.setActualInstance(instance); - return; - } - - if (instance instanceof MultiLineString) { - super.setActualInstance(instance); - return; - } - - if (instance instanceof Polygon) { - super.setActualInstance(instance); - return; - } - - if (instance instanceof MultiPolygon) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon"); - } - - /** - * Get the actual instance, which can be the following: - * LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon - * - * @return The actual instance (LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon) - */ - @SuppressWarnings("unchecked") - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `Point`. If the actual instance is not `Point`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Point` - * @throws ClassCastException if the instance is not `Point` - */ - public Point getPoint() throws ClassCastException { - return (Point)super.getActualInstance(); - } - /** - * Get the actual instance of `MultiPoint`. If the actual instance is not `MultiPoint`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `MultiPoint` - * @throws ClassCastException if the instance is not `MultiPoint` - */ - public MultiPoint getMultiPoint() throws ClassCastException { - return (MultiPoint)super.getActualInstance(); - } - /** - * Get the actual instance of `LineString`. If the actual instance is not `LineString`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `LineString` - * @throws ClassCastException if the instance is not `LineString` - */ - public LineString getLineString() throws ClassCastException { - return (LineString)super.getActualInstance(); - } - /** - * Get the actual instance of `MultiLineString`. If the actual instance is not `MultiLineString`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `MultiLineString` - * @throws ClassCastException if the instance is not `MultiLineString` - */ - public MultiLineString getMultiLineString() throws ClassCastException { - return (MultiLineString)super.getActualInstance(); - } - /** - * Get the actual instance of `Polygon`. If the actual instance is not `Polygon`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Polygon` - * @throws ClassCastException if the instance is not `Polygon` - */ - public Polygon getPolygon() throws ClassCastException { - return (Polygon)super.getActualInstance(); - } - /** - * Get the actual instance of `MultiPolygon`. If the actual instance is not `MultiPolygon`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `MultiPolygon` - * @throws ClassCastException if the instance is not `MultiPolygon` - */ - public MultiPolygon getMultiPolygon() throws ClassCastException { - return (MultiPolygon)super.getActualInstance(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to Geometry - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - // validate anyOf schemas one by one - ArrayList errorMessages = new ArrayList<>(); - // validate the json string with Point - try { - Point.validateJsonElement(jsonElement); - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for Point failed with `%s`.", e.getMessage())); - // continue to the next one - } - // validate the json string with MultiPoint - try { - MultiPoint.validateJsonElement(jsonElement); - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for MultiPoint failed with `%s`.", e.getMessage())); - // continue to the next one - } - // validate the json string with LineString - try { - LineString.validateJsonElement(jsonElement); - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for LineString failed with `%s`.", e.getMessage())); - // continue to the next one - } - // validate the json string with MultiLineString - try { - MultiLineString.validateJsonElement(jsonElement); - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for MultiLineString failed with `%s`.", e.getMessage())); - // continue to the next one - } - // validate the json string with Polygon - try { - Polygon.validateJsonElement(jsonElement); - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for Polygon failed with `%s`.", e.getMessage())); - // continue to the next one - } - // validate the json string with MultiPolygon - try { - MultiPolygon.validateJsonElement(jsonElement); - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for MultiPolygon failed with `%s`.", e.getMessage())); - // continue to the next one - } - throw new IOException(String.format("The JSON string is invalid for Geometry with anyOf schemas: LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon. no class match the result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); - } - - /** - * Create an instance of Geometry given an JSON string - * - * @param jsonString JSON string - * @return An instance of Geometry - * @throws IOException if the JSON string is invalid with respect to Geometry - */ - public static Geometry fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, Geometry.class); - } - - /** - * Convert an instance of Geometry to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - +public interface Geometry { + String getType(); +} \ No newline at end of file diff --git a/src/main/java/io/openepi/geocoding/model/HTTPValidationError.java b/src/main/java/io/openepi/geocoding/model/HTTPValidationError.java deleted file mode 100644 index 72f0bf6..0000000 --- a/src/main/java/io/openepi/geocoding/model/HTTPValidationError.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.geocoding.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.geocoding.model.ValidationError; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.geocoding.JSON; - -/** - * HTTPValidationError - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class HTTPValidationError { - public static final String SERIALIZED_NAME_DETAIL = "detail"; - @SerializedName(SERIALIZED_NAME_DETAIL) - private List detail = new ArrayList<>(); - - public HTTPValidationError() { - } - - public HTTPValidationError detail(List detail) { - this.detail = detail; - return this; - } - - public HTTPValidationError addDetailItem(ValidationError detailItem) { - if (this.detail == null) { - this.detail = new ArrayList<>(); - } - this.detail.add(detailItem); - return this; - } - - /** - * Get detail - * @return detail - */ - @javax.annotation.Nullable - public List getDetail() { - return detail; - } - - public void setDetail(List detail) { - this.detail = detail; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - HTTPValidationError htTPValidationError = (HTTPValidationError) o; - return Objects.equals(this.detail, htTPValidationError.detail); - } - - @Override - public int hashCode() { - return Objects.hash(detail); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class HTTPValidationError {\n"); - sb.append(" detail: ").append(toIndentedString(detail)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("detail"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to HTTPValidationError - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!HTTPValidationError.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in HTTPValidationError is not found in the empty JSON string", HTTPValidationError.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!HTTPValidationError.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `HTTPValidationError` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("detail") != null && !jsonObj.get("detail").isJsonNull()) { - JsonArray jsonArraydetail = jsonObj.getAsJsonArray("detail"); - if (jsonArraydetail != null) { - // ensure the json data is an array - if (!jsonObj.get("detail").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `detail` to be an array in the JSON string but got `%s`", jsonObj.get("detail").toString())); - } - - // validate the optional field `detail` (array) - for (int i = 0; i < jsonArraydetail.size(); i++) { - ValidationError.validateJsonElement(jsonArraydetail.get(i)); - }; - } - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!HTTPValidationError.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'HTTPValidationError' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(HTTPValidationError.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, HTTPValidationError value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public HTTPValidationError read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of HTTPValidationError given an JSON string - * - * @param jsonString JSON string - * @return An instance of HTTPValidationError - * @throws IOException if the JSON string is invalid with respect to HTTPValidationError - */ - public static HTTPValidationError fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, HTTPValidationError.class); - } - - /** - * Convert an instance of HTTPValidationError to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/geocoding/model/LineString.java b/src/main/java/io/openepi/geocoding/model/LineString.java index 0663ead..bdbf672 100644 --- a/src/main/java/io/openepi/geocoding/model/LineString.java +++ b/src/main/java/io/openepi/geocoding/model/LineString.java @@ -1,254 +1,11 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - package io.openepi.geocoding.model; -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.geocoding.JSON; - -/** - * LineString - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class LineString { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_COORDINATES = "coordinates"; - @SerializedName(SERIALIZED_NAME_COORDINATES) - private List> coordinates = new ArrayList<>(); - - public LineString() { - } - - public LineString type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public LineString coordinates(List> coordinates) { - this.coordinates = coordinates; - return this; - } - - public LineString addCoordinatesItem(List coordinatesItem) { - if (this.coordinates == null) { - this.coordinates = new ArrayList<>(); - } - this.coordinates.add(coordinatesItem); - return this; - } - - /** - * Get coordinates - * @return coordinates - */ - @javax.annotation.Nonnull - public List> getCoordinates() { - return coordinates; - } - - public void setCoordinates(List> coordinates) { - this.coordinates = coordinates; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - LineString lineString = (LineString) o; - return Objects.equals(this.type, lineString.type) && - Objects.equals(this.coordinates, lineString.coordinates); - } - - @Override - public int hashCode() { - return Objects.hash(type, coordinates); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class LineString {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" coordinates: ").append(toIndentedString(coordinates)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("coordinates"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("coordinates"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to LineString - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!LineString.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in LineString is not found in the empty JSON string", LineString.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!LineString.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `LineString` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : LineString.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the required json array is present - if (jsonObj.get("coordinates") == null) { - throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); - } else if (!jsonObj.get("coordinates").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `coordinates` to be an array in the JSON string but got `%s`", jsonObj.get("coordinates").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!LineString.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'LineString' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(LineString.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, LineString value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public LineString read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of LineString given an JSON string - * - * @param jsonString JSON string - * @return An instance of LineString - * @throws IOException if the JSON string is invalid with respect to LineString - */ - public static LineString fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, LineString.class); - } - /** - * Convert an instance of LineString to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} +public class LineString implements Geometry { + private String type; + private List> coordinates; + @Override public String getType() { return type; } + public List> getCoordinates() { return coordinates; } +} \ No newline at end of file diff --git a/src/main/java/io/openepi/geocoding/model/MultiLineString.java b/src/main/java/io/openepi/geocoding/model/MultiLineString.java index c969379..6e36816 100644 --- a/src/main/java/io/openepi/geocoding/model/MultiLineString.java +++ b/src/main/java/io/openepi/geocoding/model/MultiLineString.java @@ -1,254 +1,11 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - package io.openepi.geocoding.model; -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.geocoding.JSON; - -/** - * MultiLineString - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class MultiLineString { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_COORDINATES = "coordinates"; - @SerializedName(SERIALIZED_NAME_COORDINATES) - private List>> coordinates = new ArrayList<>(); - - public MultiLineString() { - } - - public MultiLineString type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public MultiLineString coordinates(List>> coordinates) { - this.coordinates = coordinates; - return this; - } - - public MultiLineString addCoordinatesItem(List> coordinatesItem) { - if (this.coordinates == null) { - this.coordinates = new ArrayList<>(); - } - this.coordinates.add(coordinatesItem); - return this; - } - - /** - * Get coordinates - * @return coordinates - */ - @javax.annotation.Nonnull - public List>> getCoordinates() { - return coordinates; - } - - public void setCoordinates(List>> coordinates) { - this.coordinates = coordinates; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MultiLineString multiLineString = (MultiLineString) o; - return Objects.equals(this.type, multiLineString.type) && - Objects.equals(this.coordinates, multiLineString.coordinates); - } - - @Override - public int hashCode() { - return Objects.hash(type, coordinates); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class MultiLineString {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" coordinates: ").append(toIndentedString(coordinates)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("coordinates"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("coordinates"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to MultiLineString - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!MultiLineString.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in MultiLineString is not found in the empty JSON string", MultiLineString.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!MultiLineString.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `MultiLineString` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : MultiLineString.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the required json array is present - if (jsonObj.get("coordinates") == null) { - throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); - } else if (!jsonObj.get("coordinates").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `coordinates` to be an array in the JSON string but got `%s`", jsonObj.get("coordinates").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!MultiLineString.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'MultiLineString' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(MultiLineString.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, MultiLineString value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public MultiLineString read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of MultiLineString given an JSON string - * - * @param jsonString JSON string - * @return An instance of MultiLineString - * @throws IOException if the JSON string is invalid with respect to MultiLineString - */ - public static MultiLineString fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, MultiLineString.class); - } - /** - * Convert an instance of MultiLineString to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} +public class MultiLineString implements Geometry { + private String type; + private List>> coordinates; + @Override public String getType() { return type; } + public List>> getCoordinates() { return coordinates; } +} \ No newline at end of file diff --git a/src/main/java/io/openepi/geocoding/model/MultiPoint.java b/src/main/java/io/openepi/geocoding/model/MultiPoint.java index f528f85..e03ae2b 100644 --- a/src/main/java/io/openepi/geocoding/model/MultiPoint.java +++ b/src/main/java/io/openepi/geocoding/model/MultiPoint.java @@ -1,254 +1,11 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - package io.openepi.geocoding.model; -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.geocoding.JSON; - -/** - * MultiPoint - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class MultiPoint { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_COORDINATES = "coordinates"; - @SerializedName(SERIALIZED_NAME_COORDINATES) - private List> coordinates = new ArrayList<>(); - - public MultiPoint() { - } - - public MultiPoint type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public MultiPoint coordinates(List> coordinates) { - this.coordinates = coordinates; - return this; - } - - public MultiPoint addCoordinatesItem(List coordinatesItem) { - if (this.coordinates == null) { - this.coordinates = new ArrayList<>(); - } - this.coordinates.add(coordinatesItem); - return this; - } - - /** - * Get coordinates - * @return coordinates - */ - @javax.annotation.Nonnull - public List> getCoordinates() { - return coordinates; - } - - public void setCoordinates(List> coordinates) { - this.coordinates = coordinates; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MultiPoint multiPoint = (MultiPoint) o; - return Objects.equals(this.type, multiPoint.type) && - Objects.equals(this.coordinates, multiPoint.coordinates); - } - - @Override - public int hashCode() { - return Objects.hash(type, coordinates); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class MultiPoint {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" coordinates: ").append(toIndentedString(coordinates)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("coordinates"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("coordinates"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to MultiPoint - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!MultiPoint.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in MultiPoint is not found in the empty JSON string", MultiPoint.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!MultiPoint.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `MultiPoint` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : MultiPoint.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the required json array is present - if (jsonObj.get("coordinates") == null) { - throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); - } else if (!jsonObj.get("coordinates").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `coordinates` to be an array in the JSON string but got `%s`", jsonObj.get("coordinates").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!MultiPoint.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'MultiPoint' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(MultiPoint.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, MultiPoint value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public MultiPoint read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of MultiPoint given an JSON string - * - * @param jsonString JSON string - * @return An instance of MultiPoint - * @throws IOException if the JSON string is invalid with respect to MultiPoint - */ - public static MultiPoint fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, MultiPoint.class); - } - /** - * Convert an instance of MultiPoint to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} +public class MultiPoint implements Geometry { + private String type; + private List> coordinates; + @Override public String getType() { return type; } + public List> getCoordinates() { return coordinates; } +} \ No newline at end of file diff --git a/src/main/java/io/openepi/geocoding/model/MultiPolygon.java b/src/main/java/io/openepi/geocoding/model/MultiPolygon.java index dbd0896..ae8a7a7 100644 --- a/src/main/java/io/openepi/geocoding/model/MultiPolygon.java +++ b/src/main/java/io/openepi/geocoding/model/MultiPolygon.java @@ -1,254 +1,11 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - package io.openepi.geocoding.model; -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.geocoding.JSON; - -/** - * MultiPolygon - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class MultiPolygon { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_COORDINATES = "coordinates"; - @SerializedName(SERIALIZED_NAME_COORDINATES) - private List>>> coordinates = new ArrayList<>(); - - public MultiPolygon() { - } - - public MultiPolygon type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public MultiPolygon coordinates(List>>> coordinates) { - this.coordinates = coordinates; - return this; - } - - public MultiPolygon addCoordinatesItem(List>> coordinatesItem) { - if (this.coordinates == null) { - this.coordinates = new ArrayList<>(); - } - this.coordinates.add(coordinatesItem); - return this; - } - - /** - * Get coordinates - * @return coordinates - */ - @javax.annotation.Nonnull - public List>>> getCoordinates() { - return coordinates; - } - - public void setCoordinates(List>>> coordinates) { - this.coordinates = coordinates; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MultiPolygon multiPolygon = (MultiPolygon) o; - return Objects.equals(this.type, multiPolygon.type) && - Objects.equals(this.coordinates, multiPolygon.coordinates); - } - - @Override - public int hashCode() { - return Objects.hash(type, coordinates); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class MultiPolygon {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" coordinates: ").append(toIndentedString(coordinates)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("coordinates"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("coordinates"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to MultiPolygon - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!MultiPolygon.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in MultiPolygon is not found in the empty JSON string", MultiPolygon.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!MultiPolygon.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `MultiPolygon` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : MultiPolygon.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the required json array is present - if (jsonObj.get("coordinates") == null) { - throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); - } else if (!jsonObj.get("coordinates").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `coordinates` to be an array in the JSON string but got `%s`", jsonObj.get("coordinates").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!MultiPolygon.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'MultiPolygon' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(MultiPolygon.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, MultiPolygon value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public MultiPolygon read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of MultiPolygon given an JSON string - * - * @param jsonString JSON string - * @return An instance of MultiPolygon - * @throws IOException if the JSON string is invalid with respect to MultiPolygon - */ - public static MultiPolygon fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, MultiPolygon.class); - } - /** - * Convert an instance of MultiPolygon to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} +public class MultiPolygon implements Geometry { + private String type; + private List>>> coordinates; + @Override public String getType() { return type; } + public List>>> getCoordinates() { return coordinates; } +} \ No newline at end of file diff --git a/src/main/java/io/openepi/geocoding/model/Point.java b/src/main/java/io/openepi/geocoding/model/Point.java index 746a090..7cdc401 100644 --- a/src/main/java/io/openepi/geocoding/model/Point.java +++ b/src/main/java/io/openepi/geocoding/model/Point.java @@ -1,254 +1,23 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - package io.openepi.geocoding.model; -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.geocoding.JSON; - -/** - * Point - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class Point { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_COORDINATES = "coordinates"; - @SerializedName(SERIALIZED_NAME_COORDINATES) - private List coordinates = new ArrayList<>(); - - public Point() { - } - public Point type(Object type) { - this.type = type; - return this; - } +public class Point implements Geometry { + private String type; + private List coordinates; - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } + @Override public String getType() { return type; } + public List getCoordinates() { return coordinates; } - public void setType(Object type) { - this.type = type; - } + public void setType(String type) { this.type = type; } + public void setCoordinates(List coordinates) { this.coordinates = coordinates; } - - public Point coordinates(List coordinates) { - this.coordinates = coordinates; - return this; - } - - public Point addCoordinatesItem(String coordinatesItem) { - if (this.coordinates == null) { - this.coordinates = new ArrayList<>(); + public Point(List coordinates) { + this.type = "Point"; + this.coordinates = coordinates; } - this.coordinates.add(coordinatesItem); - return this; - } - - /** - * Coordinates in the format (lon, lat) - * @return coordinates - */ - @javax.annotation.Nonnull - public List getCoordinates() { - return coordinates; - } - - public void setCoordinates(List coordinates) { - this.coordinates = coordinates; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; + public Point() { + this.type = "Point"; } - Point point = (Point) o; - return Objects.equals(this.type, point.type) && - Objects.equals(this.coordinates, point.coordinates); - } - - @Override - public int hashCode() { - return Objects.hash(type, coordinates); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Point {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" coordinates: ").append(toIndentedString(coordinates)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("coordinates"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("coordinates"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to Point - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!Point.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in Point is not found in the empty JSON string", Point.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!Point.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Point` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : Point.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the required json array is present - if (jsonObj.get("coordinates") == null) { - throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); - } else if (!jsonObj.get("coordinates").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `coordinates` to be an array in the JSON string but got `%s`", jsonObj.get("coordinates").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!Point.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'Point' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(Point.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, Point value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public Point read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of Point given an JSON string - * - * @param jsonString JSON string - * @return An instance of Point - * @throws IOException if the JSON string is invalid with respect to Point - */ - public static Point fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, Point.class); - } - - /** - * Convert an instance of Point to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - +} \ No newline at end of file diff --git a/src/main/java/io/openepi/geocoding/model/Polygon.java b/src/main/java/io/openepi/geocoding/model/Polygon.java index e773866..789a93b 100644 --- a/src/main/java/io/openepi/geocoding/model/Polygon.java +++ b/src/main/java/io/openepi/geocoding/model/Polygon.java @@ -1,254 +1,11 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - package io.openepi.geocoding.model; -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.geocoding.JSON; - -/** - * Polygon - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class Polygon { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type = null; - - public static final String SERIALIZED_NAME_COORDINATES = "coordinates"; - @SerializedName(SERIALIZED_NAME_COORDINATES) - private List>> coordinates = new ArrayList<>(); - - public Polygon() { - } - - public Polygon type(Object type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public Polygon coordinates(List>> coordinates) { - this.coordinates = coordinates; - return this; - } - - public Polygon addCoordinatesItem(List> coordinatesItem) { - if (this.coordinates == null) { - this.coordinates = new ArrayList<>(); - } - this.coordinates.add(coordinatesItem); - return this; - } - - /** - * Get coordinates - * @return coordinates - */ - @javax.annotation.Nonnull - public List>> getCoordinates() { - return coordinates; - } - - public void setCoordinates(List>> coordinates) { - this.coordinates = coordinates; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Polygon polygon = (Polygon) o; - return Objects.equals(this.type, polygon.type) && - Objects.equals(this.coordinates, polygon.coordinates); - } - - @Override - public int hashCode() { - return Objects.hash(type, coordinates); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Polygon {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" coordinates: ").append(toIndentedString(coordinates)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("coordinates"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("coordinates"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to Polygon - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!Polygon.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in Polygon is not found in the empty JSON string", Polygon.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!Polygon.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Polygon` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : Polygon.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the required json array is present - if (jsonObj.get("coordinates") == null) { - throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); - } else if (!jsonObj.get("coordinates").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `coordinates` to be an array in the JSON string but got `%s`", jsonObj.get("coordinates").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!Polygon.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'Polygon' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(Polygon.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, Polygon value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public Polygon read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of Polygon given an JSON string - * - * @param jsonString JSON string - * @return An instance of Polygon - * @throws IOException if the JSON string is invalid with respect to Polygon - */ - public static Polygon fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, Polygon.class); - } - /** - * Convert an instance of Polygon to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} +public class Polygon implements Geometry { + private String type; + private List>> coordinates; + @Override public String getType() { return type; } + public List>> getCoordinates() { return coordinates; } +} \ No newline at end of file diff --git a/src/main/java/io/openepi/geocoding/model/Properties.java b/src/main/java/io/openepi/geocoding/model/Properties.java index 72e34f5..db50a14 100644 --- a/src/main/java/io/openepi/geocoding/model/Properties.java +++ b/src/main/java/io/openepi/geocoding/model/Properties.java @@ -1,630 +1,79 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - package io.openepi.geocoding.model; -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import org.openapitools.jackson.nullable.JsonNullable; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.geocoding.JSON; -/** - * Properties - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") public class Properties { - public static final String SERIALIZED_NAME_NAME = "name"; - @SerializedName(SERIALIZED_NAME_NAME) - private String name; - - public static final String SERIALIZED_NAME_OSM_TYPE = "osm_type"; - @SerializedName(SERIALIZED_NAME_OSM_TYPE) - private String osmType; - - public static final String SERIALIZED_NAME_OSM_ID = "osm_id"; - @SerializedName(SERIALIZED_NAME_OSM_ID) - private Integer osmId; - - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private String type; - - public static final String SERIALIZED_NAME_COUNTRY = "country"; - @SerializedName(SERIALIZED_NAME_COUNTRY) - private String country; - - public static final String SERIALIZED_NAME_COUNTY = "county"; - @SerializedName(SERIALIZED_NAME_COUNTY) - private String county; - - public static final String SERIALIZED_NAME_CITY = "city"; - @SerializedName(SERIALIZED_NAME_CITY) - private String city; - - public static final String SERIALIZED_NAME_COUNTRYCODE = "countrycode"; - @SerializedName(SERIALIZED_NAME_COUNTRYCODE) - private String countrycode; - - public static final String SERIALIZED_NAME_OSM_KEY = "osm_key"; - @SerializedName(SERIALIZED_NAME_OSM_KEY) - private String osmKey; - - public static final String SERIALIZED_NAME_OSM_VALUE = "osm_value"; - @SerializedName(SERIALIZED_NAME_OSM_VALUE) - private String osmValue; - - public static final String SERIALIZED_NAME_POSTCODE = "postcode"; - @SerializedName(SERIALIZED_NAME_POSTCODE) - private String postcode; - - public static final String SERIALIZED_NAME_EXTENT = "extent"; - @SerializedName(SERIALIZED_NAME_EXTENT) - private List extent = new ArrayList<>(); - - public Properties() { - } - - public Properties name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - */ - @javax.annotation.Nullable - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - - public Properties osmType(String osmType) { - this.osmType = osmType; - return this; - } - - /** - * Whether the OSM object is an OSM node (N), way (W), or relation (R) - * @return osmType - */ - @javax.annotation.Nullable - public String getOsmType() { - return osmType; - } - - public void setOsmType(String osmType) { - this.osmType = osmType; - } - - - public Properties osmId(Integer osmId) { - this.osmId = osmId; - return this; - } - - /** - * An ID uniquely identifies the OSM-object within the OSM-type - * @return osmId - */ - @javax.annotation.Nonnull - public Integer getOsmId() { - return osmId; - } - - public void setOsmId(Integer osmId) { - this.osmId = osmId; - } - - - public Properties type(String type) { - this.type = type; - return this; - } - - /** - * The type of the place (e.g. house, street, city, country) - * @return type - */ - @javax.annotation.Nullable - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - - public Properties country(String country) { - this.country = country; - return this; - } - - /** - * Get country - * @return country - */ - @javax.annotation.Nullable - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - - public Properties county(String county) { - this.county = county; - return this; - } - - /** - * Get county - * @return county - */ - @javax.annotation.Nullable - public String getCounty() { - return county; - } - - public void setCounty(String county) { - this.county = county; - } - - - public Properties city(String city) { - this.city = city; - return this; - } - - /** - * Get city - * @return city - */ - @javax.annotation.Nullable - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - - public Properties countrycode(String countrycode) { - this.countrycode = countrycode; - return this; - } - - /** - * Get countrycode - * @return countrycode - */ - @javax.annotation.Nullable - public String getCountrycode() { - return countrycode; - } - - public void setCountrycode(String countrycode) { - this.countrycode = countrycode; - } - - - public Properties osmKey(String osmKey) { - this.osmKey = osmKey; - return this; - } - - /** - * Get osmKey - * @return osmKey - */ - @javax.annotation.Nullable - public String getOsmKey() { - return osmKey; - } - - public void setOsmKey(String osmKey) { - this.osmKey = osmKey; - } - - - public Properties osmValue(String osmValue) { - this.osmValue = osmValue; - return this; - } - - /** - * Get osmValue - * @return osmValue - */ - @javax.annotation.Nullable - public String getOsmValue() { - return osmValue; - } - - public void setOsmValue(String osmValue) { - this.osmValue = osmValue; - } - - - public Properties postcode(String postcode) { - this.postcode = postcode; - return this; - } - - /** - * Get postcode - * @return postcode - */ - @javax.annotation.Nullable - public String getPostcode() { - return postcode; - } - - public void setPostcode(String postcode) { - this.postcode = postcode; - } - - - public Properties extent(List extent) { - this.extent = extent; - return this; - } - - public Properties addExtentItem(String extentItem) { - if (this.extent == null) { - this.extent = new ArrayList<>(); + private String name; + private String osm_type; + private long osm_id; + private String type; + private String country; + private String county; + private String city; + private String countrycode; + private String osm_key; + private String osm_value; + private String postcode; + private List extent; + + public String getName() { return name; } + public String getOsmType() { return osm_type; } + public long getOsmId() { return osm_id; } + public String getType() { return type; } + public String getCountry() { return country; } + public String getCounty() { return county; } + public String getCity() { return city; } + public String getCountryCode() { return countrycode; } + public String getOsmKey() { return osm_key; } + public String getOsmValue() { return osm_value; } + public String getPostcode() { return postcode; } + public List getExtent() { return extent; } + + public void setName(String name) { + this.name = name; } - this.extent.add(extentItem); - return this; - } - - /** - * The bounding box formatted as (min latitude, max latitude, min longitude, max longitude) - * @return extent - */ - @javax.annotation.Nullable - public List getExtent() { - return extent; - } - public void setExtent(List extent) { - this.extent = extent; - } - - /** - * A container for additional, undeclared properties. - * This is a holder for any undeclared properties as specified with - * the 'additionalProperties' keyword in the OAS document. - */ - private Map additionalProperties; - - /** - * Set the additional (undeclared) property with the specified name and value. - * If the property does not already exist, create it otherwise replace it. - * - * @param key name of the property - * @param value value of the property - * @return the Properties instance itself - */ - public Properties putAdditionalProperty(String key, Object value) { - if (this.additionalProperties == null) { - this.additionalProperties = new HashMap(); + public void setOsm_type(String osm_type) { + this.osm_type = osm_type; } - this.additionalProperties.put(key, value); - return this; - } - - /** - * Return the additional (undeclared) property. - * - * @return a map of objects - */ - public Map getAdditionalProperties() { - return additionalProperties; - } - /** - * Return the additional (undeclared) property with the specified name. - * - * @param key name of the property - * @return an object - */ - public Object getAdditionalProperty(String key) { - if (this.additionalProperties == null) { - return null; + public void setOsm_id(long osm_id) { + this.osm_id = osm_id; } - return this.additionalProperties.get(key); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; + public void setType(String type) { + this.type = type; } - Properties properties = (Properties) o; - return Objects.equals(this.name, properties.name) && - Objects.equals(this.osmType, properties.osmType) && - Objects.equals(this.osmId, properties.osmId) && - Objects.equals(this.type, properties.type) && - Objects.equals(this.country, properties.country) && - Objects.equals(this.county, properties.county) && - Objects.equals(this.city, properties.city) && - Objects.equals(this.countrycode, properties.countrycode) && - Objects.equals(this.osmKey, properties.osmKey) && - Objects.equals(this.osmValue, properties.osmValue) && - Objects.equals(this.postcode, properties.postcode) && - Objects.equals(this.extent, properties.extent)&& - Objects.equals(this.additionalProperties, properties.additionalProperties); - } - - private static boolean equalsNullable(JsonNullable a, JsonNullable b) { - return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); - } - @Override - public int hashCode() { - return Objects.hash(name, osmType, osmId, type, country, county, city, countrycode, osmKey, osmValue, postcode, extent, additionalProperties); - } - - private static int hashCodeNullable(JsonNullable a) { - if (a == null) { - return 1; + public void setCountry(String country) { + this.country = country; } - return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Properties {\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" osmType: ").append(toIndentedString(osmType)).append("\n"); - sb.append(" osmId: ").append(toIndentedString(osmId)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" country: ").append(toIndentedString(country)).append("\n"); - sb.append(" county: ").append(toIndentedString(county)).append("\n"); - sb.append(" city: ").append(toIndentedString(city)).append("\n"); - sb.append(" countrycode: ").append(toIndentedString(countrycode)).append("\n"); - sb.append(" osmKey: ").append(toIndentedString(osmKey)).append("\n"); - sb.append(" osmValue: ").append(toIndentedString(osmValue)).append("\n"); - sb.append(" postcode: ").append(toIndentedString(postcode)).append("\n"); - sb.append(" extent: ").append(toIndentedString(extent)).append("\n"); - sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); - sb.append("}"); - return sb.toString(); - } - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; + public void setCounty(String county) { + this.county = county; } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("name"); - openapiFields.add("osm_type"); - openapiFields.add("osm_id"); - openapiFields.add("type"); - openapiFields.add("country"); - openapiFields.add("county"); - openapiFields.add("city"); - openapiFields.add("countrycode"); - openapiFields.add("osm_key"); - openapiFields.add("osm_value"); - openapiFields.add("postcode"); - openapiFields.add("extent"); - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("osm_type"); - openapiRequiredFields.add("osm_id"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to Properties - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!Properties.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in Properties is not found in the empty JSON string", Properties.openapiRequiredFields.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : Properties.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); - } - - if ((jsonObj.get("country") != null && !jsonObj.get("country").isJsonNull()) && !jsonObj.get("country").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `country` to be a primitive type in the JSON string but got `%s`", jsonObj.get("country").toString())); - } - if ((jsonObj.get("county") != null && !jsonObj.get("county").isJsonNull()) && !jsonObj.get("county").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `county` to be a primitive type in the JSON string but got `%s`", jsonObj.get("county").toString())); - } - if ((jsonObj.get("city") != null && !jsonObj.get("city").isJsonNull()) && !jsonObj.get("city").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `city` to be a primitive type in the JSON string but got `%s`", jsonObj.get("city").toString())); - } - if ((jsonObj.get("countrycode") != null && !jsonObj.get("countrycode").isJsonNull()) && !jsonObj.get("countrycode").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `countrycode` to be a primitive type in the JSON string but got `%s`", jsonObj.get("countrycode").toString())); - } - if ((jsonObj.get("osm_key") != null && !jsonObj.get("osm_key").isJsonNull()) && !jsonObj.get("osm_key").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `osm_key` to be a primitive type in the JSON string but got `%s`", jsonObj.get("osm_key").toString())); - } - if ((jsonObj.get("osm_value") != null && !jsonObj.get("osm_value").isJsonNull()) && !jsonObj.get("osm_value").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `osm_value` to be a primitive type in the JSON string but got `%s`", jsonObj.get("osm_value").toString())); - } - if ((jsonObj.get("postcode") != null && !jsonObj.get("postcode").isJsonNull()) && !jsonObj.get("postcode").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `postcode` to be a primitive type in the JSON string but got `%s`", jsonObj.get("postcode").toString())); - } - // ensure the optional json data is an array if present - if (jsonObj.get("extent") != null && !jsonObj.get("extent").isJsonNull() && !jsonObj.get("extent").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `extent` to be an array in the JSON string but got `%s`", jsonObj.get("extent").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!Properties.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'Properties' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(Properties.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, Properties value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - obj.remove("additionalProperties"); - // serialize additional properties - if (value.getAdditionalProperties() != null) { - for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { - if (entry.getValue() instanceof String) - obj.addProperty(entry.getKey(), (String) entry.getValue()); - else if (entry.getValue() instanceof Number) - obj.addProperty(entry.getKey(), (Number) entry.getValue()); - else if (entry.getValue() instanceof Boolean) - obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); - else if (entry.getValue() instanceof Character) - obj.addProperty(entry.getKey(), (Character) entry.getValue()); - else { - JsonElement jsonElement = gson.toJsonTree(entry.getValue()); - if (jsonElement.isJsonArray()) { - obj.add(entry.getKey(), jsonElement.getAsJsonArray()); - } else { - obj.add(entry.getKey(), jsonElement.getAsJsonObject()); - } - } - } - } - elementAdapter.write(out, obj); - } + public void setCity(String city) { + this.city = city; + } - @Override - public Properties read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // store additional fields in the deserialized instance - Properties instance = thisAdapter.fromJsonTree(jsonObj); - for (Map.Entry entry : jsonObj.entrySet()) { - if (!openapiFields.contains(entry.getKey())) { - if (entry.getValue().isJsonPrimitive()) { // primitive type - if (entry.getValue().getAsJsonPrimitive().isString()) - instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); - else if (entry.getValue().getAsJsonPrimitive().isNumber()) - instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); - else if (entry.getValue().getAsJsonPrimitive().isBoolean()) - instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); - else - throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); - } else if (entry.getValue().isJsonArray()) { - instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); - } else { // JSON object - instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); - } - } - } - return instance; - } + public void setCountrycode(String countrycode) { + this.countrycode = countrycode; + } - }.nullSafe(); + public void setOsm_key(String osm_key) { + this.osm_key = osm_key; } - } - /** - * Create an instance of Properties given an JSON string - * - * @param jsonString JSON string - * @return An instance of Properties - * @throws IOException if the JSON string is invalid with respect to Properties - */ - public static Properties fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, Properties.class); - } + public void setOsm_value(String osm_value) { + this.osm_value = osm_value; + } - /** - * Convert an instance of Properties to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} + public void setPostcode(String postcode) { + this.postcode = postcode; + } + public void setExtent(List extent) { + this.extent = extent; + } +} \ No newline at end of file diff --git a/src/main/java/io/openepi/geocoding/model/ValidationError.java b/src/main/java/io/openepi/geocoding/model/ValidationError.java deleted file mode 100644 index bcd662d..0000000 --- a/src/main/java/io/openepi/geocoding/model/ValidationError.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.geocoding.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.geocoding.model.ValidationErrorLocInner; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.geocoding.JSON; - -/** - * ValidationError - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class ValidationError { - public static final String SERIALIZED_NAME_LOC = "loc"; - @SerializedName(SERIALIZED_NAME_LOC) - private List loc = new ArrayList<>(); - - public static final String SERIALIZED_NAME_MSG = "msg"; - @SerializedName(SERIALIZED_NAME_MSG) - private String msg; - - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private String type; - - public ValidationError() { - } - - public ValidationError loc(List loc) { - this.loc = loc; - return this; - } - - public ValidationError addLocItem(ValidationErrorLocInner locItem) { - if (this.loc == null) { - this.loc = new ArrayList<>(); - } - this.loc.add(locItem); - return this; - } - - /** - * Get loc - * @return loc - */ - @javax.annotation.Nonnull - public List getLoc() { - return loc; - } - - public void setLoc(List loc) { - this.loc = loc; - } - - - public ValidationError msg(String msg) { - this.msg = msg; - return this; - } - - /** - * Get msg - * @return msg - */ - @javax.annotation.Nonnull - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - - public ValidationError type(String type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nonnull - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ValidationError validationError = (ValidationError) o; - return Objects.equals(this.loc, validationError.loc) && - Objects.equals(this.msg, validationError.msg) && - Objects.equals(this.type, validationError.type); - } - - @Override - public int hashCode() { - return Objects.hash(loc, msg, type); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ValidationError {\n"); - sb.append(" loc: ").append(toIndentedString(loc)).append("\n"); - sb.append(" msg: ").append(toIndentedString(msg)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("loc"); - openapiFields.add("msg"); - openapiFields.add("type"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("loc"); - openapiRequiredFields.add("msg"); - openapiRequiredFields.add("type"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to ValidationError - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!ValidationError.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in ValidationError is not found in the empty JSON string", ValidationError.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!ValidationError.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ValidationError` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : ValidationError.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the json data is an array - if (!jsonObj.get("loc").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `loc` to be an array in the JSON string but got `%s`", jsonObj.get("loc").toString())); - } - - JsonArray jsonArrayloc = jsonObj.getAsJsonArray("loc"); - // validate the required field `loc` (array) - for (int i = 0; i < jsonArrayloc.size(); i++) { - ValidationErrorLocInner.validateJsonElement(jsonArrayloc.get(i)); - }; - if (!jsonObj.get("msg").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `msg` to be a primitive type in the JSON string but got `%s`", jsonObj.get("msg").toString())); - } - if (!jsonObj.get("type").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!ValidationError.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ValidationError' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(ValidationError.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, ValidationError value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public ValidationError read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of ValidationError given an JSON string - * - * @param jsonString JSON string - * @return An instance of ValidationError - * @throws IOException if the JSON string is invalid with respect to ValidationError - */ - public static ValidationError fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ValidationError.class); - } - - /** - * Convert an instance of ValidationError to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/geocoding/model/ValidationErrorLocInner.java b/src/main/java/io/openepi/geocoding/model/ValidationErrorLocInner.java deleted file mode 100644 index 407b902..0000000 --- a/src/main/java/io/openepi/geocoding/model/ValidationErrorLocInner.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Geocoder API - *

This is a RESTful service that provides geocoding and reverse geocoding using OpenStreetMap® data. The data is licensed under the Open Data Commons Open Database License (ODbL), by the OpenStreetMap Foundation (OSMF).

The data is sourced from https://photon.komoot.io.

- * - * The version of the OpenAPI document: 0.4.3 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.geocoding.model; - -import java.util.Objects; - - - -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.JsonPrimitive; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonParseException; - -import io.openepi.geocoding.JSON; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-29T12:45:40.887231+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class ValidationErrorLocInner extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(ValidationErrorLocInner.class.getName()); - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!ValidationErrorLocInner.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ValidationErrorLocInner' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); - final TypeAdapter adapterInteger = gson.getDelegateAdapter(this, TypeToken.get(Integer.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, ValidationErrorLocInner value) throws IOException { - if (value == null || value.getActualInstance() == null) { - elementAdapter.write(out, null); - return; - } - - // check if the actual instance is of the type `String` - if (value.getActualInstance() instanceof String) { - JsonPrimitive primitive = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonPrimitive(); - elementAdapter.write(out, primitive); - return; - } - // check if the actual instance is of the type `Integer` - if (value.getActualInstance() instanceof Integer) { - JsonPrimitive primitive = adapterInteger.toJsonTree((Integer)value.getActualInstance()).getAsJsonPrimitive(); - elementAdapter.write(out, primitive); - return; - } - throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: Integer, String"); - } - - @Override - public ValidationErrorLocInner read(JsonReader in) throws IOException { - Object deserialized = null; - JsonElement jsonElement = elementAdapter.read(in); - - ArrayList errorMessages = new ArrayList<>(); - TypeAdapter actualAdapter = elementAdapter; - - // deserialize String - try { - // validate the JSON object to see if any exception is thrown - if (!jsonElement.getAsJsonPrimitive().isString()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); - } - actualAdapter = adapterString; - ValidationErrorLocInner ret = new ValidationErrorLocInner(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'String'", e); - } - // deserialize Integer - try { - // validate the JSON object to see if any exception is thrown - if (!jsonElement.getAsJsonPrimitive().isNumber()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); - } - actualAdapter = adapterInteger; - ValidationErrorLocInner ret = new ValidationErrorLocInner(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'Integer'", e); - } - - throw new IOException(String.format("Failed deserialization for ValidationErrorLocInner: no class matches result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); - } - }.nullSafe(); - } - } - - // store a list of schema names defined in anyOf - public static final Map> schemas = new HashMap>(); - - public ValidationErrorLocInner() { - super("anyOf", Boolean.FALSE); - } - - public ValidationErrorLocInner(Object o) { - super("anyOf", Boolean.FALSE); - setActualInstance(o); - } - - static { - schemas.put("String", String.class); - schemas.put("Integer", Integer.class); - } - - @Override - public Map> getSchemas() { - return ValidationErrorLocInner.schemas; - } - - /** - * Set the instance that matches the anyOf child schema, check - * the instance parameter is valid against the anyOf child schemas: - * Integer, String - * - * It could be an instance of the 'anyOf' schemas. - */ - @Override - public void setActualInstance(Object instance) { - if (instance instanceof String) { - super.setActualInstance(instance); - return; - } - - if (instance instanceof Integer) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be Integer, String"); - } - - /** - * Get the actual instance, which can be the following: - * Integer, String - * - * @return The actual instance (Integer, String) - */ - @SuppressWarnings("unchecked") - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `String`. If the actual instance is not `String`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `String` - * @throws ClassCastException if the instance is not `String` - */ - public String getString() throws ClassCastException { - return (String)super.getActualInstance(); - } - /** - * Get the actual instance of `Integer`. If the actual instance is not `Integer`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Integer` - * @throws ClassCastException if the instance is not `Integer` - */ - public Integer getInteger() throws ClassCastException { - return (Integer)super.getActualInstance(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to ValidationErrorLocInner - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - // validate anyOf schemas one by one - ArrayList errorMessages = new ArrayList<>(); - // validate the json string with String - try { - if (!jsonElement.getAsJsonPrimitive().isString()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); - } - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); - // continue to the next one - } - // validate the json string with Integer - try { - if (!jsonElement.getAsJsonPrimitive().isNumber()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); - } - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); - // continue to the next one - } - throw new IOException(String.format("The JSON string is invalid for ValidationErrorLocInner with anyOf schemas: Integer, String. no class match the result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); - } - - /** - * Create an instance of ValidationErrorLocInner given an JSON string - * - * @param jsonString JSON string - * @return An instance of ValidationErrorLocInner - * @throws IOException if the JSON string is invalid with respect to ValidationErrorLocInner - */ - public static ValidationErrorLocInner fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ValidationErrorLocInner.class); - } - - /** - * Convert an instance of ValidationErrorLocInner to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/ApiClient.java b/src/main/java/io/openepi/soil/ApiClient.java deleted file mode 100644 index 04bf6f4..0000000 --- a/src/main/java/io/openepi/soil/ApiClient.java +++ /dev/null @@ -1,1562 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil; - -import io.openepi.common.*; -import okhttp3.*; -import okhttp3.internal.http.HttpMethod; -import okhttp3.internal.tls.OkHostnameVerifier; -import okhttp3.logging.HttpLoggingInterceptor; -import okhttp3.logging.HttpLoggingInterceptor.Level; -import okio.Buffer; -import okio.BufferedSink; -import okio.Okio; - -import javax.net.ssl.*; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Type; -import java.net.URI; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.text.DateFormat; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import io.openepi.common.auth.Authentication; -import io.openepi.common.auth.HttpBasicAuth; -import io.openepi.common.auth.ApiKeyAuth; - -/** - *

ApiClient class.

- */ -public class ApiClient { - - private String basePath = "https://api.openepi.io/soil"; - protected List servers = new ArrayList(Arrays.asList( - new ServerConfiguration( - "https://api.openepi.io/soil", - "No description provided", - new HashMap() - ) - )); - protected Integer serverIndex = 0; - protected Map serverVariables = null; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private Map defaultCookieMap = new HashMap(); - private String tempFolderPath = null; - - private Map authentications; - - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; - - private InputStream sslCaCert; - private boolean verifyingSsl; - private KeyManager[] keyManagers; - - private OkHttpClient httpClient; - private JSON json; - - private HttpLoggingInterceptor loggingInterceptor; - - /** - * Basic constructor for ApiClient - */ - public ApiClient() { - init(); - initHttpClient(); - - // Setup authentications (key: authentication name, value: authentication). - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - /** - * Basic constructor with custom OkHttpClient - * - * @param client a {@link okhttp3.OkHttpClient} object - */ - public ApiClient(OkHttpClient client) { - init(); - - httpClient = client; - - // Setup authentications (key: authentication name, value: authentication). - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - private void initHttpClient() { - initHttpClient(Collections.emptyList()); - } - - private void initHttpClient(List interceptors) { - OkHttpClient.Builder builder = new OkHttpClient.Builder(); - builder.addNetworkInterceptor(getProgressInterceptor()); - for (Interceptor interceptor: interceptors) { - builder.addInterceptor(interceptor); - } - - httpClient = builder.build(); - } - - private void init() { - verifyingSsl = true; - - json = new JSON(); - - // Set default User-Agent. - setUserAgent("OpenAPI-Generator/0.2.5/java"); - - authentications = new HashMap(); - } - - /** - * Get base path - * - * @return Base path - */ - public String getBasePath() { - return basePath; - } - - /** - * Set base path - * - * @param basePath Base path of the URL (e.g https://api.openepi.io/soil - * @return An instance of OkHttpClient - */ - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - this.serverIndex = null; - return this; - } - - public List getServers() { - return servers; - } - - public ApiClient setServers(List servers) { - this.servers = servers; - return this; - } - - public Integer getServerIndex() { - return serverIndex; - } - - public ApiClient setServerIndex(Integer serverIndex) { - this.serverIndex = serverIndex; - return this; - } - - public Map getServerVariables() { - return serverVariables; - } - - public ApiClient setServerVariables(Map serverVariables) { - this.serverVariables = serverVariables; - return this; - } - - /** - * Get HTTP client - * - * @return An instance of OkHttpClient - */ - public OkHttpClient getHttpClient() { - return httpClient; - } - - /** - * Set HTTP client, which must never be null. - * - * @param newHttpClient An instance of OkHttpClient - * @return Api Client - * @throws java.lang.NullPointerException when newHttpClient is null - */ - public ApiClient setHttpClient(OkHttpClient newHttpClient) { - this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!"); - return this; - } - - /** - * Get JSON - * - * @return JSON object - */ - public JSON getJSON() { - return json; - } - - /** - * Set JSON - * - * @param json JSON object - * @return Api client - */ - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - /** - * True if isVerifyingSsl flag is on - * - * @return True if isVerifySsl flag is on - */ - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - * - * @param verifyingSsl True to verify TLS/SSL connection - * @return ApiClient - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - /** - * Get SSL CA cert. - * - * @return Input stream to the SSL CA cert - */ - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - * - * @param sslCaCert input stream for SSL CA cert - * @return ApiClient - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - /** - *

Getter for the field keyManagers.

- * - * @return an array of {@link javax.net.ssl.KeyManager} objects - */ - public KeyManager[] getKeyManagers() { - return keyManagers; - } - - /** - * Configure client keys to use for authorization in an SSL session. - * Use null to reset to default. - * - * @param managers The KeyManagers to use - * @return ApiClient - */ - public ApiClient setKeyManagers(KeyManager[] managers) { - this.keyManagers = managers; - applySslSettings(); - return this; - } - - /** - *

Getter for the field dateFormat.

- * - * @return a {@link java.text.DateFormat} object - */ - public DateFormat getDateFormat() { - return dateFormat; - } - - /** - *

Setter for the field dateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link io.openepi.soil.ApiClient} object - */ - public ApiClient setDateFormat(DateFormat dateFormat) { - JSON.setDateFormat(dateFormat); - return this; - } - - /** - *

Set SqlDateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link io.openepi.soil.ApiClient} object - */ - public ApiClient setSqlDateFormat(DateFormat dateFormat) { - JSON.setSqlDateFormat(dateFormat); - return this; - } - - /** - *

Set OffsetDateTimeFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link io.openepi.soil.ApiClient} object - */ - public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - JSON.setOffsetDateTimeFormat(dateFormat); - return this; - } - - /** - *

Set LocalDateFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link io.openepi.soil.ApiClient} object - */ - public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { - JSON.setLocalDateFormat(dateFormat); - return this; - } - - /** - *

Set LenientOnJson.

- * - * @param lenientOnJson a boolean - * @return a {@link io.openepi.soil.ApiClient} object - */ - public ApiClient setLenientOnJson(boolean lenientOnJson) { - JSON.setLenientOnJson(lenientOnJson); - return this; - } - - /** - * Get authentications (key: authentication name, value: authentication). - * - * @return Map of authentication objects - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - - /** - * Helper method to set username for the first HTTP basic authentication. - * - * @param username Username - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - * - * @param password Password - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - * - * @param apiKey API key - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - * - * @param apiKeyPrefix API key prefix - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - * - * @param accessToken Access token - */ - public void setAccessToken(String accessToken) { - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Helper method to set credentials for AWSV4 Signature - * - * @param accessKey Access Key - * @param secretKey Secret Key - * @param region Region - * @param service Service to access to - */ - public void setAWS4Configuration(String accessKey, String secretKey, String region, String service) { - throw new RuntimeException("No AWS4 authentication configured!"); - } - - /** - * Helper method to set credentials for AWSV4 Signature - * - * @param accessKey Access Key - * @param secretKey Secret Key - * @param sessionToken Session Token - * @param region Region - * @param service Service to access to - */ - public void setAWS4Configuration(String accessKey, String secretKey, String sessionToken, String region, String service) { - throw new RuntimeException("No AWS4 authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - * - * @param userAgent HTTP request's user agent - * @return ApiClient - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - * @return ApiClient - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * Add a default cookie. - * - * @param key The cookie's key - * @param value The cookie's value - * @return ApiClient - */ - public ApiClient addDefaultCookie(String key, String value) { - defaultCookieMap.put(key, value); - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - * - * @return True if debugging is enabled, false otherwise. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - * @return ApiClient - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); - } else { - final OkHttpClient.Builder builder = httpClient.newBuilder(); - builder.interceptors().remove(loggingInterceptor); - httpClient = builder.build(); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } - - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default temporary folder. - * - * @see createTempFile - * @return Temporary folder path - */ - public String getTempFolderPath() { - return tempFolderPath; - } - - /** - * Set the temporary folder path (for downloading files) - * - * @param tempFolderPath Temporary folder path - * @return ApiClient - */ - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } - - /** - * Get connection timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getConnectTimeout() { - return httpClient.connectTimeoutMillis(); - } - - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param connectionTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - /** - * Get read timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getReadTimeout() { - return httpClient.readTimeoutMillis(); - } - - /** - * Sets the read timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param readTimeout read timeout in milliseconds - * @return Api client - */ - public ApiClient setReadTimeout(int readTimeout) { - httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - /** - * Get write timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getWriteTimeout() { - return httpClient.writeTimeoutMillis(); - } - - /** - * Sets the write timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param writeTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setWriteTimeout(int writeTimeout) { - httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } - - - /** - * Format the given parameter object into string. - * - * @param param Parameter - * @return String representation of the parameter - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) { - //Serialize to json string and remove the " enclosing characters - String jsonStr = JSON.serialize(param); - return jsonStr.substring(1, jsonStr.length() - 1); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection) param) { - if (b.length() > 0) { - b.append(","); - } - b.append(o); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /** - * Formats the specified query parameter to a list containing a single {@code Pair} object. - * - * Note that {@code value} must not be a collection. - * - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list containing a single {@code Pair} object. - */ - public List parameterToPair(String name, Object value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value instanceof Collection) { - return params; - } - - params.add(new Pair(name, parameterToString(value))); - return params; - } - - /** - * Formats the specified collection query parameters to a list of {@code Pair} objects. - * - * Note that the values of each of the returned Pair objects are percent-encoded. - * - * @param collectionFormat The collection format of the parameter. - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list of {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Collection value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value.isEmpty()) { - return params; - } - - // create the params based on the collection format - if ("multi".equals(collectionFormat)) { - for (Object item : value) { - params.add(new Pair(name, escapeString(parameterToString(item)))); - } - return params; - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - // escape all delimiters except commas, which are URI reserved - // characters - if ("ssv".equals(collectionFormat)) { - delimiter = escapeString(" "); - } else if ("tsv".equals(collectionFormat)) { - delimiter = escapeString("\t"); - } else if ("pipes".equals(collectionFormat)) { - delimiter = escapeString("|"); - } - - StringBuilder sb = new StringBuilder(); - for (Object item : value) { - sb.append(delimiter); - sb.append(escapeString(parameterToString(item))); - } - - params.add(new Pair(name, sb.substring(delimiter.length()))); - - return params; - } - - /** - * Formats the specified collection path parameter to a string value. - * - * @param collectionFormat The collection format of the parameter. - * @param value The value of the parameter. - * @return String representation of the parameter - */ - public String collectionPathParameterToString(String collectionFormat, Collection value) { - // create the value based on the collection format - if ("multi".equals(collectionFormat)) { - // not valid for path params - return parameterToString(value); - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - if ("ssv".equals(collectionFormat)) { - delimiter = " "; - } else if ("tsv".equals(collectionFormat)) { - delimiter = "\t"; - } else if ("pipes".equals(collectionFormat)) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : value) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - return sb.substring(delimiter.length()); - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * application/vnd.company+json - * "* / *" is also default to JSON - * @param mime MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public boolean isJsonMime(String mime) { - String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; - return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * returns null. If it matches "any", JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return null; - } - - if (contentTypes[0].equals("*/*")) { - return "application/json"; - } - - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - * - * @param str String to be escaped - * @return Escaped string - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param Type - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws ApiException If fail to deserialize response body, i.e. cannot read response body - * or the Content-Type of the response is not supported. - */ - @SuppressWarnings("unchecked") - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; - } - - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); - } - - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); - } - - if (respBody == null || "".equals(respBody)) { - return null; - } - - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return JSON.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } - } - - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create((File) obj, MediaType.parse(contentType)); - } else if ("text/plain".equals(contentType) && obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - return RequestBody.create(content, MediaType.parse(contentType)); - } else if (obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } - } - - /** - * Download file from the given response. - * - * @param response An instance of the Response object - * @throws ApiException If fail to read file content from response and write to disk - * @return Downloaded file - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * Prepare file for download - * - * @param response An instance of the Response object - * @return Prepared file for the download - * @throws java.io.IOException If fail to prepare file for download - */ - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } - } - - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // Files.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; - } - - if (tempFolderPath == null) - return Files.createTempFile(prefix, suffix).toFile(); - else - return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); - } - - /** - * {@link #execute(Call, Type)} - * - * @param Type - * @param call An instance of the Call object - * @return ApiResponse<T> - * @throws ApiException If fail to execute the call - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @param call Call - * @return ApiResponse object containing response status, headers and - * data, which is a Java object deserialized from response body and would be null - * when returnType is null. - * @throws ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * {@link #executeAsync(Call, Type, ApiCallback)} - * - * @param Type - * @param call An instance of the Call object - * @param callback ApiCallback<T> - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } - - /** - * Execute HTTP call asynchronously. - * - * @param Type - * @param call The callback to be executed when the API call finishes - * @param returnType Return type - * @param callback ApiCallback - * @see #execute(Call, Type) - */ - @SuppressWarnings("unchecked") - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } - - @Override - public void onResponse(Call call, Response response) throws IOException { - T result; - try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; - } catch (Exception e) { - callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); - return; - } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @param Type - * @param response Response - * @param returnType Return type - * @return Type - * @throws ApiException If the response has an unsuccessful status code or - * fail to deserialize the response body - */ - public T handleResponse(Response response, Type returnType) throws ApiException { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - if (response.body() != null) { - try { - response.body().close(); - } catch (Exception e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { - try { - respBody = response.body().string(); - } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - - /** - * Build HTTP call with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP call - * @throws ApiException If fail to serialize the request body object - */ - public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); - - return httpClient.newCall(request); - } - - /** - * Build an HTTP request with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP request - * @throws ApiException If fail to serialize the request body object - */ - public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams - List allQueryParams = new ArrayList(queryParams); - allQueryParams.addAll(collectionQueryParams); - - final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); - - // prepare HTTP request body - RequestBody reqBody; - String contentType = headerParams.get("Content-Type"); - String contentTypePure = contentType; - if (contentTypePure != null && contentTypePure.contains(";")) { - contentTypePure = contentType.substring(0, contentType.indexOf(";")); - } - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentTypePure)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentTypePure)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create("", contentType == null ? null : MediaType.parse(contentType)); - } - } else { - reqBody = serialize(body, contentType); - } - - // update parameters with authentication settings - updateParamsForAuth(authNames, allQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url)); - - final Request.Builder reqBuilder = new Request.Builder().url(url); - processHeaderParams(headerParams, reqBuilder); - processCookieParams(cookieParams, reqBuilder); - - // Associate callback with request (if not null) so interceptor can - // access it when creating ProgressResponseBody - reqBuilder.tag(callback); - - Request request = null; - - if (callback != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return request; - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param baseUrl The base URL - * @param path The sub path - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @return The full URL - */ - public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { - final StringBuilder url = new StringBuilder(); - if (baseUrl != null) { - url.append(baseUrl).append(path); - } else { - String baseURL; - if (serverIndex != null) { - if (serverIndex < 0 || serverIndex >= servers.size()) { - throw new ArrayIndexOutOfBoundsException(String.format( - "Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size() - )); - } - baseURL = servers.get(serverIndex).URL(serverVariables); - } else { - baseURL = basePath; - } - url.append(baseURL).append(path); - } - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { - String prefix = url.toString().contains("?") ? "&" : "?"; - for (Pair param : collectionQueryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - // collection query parameter value already escaped as part of parameterToPairs - url.append(escapeString(param.getName())).append("=").append(value); - } - } - } - - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - * - * @param headerParams Header parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Set cookie parameters to the request builder, including default cookies. - * - * @param cookieParams Cookie parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processCookieParams(Map cookieParams, Request.Builder reqBuilder) { - for (Entry param : cookieParams.entrySet()) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - for (Entry param : defaultCookieMap.entrySet()) { - if (!cookieParams.containsKey(param.getKey())) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - * @param cookieParams Map of cookie parameters - * @param payload HTTP request body - * @param method HTTP method - * @param uri URI - * @throws ApiException If fails to update the parameters - */ - public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, - Map cookieParams, String payload, String method, URI uri) throws ApiException { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) { - throw new RuntimeException("Authentication undefined: " + authName); - } - auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); - } - } - - /** - * Build a form-encoding request body with the given form parameters. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - addPartToMultiPartBuilder(mpBuilder, param.getKey(), file); - } else if (param.getValue() instanceof List) { - List list = (List) param.getValue(); - for (Object item: list) { - if (item instanceof File) { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item); - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The guessed Content-Type - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - - /** - * Add a Content-Disposition Header for the given key and file to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param file The file to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, File file) { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); - } - - /** - * Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param obj The complex object to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) { - RequestBody requestBody; - if (obj instanceof String) { - requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain")); - } else { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - requestBody = RequestBody.create(content, MediaType.parse("application/json")); - } - - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""); - mpBuilder.addPart(partHeaders, requestBody); - } - - /** - * Get network interceptor to add it to the httpClient to track download progress for - * async requests. - */ - private Interceptor getProgressInterceptor() { - return new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - final Request request = chain.request(); - final Response originalResponse = chain.proceed(request); - if (request.tag() instanceof ApiCallback) { - final ApiCallback callback = (ApiCallback) request.tag(); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), callback)) - .build(); - } - return originalResponse; - } - }; - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { - try { - TrustManager[] trustManagers; - HostnameVerifier hostnameVerifier; - if (!verifyingSsl) { - trustManagers = new TrustManager[]{ - new X509TrustManager() { - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[]{}; - } - } - }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - } else { - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - - if (sslCaCert == null) { - trustManagerFactory.init((KeyStore) null); - } else { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); - } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + (index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); - } - trustManagerFactory.init(caKeyStore); - } - trustManagers = trustManagerFactory.getTrustManagers(); - hostnameVerifier = OkHostnameVerifier.INSTANCE; - } - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient = httpClient.newBuilder() - .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) - .hostnameVerifier(hostnameVerifier) - .build(); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); - } - } - - /** - * Convert the HTTP request body to a string. - * - * @param requestBody The HTTP request object - * @return The string representation of the HTTP request body - * @throws ApiException If fail to serialize the request body object into a string - */ - private String requestBodyToString(RequestBody requestBody) throws ApiException { - if (requestBody != null) { - try { - final Buffer buffer = new Buffer(); - requestBody.writeTo(buffer); - return buffer.readUtf8(); - } catch (final IOException e) { - throw new ApiException(e); - } - } - - // empty http request body - return ""; - } -} diff --git a/src/main/java/io/openepi/soil/Configuration.java b/src/main/java/io/openepi/soil/Configuration.java deleted file mode 100644 index 109b345..0000000 --- a/src/main/java/io/openepi/soil/Configuration.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class Configuration { - public static final String VERSION = "0.2.5"; - - private static ApiClient defaultApiClient = new ApiClient(); - - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - * - * @return Default API client - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } - - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - * - * @param apiClient API client - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } -} diff --git a/src/main/java/io/openepi/soil/JSON.java b/src/main/java/io/openepi/soil/JSON.java deleted file mode 100644 index bd1ee99..0000000 --- a/src/main/java/io/openepi/soil/JSON.java +++ /dev/null @@ -1,418 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.internal.bind.util.ISO8601Utils; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonElement; -import io.gsonfire.GsonFireBuilder; -import io.gsonfire.TypeSelector; - -import okio.ByteString; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Type; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.ParsePosition; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.Locale; -import java.util.Map; -import java.util.HashMap; - -/* - * A JSON utility class - * - * NOTE: in the future, this class may be converted to static, which may break - * backward-compatibility - */ -public class JSON { - private static Gson gson; - private static boolean isLenientOnJson = false; - private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); - private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); - private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); - private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); - private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - - @SuppressWarnings("unchecked") - public static GsonBuilder createGson() { - GsonFireBuilder fireBuilder = new GsonFireBuilder() - ; - GsonBuilder builder = fireBuilder.createGsonBuilder(); - return builder; - } - - private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { - JsonElement element = readElement.getAsJsonObject().get(discriminatorField); - if (null == element) { - throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); - } - return element.getAsString(); - } - - /** - * Returns the Java class that implements the OpenAPI schema for the specified discriminator value. - * - * @param classByDiscriminatorValue The map of discriminator values to Java classes. - * @param discriminatorValue The value of the OpenAPI discriminator in the input data. - * @return The Java class that implements the OpenAPI schema - */ - private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { - Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue); - if (null == clazz) { - throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); - } - return clazz; - } - - static { - GsonBuilder gsonBuilder = createGson(); - gsonBuilder.registerTypeAdapter(Date.class, dateTypeAdapter); - gsonBuilder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); - gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); - gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); - gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.BoundingBoxGeometry.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.DepthRange.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.HTTPValidationError.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.PointGeometry.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.SoilDepth.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.SoilLayer.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.SoilLayerList.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.SoilPropertyJSON.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.SoilPropertyUnit.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.SoilPropertyValues.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.SoilTypeInfo.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.SoilTypeJSON.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.SoilTypeProbability.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.SoilTypeSummary.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.SoilTypeSummaryInfo.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.SoilTypeSummaryJSON.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.ValidationError.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new io.openepi.soil.model.ValidationErrorLocInner.CustomTypeAdapterFactory()); - gson = gsonBuilder.create(); - } - - /** - * Get Gson. - * - * @return Gson - */ - public static Gson getGson() { - return gson; - } - - /** - * Set Gson. - * - * @param gson Gson - */ - public static void setGson(Gson gson) { - JSON.gson = gson; - } - - public static void setLenientOnJson(boolean lenientOnJson) { - isLenientOnJson = lenientOnJson; - } - - /** - * Serialize the given Java object into JSON string. - * - * @param obj Object - * @return String representation of the JSON - */ - public static String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param Type - * @param body The JSON string - * @param returnType The type to deserialize into - * @return The deserialized Java object - */ - @SuppressWarnings("unchecked") - public static T deserialize(String body, Type returnType) { - try { - if (isLenientOnJson) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - if (returnType.equals(String.class)) { - return (T) body; - } else { - throw (e); - } - } - } - - /** - * Gson TypeAdapter for Byte Array type - */ - public static class ByteArrayAdapter extends TypeAdapter { - - @Override - public void write(JsonWriter out, byte[] value) throws IOException { - if (value == null) { - out.nullValue(); - } else { - out.value(ByteString.of(value).base64()); - } - } - - @Override - public byte[] read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String bytesAsBase64 = in.nextString(); - ByteString byteString = ByteString.decodeBase64(bytesAsBase64); - return byteString.toByteArray(); - } - } - } - - /** - * Gson TypeAdapter for JSR310 OffsetDateTime type - */ - public static class OffsetDateTimeTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public OffsetDateTimeTypeAdapter() { - this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); - } - - public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, OffsetDateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public OffsetDateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - if (date.endsWith("+0000")) { - date = date.substring(0, date.length()-5) + "Z"; - } - return OffsetDateTime.parse(date, formatter); - } - } - } - - /** - * Gson TypeAdapter for JSR310 LocalDate type - */ - public static class LocalDateTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public LocalDateTypeAdapter() { - this(DateTimeFormatter.ISO_LOCAL_DATE); - } - - public LocalDateTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return LocalDate.parse(date, formatter); - } - } - } - - public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - offsetDateTimeTypeAdapter.setFormat(dateFormat); - } - - public static void setLocalDateFormat(DateTimeFormatter dateFormat) { - localDateTypeAdapter.setFormat(dateFormat); - } - - /** - * Gson TypeAdapter for java.sql.Date type - * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used - * (more efficient than SimpleDateFormat). - */ - public static class SqlDateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public SqlDateTypeAdapter() {} - - public SqlDateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, java.sql.Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = date.toString(); - } - out.value(value); - } - } - - @Override - public java.sql.Date read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return new java.sql.Date(dateFormat.parse(date).getTime()); - } - return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } - } - - /** - * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, ISO8601Utils will be used. - */ - public static class DateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public DateTypeAdapter() {} - - public DateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = ISO8601Utils.format(date, true); - } - out.value(value); - } - } - - @Override - public Date read(JsonReader in) throws IOException { - try { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return dateFormat.parse(date); - } - return ISO8601Utils.parse(date, new ParsePosition(0)); - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } catch (IllegalArgumentException e) { - throw new JsonParseException(e); - } - } - } - - public static void setDateFormat(DateFormat dateFormat) { - dateTypeAdapter.setFormat(dateFormat); - } - - public static void setSqlDateFormat(DateFormat dateFormat) { - sqlDateTypeAdapter.setFormat(dateFormat); - } -} diff --git a/src/main/java/io/openepi/soil/api/HealthApi.java b/src/main/java/io/openepi/soil/api/HealthApi.java deleted file mode 100644 index bc180ab..0000000 --- a/src/main/java/io/openepi/soil/api/HealthApi.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.api; - -import io.openepi.common.ApiCallback; -import io.openepi.soil.ApiClient; -import io.openepi.common.ApiException; -import io.openepi.common.ApiResponse; -import io.openepi.soil.Configuration; -import io.openepi.common.Pair; - -import com.google.gson.reflect.TypeToken; - - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class HealthApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public HealthApi() { - this(Configuration.getDefaultApiClient()); - } - - public HealthApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for livenessHealthGet - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call livenessHealthGetCall(final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/health"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call livenessHealthGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { - return livenessHealthGetCall(_callback); - - } - - /** - * Check if this service is alive - * Returns a simple message to indicate that this service is alive - * @return Map<String, String> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public Map livenessHealthGet() throws ApiException { - ApiResponse> localVarResp = livenessHealthGetWithHttpInfo(); - return localVarResp.getData(); - } - - /** - * Check if this service is alive - * Returns a simple message to indicate that this service is alive - * @return ApiResponse<Map<String, String>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public ApiResponse> livenessHealthGetWithHttpInfo() throws ApiException { - okhttp3.Call localVarCall = livenessHealthGetValidateBeforeCall(null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Check if this service is alive (asynchronously) - * Returns a simple message to indicate that this service is alive - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call livenessHealthGetAsync(final ApiCallback> _callback) throws ApiException { - - okhttp3.Call localVarCall = livenessHealthGetValidateBeforeCall(_callback); - Type localVarReturnType = new TypeToken>(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for readyReadyGet - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call readyReadyGetCall(final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/ready"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call readyReadyGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { - return readyReadyGetCall(_callback); - - } - - /** - * Check if this service is ready to receive requests - * Returns a message describing the status of this service - * @return Object - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public Object readyReadyGet() throws ApiException { - ApiResponse localVarResp = readyReadyGetWithHttpInfo(); - return localVarResp.getData(); - } - - /** - * Check if this service is ready to receive requests - * Returns a message describing the status of this service - * @return ApiResponse<Object> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public ApiResponse readyReadyGetWithHttpInfo() throws ApiException { - okhttp3.Call localVarCall = readyReadyGetValidateBeforeCall(null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Check if this service is ready to receive requests (asynchronously) - * Returns a message describing the status of this service - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - -
Status Code Description Response Headers
200 Successful Response -
- */ - public okhttp3.Call readyReadyGetAsync(final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = readyReadyGetValidateBeforeCall(_callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } -} diff --git a/src/main/java/io/openepi/soil/api/SoilApi.java b/src/main/java/io/openepi/soil/api/SoilApi.java deleted file mode 100644 index ac7b72d..0000000 --- a/src/main/java/io/openepi/soil/api/SoilApi.java +++ /dev/null @@ -1,580 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.api; - -import io.openepi.common.ApiCallback; -import io.openepi.soil.ApiClient; -import io.openepi.common.ApiException; -import io.openepi.common.ApiResponse; -import io.openepi.soil.Configuration; -import io.openepi.common.Pair; - -import com.google.gson.reflect.TypeToken; - - -import java.math.BigDecimal; - -import io.openepi.soil.model.SoilDepthLabels; -import io.openepi.soil.model.SoilPropertiesCodes; -import io.openepi.soil.model.SoilPropertyJSON; -import io.openepi.soil.model.SoilPropertyValueTypes; -import io.openepi.soil.model.SoilTypeJSON; -import io.openepi.soil.model.SoilTypeSummaryJSON; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class SoilApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public SoilApi() { - this(Configuration.getDefaultApiClient()); - } - - public SoilApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for getSoilPropertyPropertyGet - * @param lon Longitude (required) - * @param lat Latitude (required) - * @param depths List of depths to include in the query. (required) - * @param properties List of soil properties to include in the query. (required) - * @param values List of values to include in the query. (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call getSoilPropertyPropertyGetCall(BigDecimal lon, BigDecimal lat, List depths, List properties, List values, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/property"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - if (lon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lon", lon)); - } - - if (lat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lat", lat)); - } - - if (depths != null) { - localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "depths", depths)); - } - - if (properties != null) { - localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "properties", properties)); - } - - if (values != null) { - localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "values", values)); - } - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call getSoilPropertyPropertyGetValidateBeforeCall(BigDecimal lon, BigDecimal lat, List depths, List properties, List values, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'lon' is set - if (lon == null) { - throw new ApiException("Missing the required parameter 'lon' when calling getSoilPropertyPropertyGet(Async)"); - } - - // verify the required parameter 'lat' is set - if (lat == null) { - throw new ApiException("Missing the required parameter 'lat' when calling getSoilPropertyPropertyGet(Async)"); - } - - // verify the required parameter 'depths' is set - if (depths == null) { - throw new ApiException("Missing the required parameter 'depths' when calling getSoilPropertyPropertyGet(Async)"); - } - - // verify the required parameter 'properties' is set - if (properties == null) { - throw new ApiException("Missing the required parameter 'properties' when calling getSoilPropertyPropertyGet(Async)"); - } - - // verify the required parameter 'values' is set - if (values == null) { - throw new ApiException("Missing the required parameter 'values' when calling getSoilPropertyPropertyGet(Async)"); - } - - return getSoilPropertyPropertyGetCall(lon, lat, depths, properties, values, _callback); - - } - - /** - * Get soil property - * Returns the values of the soil properties for the given location and depths. Note: The ocs property is only available for the 0-30cm depth and vice versa. If the depth and property are incompatible, the response will not include the property. - * @param lon Longitude (required) - * @param lat Latitude (required) - * @param depths List of depths to include in the query. (required) - * @param properties List of soil properties to include in the query. (required) - * @param values List of values to include in the query. (required) - * @return SoilPropertyJSON - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public SoilPropertyJSON getSoilProperty(BigDecimal lon, BigDecimal lat, List depths, List properties, List values) throws ApiException { - ApiResponse localVarResp = getSoilPropertyPropertyGetWithHttpInfo(lon, lat, depths, properties, values); - return localVarResp.getData(); - } - - /** - * Get soil property - * Returns the values of the soil properties for the given location and depths. Note: The ocs property is only available for the 0-30cm depth and vice versa. If the depth and property are incompatible, the response will not include the property. - * @param lon Longitude (required) - * @param lat Latitude (required) - * @param depths List of depths to include in the query. (required) - * @param properties List of soil properties to include in the query. (required) - * @param values List of values to include in the query. (required) - * @return ApiResponse<SoilPropertyJSON> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public ApiResponse getSoilPropertyPropertyGetWithHttpInfo(BigDecimal lon, BigDecimal lat, List depths, List properties, List values) throws ApiException { - okhttp3.Call localVarCall = getSoilPropertyPropertyGetValidateBeforeCall(lon, lat, depths, properties, values, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Get soil property (asynchronously) - * Returns the values of the soil properties for the given location and depths. Note: The ocs property is only available for the 0-30cm depth and vice versa. If the depth and property are incompatible, the response will not include the property. - * @param lon Longitude (required) - * @param lat Latitude (required) - * @param depths List of depths to include in the query. (required) - * @param properties List of soil properties to include in the query. (required) - * @param values List of values to include in the query. (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call getSoilPropertyAsync(BigDecimal lon, BigDecimal lat, List depths, List properties, List values, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = getSoilPropertyPropertyGetValidateBeforeCall(lon, lat, depths, properties, values, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for getSoilTypeSummaryTypeSummaryGet - * @param minLon Minimum longitude (required) - * @param maxLon Maximum longitude (required) - * @param minLat Minimum latitude (required) - * @param maxLat Maximum latitude (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call getSoilTypeSummaryTypeSummaryGetCall(BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/type/summary"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - if (minLon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("min_lon", minLon)); - } - - if (maxLon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("max_lon", maxLon)); - } - - if (minLat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("min_lat", minLat)); - } - - if (maxLat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("max_lat", maxLat)); - } - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call getSoilTypeSummaryTypeSummaryGetValidateBeforeCall(BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'minLon' is set - if (minLon == null) { - throw new ApiException("Missing the required parameter 'minLon' when calling getSoilTypeSummaryTypeSummaryGet(Async)"); - } - - // verify the required parameter 'maxLon' is set - if (maxLon == null) { - throw new ApiException("Missing the required parameter 'maxLon' when calling getSoilTypeSummaryTypeSummaryGet(Async)"); - } - - // verify the required parameter 'minLat' is set - if (minLat == null) { - throw new ApiException("Missing the required parameter 'minLat' when calling getSoilTypeSummaryTypeSummaryGet(Async)"); - } - - // verify the required parameter 'maxLat' is set - if (maxLat == null) { - throw new ApiException("Missing the required parameter 'maxLat' when calling getSoilTypeSummaryTypeSummaryGet(Async)"); - } - - return getSoilTypeSummaryTypeSummaryGetCall(minLon, maxLon, minLat, maxLat, _callback); - - } - - /** - * Get soil type summary - * Returns the summary of the soil types present in the given bounding box, represented by a mapping of each soil type to the number of occurrences in the bounding box - * @param minLon Minimum longitude (required) - * @param maxLon Maximum longitude (required) - * @param minLat Minimum latitude (required) - * @param maxLat Maximum latitude (required) - * @return SoilTypeSummaryJSON - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public SoilTypeSummaryJSON getSoilTypeSummary(BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat) throws ApiException { - ApiResponse localVarResp = getSoilTypeSummaryTypeSummaryGetWithHttpInfo(minLon, maxLon, minLat, maxLat); - return localVarResp.getData(); - } - - /** - * Get soil type summary - * Returns the summary of the soil types present in the given bounding box, represented by a mapping of each soil type to the number of occurrences in the bounding box - * @param minLon Minimum longitude (required) - * @param maxLon Maximum longitude (required) - * @param minLat Minimum latitude (required) - * @param maxLat Maximum latitude (required) - * @return ApiResponse<SoilTypeSummaryJSON> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public ApiResponse getSoilTypeSummaryTypeSummaryGetWithHttpInfo(BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat) throws ApiException { - okhttp3.Call localVarCall = getSoilTypeSummaryTypeSummaryGetValidateBeforeCall(minLon, maxLon, minLat, maxLat, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Get soil type summary (asynchronously) - * Returns the summary of the soil types present in the given bounding box, represented by a mapping of each soil type to the number of occurrences in the bounding box - * @param minLon Minimum longitude (required) - * @param maxLon Maximum longitude (required) - * @param minLat Minimum latitude (required) - * @param maxLat Maximum latitude (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call getSoilTypeSummaryAsync(BigDecimal minLon, BigDecimal maxLon, BigDecimal minLat, BigDecimal maxLat, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = getSoilTypeSummaryTypeSummaryGetValidateBeforeCall(minLon, maxLon, minLat, maxLat, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for getSoilTypeTypeGet - * @param lon Longitude (required) - * @param lat Latitude (required) - * @param topK Number of most probable soil types that will be returned, sorted by probability in descending order (optional, default to 0) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call getSoilTypeTypeGetCall(BigDecimal lon, BigDecimal lat, Integer topK, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/type"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - if (lon != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lon", lon)); - } - - if (lat != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("lat", lat)); - } - - if (topK != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("top_k", topK)); - } - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call getSoilTypeTypeGetValidateBeforeCall(BigDecimal lon, BigDecimal lat, Integer topK, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'lon' is set - if (lon == null) { - throw new ApiException("Missing the required parameter 'lon' when calling getSoilTypeTypeGet(Async)"); - } - - // verify the required parameter 'lat' is set - if (lat == null) { - throw new ApiException("Missing the required parameter 'lat' when calling getSoilTypeTypeGet(Async)"); - } - - return getSoilTypeTypeGetCall(lon, lat, topK, _callback); - - } - - /** - * Get soil type - * Returns the most probable soil type for the given location - * @param lon Longitude (required) - * @param lat Latitude (required) - * @param topK Number of most probable soil types that will be returned, sorted by probability in descending order (optional, default to 0) - * @return SoilTypeJSON - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public SoilTypeJSON getSoilType(BigDecimal lon, BigDecimal lat, Integer topK) throws ApiException { - ApiResponse localVarResp = getSoilTypeTypeGetWithHttpInfo(lon, lat, topK); - return localVarResp.getData(); - } - - /** - * Get soil type - * Returns the most probable soil type for the given location - * @param lon Longitude (required) - * @param lat Latitude (required) - * @param topK Number of most probable soil types that will be returned, sorted by probability in descending order (optional, default to 0) - * @return ApiResponse<SoilTypeJSON> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public ApiResponse getSoilTypeTypeGetWithHttpInfo(BigDecimal lon, BigDecimal lat, Integer topK) throws ApiException { - okhttp3.Call localVarCall = getSoilTypeTypeGetValidateBeforeCall(lon, lat, topK, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Get soil type (asynchronously) - * Returns the most probable soil type for the given location - * @param lon Longitude (required) - * @param lat Latitude (required) - * @param topK Number of most probable soil types that will be returned, sorted by probability in descending order (optional, default to 0) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - -
Status Code Description Response Headers
200 Successful Response -
422 Validation Error -
- */ - public okhttp3.Call getSoilTypeAsync(BigDecimal lon, BigDecimal lat, Integer topK, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = getSoilTypeTypeGetValidateBeforeCall(lon, lat, topK, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } -} diff --git a/src/main/java/io/openepi/soil/model/AbstractOpenApiSchema.java b/src/main/java/io/openepi/soil/model/AbstractOpenApiSchema.java deleted file mode 100644 index 23c0e36..0000000 --- a/src/main/java/io/openepi/soil/model/AbstractOpenApiSchema.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import java.util.Map; - -/** - * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public abstract class AbstractOpenApiSchema { - - // store the actual instance of the schema/object - private Object instance; - - // is nullable - private Boolean isNullable; - - // schema type (e.g. oneOf, anyOf) - private final String schemaType; - - public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { - this.schemaType = schemaType; - this.isNullable = isNullable; - } - - /** - * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object - * - * @return an instance of the actual schema/object - */ - public abstract Map> getSchemas(); - - /** - * Get the actual instance - * - * @return an instance of the actual schema/object - */ - //@JsonValue - public Object getActualInstance() {return instance;} - - /** - * Set the actual instance - * - * @param instance the actual instance of the schema/object - */ - public void setActualInstance(Object instance) {this.instance = instance;} - - /** - * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well - * - * @return an instance of the actual schema/object - */ - public Object getActualInstanceRecursively() { - return getActualInstanceRecursively(this); - } - - private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { - if (object.getActualInstance() == null) { - return null; - } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { - return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); - } else { - return object.getActualInstance(); - } - } - - /** - * Get the schema type (e.g. anyOf, oneOf) - * - * @return the schema type - */ - public String getSchemaType() { - return schemaType; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ").append(getClass()).append(" {\n"); - sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); - sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); - sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; - return Objects.equals(this.instance, a.instance) && - Objects.equals(this.isNullable, a.isNullable) && - Objects.equals(this.schemaType, a.schemaType); - } - - @Override - public int hashCode() { - return Objects.hash(instance, isNullable, schemaType); - } - - /** - * Is nullable - * - * @return true if it's nullable - */ - public Boolean isNullable() { - if (Boolean.TRUE.equals(isNullable)) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } - - - -} diff --git a/src/main/java/io/openepi/soil/model/BoundingBoxGeometry.java b/src/main/java/io/openepi/soil/model/BoundingBoxGeometry.java deleted file mode 100644 index 7850b30..0000000 --- a/src/main/java/io/openepi/soil/model/BoundingBoxGeometry.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.soil.model.GeometryType; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * BoundingBoxGeometry - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class BoundingBoxGeometry { - public static final String SERIALIZED_NAME_COORDINATES = "coordinates"; - @SerializedName(SERIALIZED_NAME_COORDINATES) - private List>> coordinates = new ArrayList<>(); - - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private GeometryType type; - - public BoundingBoxGeometry() { - } - - public BoundingBoxGeometry coordinates(List>> coordinates) { - this.coordinates = coordinates; - return this; - } - - public BoundingBoxGeometry addCoordinatesItem(List> coordinatesItem) { - if (this.coordinates == null) { - this.coordinates = new ArrayList<>(); - } - this.coordinates.add(coordinatesItem); - return this; - } - - /** - * [[[min_lon, min_lat], [max_lon, min_lat], [max_lon, max_lat], [min_lon, max_lat], [min_lon, min_lat]]] - * @return coordinates - */ - @javax.annotation.Nonnull - public List>> getCoordinates() { - return coordinates; - } - - public void setCoordinates(List>> coordinates) { - this.coordinates = coordinates; - } - - - public BoundingBoxGeometry type(GeometryType type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nonnull - public GeometryType getType() { - return type; - } - - public void setType(GeometryType type) { - this.type = type; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - BoundingBoxGeometry boundingBoxGeometry = (BoundingBoxGeometry) o; - return Objects.equals(this.coordinates, boundingBoxGeometry.coordinates) && - Objects.equals(this.type, boundingBoxGeometry.type); - } - - @Override - public int hashCode() { - return Objects.hash(coordinates, type); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class BoundingBoxGeometry {\n"); - sb.append(" coordinates: ").append(toIndentedString(coordinates)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("coordinates"); - openapiFields.add("type"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("coordinates"); - openapiRequiredFields.add("type"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to BoundingBoxGeometry - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!BoundingBoxGeometry.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in BoundingBoxGeometry is not found in the empty JSON string", BoundingBoxGeometry.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!BoundingBoxGeometry.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `BoundingBoxGeometry` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : BoundingBoxGeometry.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the required json array is present - if (jsonObj.get("coordinates") == null) { - throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); - } else if (!jsonObj.get("coordinates").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `coordinates` to be an array in the JSON string but got `%s`", jsonObj.get("coordinates").toString())); - } - // validate the required field `type` - GeometryType.validateJsonElement(jsonObj.get("type")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!BoundingBoxGeometry.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'BoundingBoxGeometry' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(BoundingBoxGeometry.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, BoundingBoxGeometry value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public BoundingBoxGeometry read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of BoundingBoxGeometry given an JSON string - * - * @param jsonString JSON string - * @return An instance of BoundingBoxGeometry - * @throws IOException if the JSON string is invalid with respect to BoundingBoxGeometry - */ - public static BoundingBoxGeometry fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, BoundingBoxGeometry.class); - } - - /** - * Convert an instance of BoundingBoxGeometry to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/DepthRange.java b/src/main/java/io/openepi/soil/model/DepthRange.java deleted file mode 100644 index 56874df..0000000 --- a/src/main/java/io/openepi/soil/model/DepthRange.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.soil.model.SoilDepths; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * DepthRange - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class DepthRange { - public static final String SERIALIZED_NAME_TOP_DEPTH = "top_depth"; - @SerializedName(SERIALIZED_NAME_TOP_DEPTH) - private SoilDepths topDepth; - - public static final String SERIALIZED_NAME_BOTTOM_DEPTH = "bottom_depth"; - @SerializedName(SERIALIZED_NAME_BOTTOM_DEPTH) - private SoilDepths bottomDepth; - - public static final String SERIALIZED_NAME_UNIT_DEPTH = "unit_depth"; - @SerializedName(SERIALIZED_NAME_UNIT_DEPTH) - private Object unitDepth; - - public DepthRange() { - } - - public DepthRange topDepth(SoilDepths topDepth) { - this.topDepth = topDepth; - return this; - } - - /** - * The top depth - * @return topDepth - */ - @javax.annotation.Nonnull - public SoilDepths getTopDepth() { - return topDepth; - } - - public void setTopDepth(SoilDepths topDepth) { - this.topDepth = topDepth; - } - - - public DepthRange bottomDepth(SoilDepths bottomDepth) { - this.bottomDepth = bottomDepth; - return this; - } - - /** - * The bottom depth - * @return bottomDepth - */ - @javax.annotation.Nonnull - public SoilDepths getBottomDepth() { - return bottomDepth; - } - - public void setBottomDepth(SoilDepths bottomDepth) { - this.bottomDepth = bottomDepth; - } - - - public DepthRange unitDepth(Object unitDepth) { - this.unitDepth = unitDepth; - return this; - } - - /** - * The unit of the depth range - * @return unitDepth - */ - @javax.annotation.Nullable - public Object getUnitDepth() { - return unitDepth; - } - - public void setUnitDepth(Object unitDepth) { - this.unitDepth = unitDepth; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - DepthRange depthRange = (DepthRange) o; - return Objects.equals(this.topDepth, depthRange.topDepth) && - Objects.equals(this.bottomDepth, depthRange.bottomDepth) && - Objects.equals(this.unitDepth, depthRange.unitDepth); - } - - @Override - public int hashCode() { - return Objects.hash(topDepth, bottomDepth, unitDepth); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class DepthRange {\n"); - sb.append(" topDepth: ").append(toIndentedString(topDepth)).append("\n"); - sb.append(" bottomDepth: ").append(toIndentedString(bottomDepth)).append("\n"); - sb.append(" unitDepth: ").append(toIndentedString(unitDepth)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("top_depth"); - openapiFields.add("bottom_depth"); - openapiFields.add("unit_depth"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("top_depth"); - openapiRequiredFields.add("bottom_depth"); - openapiRequiredFields.add("unit_depth"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to DepthRange - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!DepthRange.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in DepthRange is not found in the empty JSON string", DepthRange.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!DepthRange.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `DepthRange` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : DepthRange.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `top_depth` - SoilDepths.validateJsonElement(jsonObj.get("top_depth")); - // validate the required field `bottom_depth` - SoilDepths.validateJsonElement(jsonObj.get("bottom_depth")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!DepthRange.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'DepthRange' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(DepthRange.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, DepthRange value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public DepthRange read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of DepthRange given an JSON string - * - * @param jsonString JSON string - * @return An instance of DepthRange - * @throws IOException if the JSON string is invalid with respect to DepthRange - */ - public static DepthRange fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, DepthRange.class); - } - - /** - * Convert an instance of DepthRange to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/GeometryType.java b/src/main/java/io/openepi/soil/model/GeometryType.java deleted file mode 100644 index acc5b7c..0000000 --- a/src/main/java/io/openepi/soil/model/GeometryType.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets GeometryType - */ -@JsonAdapter(GeometryType.Adapter.class) -public enum GeometryType { - - POINT("Point"), - - POLYGON("Polygon"); - - private String value; - - GeometryType(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static GeometryType fromValue(String value) { - for (GeometryType b : GeometryType.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final GeometryType enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public GeometryType read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return GeometryType.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - GeometryType.fromValue(value); - } -} - diff --git a/src/main/java/io/openepi/soil/model/HTTPValidationError.java b/src/main/java/io/openepi/soil/model/HTTPValidationError.java deleted file mode 100644 index 1c18229..0000000 --- a/src/main/java/io/openepi/soil/model/HTTPValidationError.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.soil.model.ValidationError; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * HTTPValidationError - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class HTTPValidationError { - public static final String SERIALIZED_NAME_DETAIL = "detail"; - @SerializedName(SERIALIZED_NAME_DETAIL) - private List detail = new ArrayList<>(); - - public HTTPValidationError() { - } - - public HTTPValidationError detail(List detail) { - this.detail = detail; - return this; - } - - public HTTPValidationError addDetailItem(ValidationError detailItem) { - if (this.detail == null) { - this.detail = new ArrayList<>(); - } - this.detail.add(detailItem); - return this; - } - - /** - * Get detail - * @return detail - */ - @javax.annotation.Nullable - public List getDetail() { - return detail; - } - - public void setDetail(List detail) { - this.detail = detail; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - HTTPValidationError htTPValidationError = (HTTPValidationError) o; - return Objects.equals(this.detail, htTPValidationError.detail); - } - - @Override - public int hashCode() { - return Objects.hash(detail); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class HTTPValidationError {\n"); - sb.append(" detail: ").append(toIndentedString(detail)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("detail"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to HTTPValidationError - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!HTTPValidationError.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in HTTPValidationError is not found in the empty JSON string", HTTPValidationError.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!HTTPValidationError.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `HTTPValidationError` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("detail") != null && !jsonObj.get("detail").isJsonNull()) { - JsonArray jsonArraydetail = jsonObj.getAsJsonArray("detail"); - if (jsonArraydetail != null) { - // ensure the json data is an array - if (!jsonObj.get("detail").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `detail` to be an array in the JSON string but got `%s`", jsonObj.get("detail").toString())); - } - - // validate the optional field `detail` (array) - for (int i = 0; i < jsonArraydetail.size(); i++) { - ValidationError.validateJsonElement(jsonArraydetail.get(i)); - }; - } - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!HTTPValidationError.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'HTTPValidationError' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(HTTPValidationError.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, HTTPValidationError value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public HTTPValidationError read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of HTTPValidationError given an JSON string - * - * @param jsonString JSON string - * @return An instance of HTTPValidationError - * @throws IOException if the JSON string is invalid with respect to HTTPValidationError - */ - public static HTTPValidationError fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, HTTPValidationError.class); - } - - /** - * Convert an instance of HTTPValidationError to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/PointGeometry.java b/src/main/java/io/openepi/soil/model/PointGeometry.java deleted file mode 100644 index 5a40357..0000000 --- a/src/main/java/io/openepi/soil/model/PointGeometry.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.soil.model.GeometryType; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * PointGeometry - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class PointGeometry { - public static final String SERIALIZED_NAME_COORDINATES = "coordinates"; - @SerializedName(SERIALIZED_NAME_COORDINATES) - private List coordinates = new ArrayList<>(); - - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private GeometryType type; - - public PointGeometry() { - } - - public PointGeometry coordinates(List coordinates) { - this.coordinates = coordinates; - return this; - } - - public PointGeometry addCoordinatesItem(BigDecimal coordinatesItem) { - if (this.coordinates == null) { - this.coordinates = new ArrayList<>(); - } - this.coordinates.add(coordinatesItem); - return this; - } - - /** - * [longitude, latitude] decimal coordinates - * @return coordinates - */ - @javax.annotation.Nonnull - public List getCoordinates() { - return coordinates; - } - - public void setCoordinates(List coordinates) { - this.coordinates = coordinates; - } - - - public PointGeometry type(GeometryType type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nonnull - public GeometryType getType() { - return type; - } - - public void setType(GeometryType type) { - this.type = type; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - PointGeometry pointGeometry = (PointGeometry) o; - return Objects.equals(this.coordinates, pointGeometry.coordinates) && - Objects.equals(this.type, pointGeometry.type); - } - - @Override - public int hashCode() { - return Objects.hash(coordinates, type); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class PointGeometry {\n"); - sb.append(" coordinates: ").append(toIndentedString(coordinates)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("coordinates"); - openapiFields.add("type"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("coordinates"); - openapiRequiredFields.add("type"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to PointGeometry - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!PointGeometry.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in PointGeometry is not found in the empty JSON string", PointGeometry.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!PointGeometry.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `PointGeometry` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : PointGeometry.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the required json array is present - if (jsonObj.get("coordinates") == null) { - throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); - } else if (!jsonObj.get("coordinates").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `coordinates` to be an array in the JSON string but got `%s`", jsonObj.get("coordinates").toString())); - } - // validate the required field `type` - GeometryType.validateJsonElement(jsonObj.get("type")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!PointGeometry.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'PointGeometry' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(PointGeometry.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, PointGeometry value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public PointGeometry read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of PointGeometry given an JSON string - * - * @param jsonString JSON string - * @return An instance of PointGeometry - * @throws IOException if the JSON string is invalid with respect to PointGeometry - */ - public static PointGeometry fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, PointGeometry.class); - } - - /** - * Convert an instance of PointGeometry to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilConversionFactors.java b/src/main/java/io/openepi/soil/model/SoilConversionFactors.java deleted file mode 100644 index 2d7f6f0..0000000 --- a/src/main/java/io/openepi/soil/model/SoilConversionFactors.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets SoilConversionFactors - */ -@JsonAdapter(SoilConversionFactors.Adapter.class) -public enum SoilConversionFactors { - - NUMBER_10(10), - - NUMBER_100(100); - - private Integer value; - - SoilConversionFactors(Integer value) { - this.value = value; - } - - public Integer getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static SoilConversionFactors fromValue(Integer value) { - for (SoilConversionFactors b : SoilConversionFactors.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final SoilConversionFactors enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public SoilConversionFactors read(final JsonReader jsonReader) throws IOException { - Integer value = jsonReader.nextInt(); - return SoilConversionFactors.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - Integer value = jsonElement.getAsInt(); - SoilConversionFactors.fromValue(value); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilDepth.java b/src/main/java/io/openepi/soil/model/SoilDepth.java deleted file mode 100644 index 95c5efc..0000000 --- a/src/main/java/io/openepi/soil/model/SoilDepth.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.soil.model.DepthRange; -import io.openepi.soil.model.SoilDepthLabels; -import io.openepi.soil.model.SoilPropertyValues; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * SoilDepth - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SoilDepth { - public static final String SERIALIZED_NAME_RANGE = "range"; - @SerializedName(SERIALIZED_NAME_RANGE) - private DepthRange range; - - public static final String SERIALIZED_NAME_LABEL = "label"; - @SerializedName(SERIALIZED_NAME_LABEL) - private SoilDepthLabels label; - - public static final String SERIALIZED_NAME_VALUES = "values"; - @SerializedName(SERIALIZED_NAME_VALUES) - private SoilPropertyValues values; - - public SoilDepth() { - } - - public SoilDepth range(DepthRange range) { - this.range = range; - return this; - } - - /** - * The soil depth range - * @return range - */ - @javax.annotation.Nonnull - public DepthRange getRange() { - return range; - } - - public void setRange(DepthRange range) { - this.range = range; - } - - - public SoilDepth label(SoilDepthLabels label) { - this.label = label; - return this; - } - - /** - * The soil depth label - * @return label - */ - @javax.annotation.Nonnull - public SoilDepthLabels getLabel() { - return label; - } - - public void setLabel(SoilDepthLabels label) { - this.label = label; - } - - - public SoilDepth values(SoilPropertyValues values) { - this.values = values; - return this; - } - - /** - * The queried soil property values - * @return values - */ - @javax.annotation.Nonnull - public SoilPropertyValues getValues() { - return values; - } - - public void setValues(SoilPropertyValues values) { - this.values = values; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SoilDepth soilDepth = (SoilDepth) o; - return Objects.equals(this.range, soilDepth.range) && - Objects.equals(this.label, soilDepth.label) && - Objects.equals(this.values, soilDepth.values); - } - - @Override - public int hashCode() { - return Objects.hash(range, label, values); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SoilDepth {\n"); - sb.append(" range: ").append(toIndentedString(range)).append("\n"); - sb.append(" label: ").append(toIndentedString(label)).append("\n"); - sb.append(" values: ").append(toIndentedString(values)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("range"); - openapiFields.add("label"); - openapiFields.add("values"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("range"); - openapiRequiredFields.add("label"); - openapiRequiredFields.add("values"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SoilDepth - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SoilDepth.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SoilDepth is not found in the empty JSON string", SoilDepth.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SoilDepth.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SoilDepth` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SoilDepth.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `range` - DepthRange.validateJsonElement(jsonObj.get("range")); - // validate the required field `label` - SoilDepthLabels.validateJsonElement(jsonObj.get("label")); - // validate the required field `values` - SoilPropertyValues.validateJsonElement(jsonObj.get("values")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SoilDepth.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SoilDepth' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SoilDepth.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SoilDepth value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SoilDepth read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SoilDepth given an JSON string - * - * @param jsonString JSON string - * @return An instance of SoilDepth - * @throws IOException if the JSON string is invalid with respect to SoilDepth - */ - public static SoilDepth fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SoilDepth.class); - } - - /** - * Convert an instance of SoilDepth to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilDepthLabels.java b/src/main/java/io/openepi/soil/model/SoilDepthLabels.java deleted file mode 100644 index 22a7b7e..0000000 --- a/src/main/java/io/openepi/soil/model/SoilDepthLabels.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets SoilDepthLabels - */ -@JsonAdapter(SoilDepthLabels.Adapter.class) -public enum SoilDepthLabels { - - _0_5CM("0-5cm"), - - _0_30CM("0-30cm"), - - _5_15CM("5-15cm"), - - _15_30CM("15-30cm"), - - _30_60CM("30-60cm"), - - _60_100CM("60-100cm"), - - _100_200CM("100-200cm"); - - private String value; - - SoilDepthLabels(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static SoilDepthLabels fromValue(String value) { - for (SoilDepthLabels b : SoilDepthLabels.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final SoilDepthLabels enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public SoilDepthLabels read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return SoilDepthLabels.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - SoilDepthLabels.fromValue(value); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilDepths.java b/src/main/java/io/openepi/soil/model/SoilDepths.java deleted file mode 100644 index 774a74a..0000000 --- a/src/main/java/io/openepi/soil/model/SoilDepths.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets SoilDepths - */ -@JsonAdapter(SoilDepths.Adapter.class) -public enum SoilDepths { - - NUMBER_0(0), - - NUMBER_5(5), - - NUMBER_15(15), - - NUMBER_30(30), - - NUMBER_60(60), - - NUMBER_100(100), - - NUMBER_200(200); - - private Integer value; - - SoilDepths(Integer value) { - this.value = value; - } - - public Integer getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static SoilDepths fromValue(Integer value) { - for (SoilDepths b : SoilDepths.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final SoilDepths enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public SoilDepths read(final JsonReader jsonReader) throws IOException { - Integer value = jsonReader.nextInt(); - return SoilDepths.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - Integer value = jsonElement.getAsInt(); - SoilDepths.fromValue(value); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilLayer.java b/src/main/java/io/openepi/soil/model/SoilLayer.java deleted file mode 100644 index 35e6e8f..0000000 --- a/src/main/java/io/openepi/soil/model/SoilLayer.java +++ /dev/null @@ -1,322 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.soil.model.SoilDepth; -import io.openepi.soil.model.SoilPropertiesCodes; -import io.openepi.soil.model.SoilPropertyUnit; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * SoilLayer - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SoilLayer { - public static final String SERIALIZED_NAME_CODE = "code"; - @SerializedName(SERIALIZED_NAME_CODE) - private SoilPropertiesCodes code; - - public static final String SERIALIZED_NAME_NAME = "name"; - @SerializedName(SERIALIZED_NAME_NAME) - private String name; - - public static final String SERIALIZED_NAME_UNIT_MEASURE = "unit_measure"; - @SerializedName(SERIALIZED_NAME_UNIT_MEASURE) - private SoilPropertyUnit unitMeasure; - - public static final String SERIALIZED_NAME_DEPTHS = "depths"; - @SerializedName(SERIALIZED_NAME_DEPTHS) - private List depths = new ArrayList<>(); - - public SoilLayer() { - } - - public SoilLayer code(SoilPropertiesCodes code) { - this.code = code; - return this; - } - - /** - * The soil property code - * @return code - */ - @javax.annotation.Nonnull - public SoilPropertiesCodes getCode() { - return code; - } - - public void setCode(SoilPropertiesCodes code) { - this.code = code; - } - - - public SoilLayer name(String name) { - this.name = name; - return this; - } - - /** - * The name of the soil property - * @return name - */ - @javax.annotation.Nonnull - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - - public SoilLayer unitMeasure(SoilPropertyUnit unitMeasure) { - this.unitMeasure = unitMeasure; - return this; - } - - /** - * The unit of the soil property - * @return unitMeasure - */ - @javax.annotation.Nonnull - public SoilPropertyUnit getUnitMeasure() { - return unitMeasure; - } - - public void setUnitMeasure(SoilPropertyUnit unitMeasure) { - this.unitMeasure = unitMeasure; - } - - - public SoilLayer depths(List depths) { - this.depths = depths; - return this; - } - - public SoilLayer addDepthsItem(SoilDepth depthsItem) { - if (this.depths == null) { - this.depths = new ArrayList<>(); - } - this.depths.add(depthsItem); - return this; - } - - /** - * The queried soil depths with values - * @return depths - */ - @javax.annotation.Nonnull - public List getDepths() { - return depths; - } - - public void setDepths(List depths) { - this.depths = depths; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SoilLayer soilLayer = (SoilLayer) o; - return Objects.equals(this.code, soilLayer.code) && - Objects.equals(this.name, soilLayer.name) && - Objects.equals(this.unitMeasure, soilLayer.unitMeasure) && - Objects.equals(this.depths, soilLayer.depths); - } - - @Override - public int hashCode() { - return Objects.hash(code, name, unitMeasure, depths); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SoilLayer {\n"); - sb.append(" code: ").append(toIndentedString(code)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" unitMeasure: ").append(toIndentedString(unitMeasure)).append("\n"); - sb.append(" depths: ").append(toIndentedString(depths)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("code"); - openapiFields.add("name"); - openapiFields.add("unit_measure"); - openapiFields.add("depths"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("code"); - openapiRequiredFields.add("name"); - openapiRequiredFields.add("unit_measure"); - openapiRequiredFields.add("depths"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SoilLayer - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SoilLayer.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SoilLayer is not found in the empty JSON string", SoilLayer.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SoilLayer.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SoilLayer` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SoilLayer.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `code` - SoilPropertiesCodes.validateJsonElement(jsonObj.get("code")); - if (!jsonObj.get("name").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); - } - // validate the required field `unit_measure` - SoilPropertyUnit.validateJsonElement(jsonObj.get("unit_measure")); - // ensure the json data is an array - if (!jsonObj.get("depths").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `depths` to be an array in the JSON string but got `%s`", jsonObj.get("depths").toString())); - } - - JsonArray jsonArraydepths = jsonObj.getAsJsonArray("depths"); - // validate the required field `depths` (array) - for (int i = 0; i < jsonArraydepths.size(); i++) { - SoilDepth.validateJsonElement(jsonArraydepths.get(i)); - }; - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SoilLayer.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SoilLayer' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SoilLayer.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SoilLayer value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SoilLayer read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SoilLayer given an JSON string - * - * @param jsonString JSON string - * @return An instance of SoilLayer - * @throws IOException if the JSON string is invalid with respect to SoilLayer - */ - public static SoilLayer fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SoilLayer.class); - } - - /** - * Convert an instance of SoilLayer to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilLayerList.java b/src/main/java/io/openepi/soil/model/SoilLayerList.java deleted file mode 100644 index ed02446..0000000 --- a/src/main/java/io/openepi/soil/model/SoilLayerList.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.soil.model.SoilLayer; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * SoilLayerList - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SoilLayerList { - public static final String SERIALIZED_NAME_LAYERS = "layers"; - @SerializedName(SERIALIZED_NAME_LAYERS) - private List layers = new ArrayList<>(); - - public SoilLayerList() { - } - - public SoilLayerList layers(List layers) { - this.layers = layers; - return this; - } - - public SoilLayerList addLayersItem(SoilLayer layersItem) { - if (this.layers == null) { - this.layers = new ArrayList<>(); - } - this.layers.add(layersItem); - return this; - } - - /** - * The queried soil property layers - * @return layers - */ - @javax.annotation.Nonnull - public List getLayers() { - return layers; - } - - public void setLayers(List layers) { - this.layers = layers; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SoilLayerList soilLayerList = (SoilLayerList) o; - return Objects.equals(this.layers, soilLayerList.layers); - } - - @Override - public int hashCode() { - return Objects.hash(layers); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SoilLayerList {\n"); - sb.append(" layers: ").append(toIndentedString(layers)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("layers"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("layers"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SoilLayerList - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SoilLayerList.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SoilLayerList is not found in the empty JSON string", SoilLayerList.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SoilLayerList.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SoilLayerList` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SoilLayerList.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the json data is an array - if (!jsonObj.get("layers").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `layers` to be an array in the JSON string but got `%s`", jsonObj.get("layers").toString())); - } - - JsonArray jsonArraylayers = jsonObj.getAsJsonArray("layers"); - // validate the required field `layers` (array) - for (int i = 0; i < jsonArraylayers.size(); i++) { - SoilLayer.validateJsonElement(jsonArraylayers.get(i)); - }; - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SoilLayerList.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SoilLayerList' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SoilLayerList.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SoilLayerList value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SoilLayerList read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SoilLayerList given an JSON string - * - * @param jsonString JSON string - * @return An instance of SoilLayerList - * @throws IOException if the JSON string is invalid with respect to SoilLayerList - */ - public static SoilLayerList fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SoilLayerList.class); - } - - /** - * Convert an instance of SoilLayerList to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilMappedUnits.java b/src/main/java/io/openepi/soil/model/SoilMappedUnits.java deleted file mode 100644 index ae2d46e..0000000 --- a/src/main/java/io/openepi/soil/model/SoilMappedUnits.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets SoilMappedUnits - */ -@JsonAdapter(SoilMappedUnits.Adapter.class) -public enum SoilMappedUnits { - - CG_CM_("cg/cm³"), - - MMOL_C_KG("mmol(c)/kg"), - - CM_DM_("cm³/dm³"), - - G_KG("g/kg"), - - CG_KG("cg/kg"), - - HG_M_("hg/m³"), - - T_HA("t/ha"), - - P_H_10("pH*10"), - - DG_KG("dg/kg"); - - private String value; - - SoilMappedUnits(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static SoilMappedUnits fromValue(String value) { - for (SoilMappedUnits b : SoilMappedUnits.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final SoilMappedUnits enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public SoilMappedUnits read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return SoilMappedUnits.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - SoilMappedUnits.fromValue(value); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilPropertiesCodes.java b/src/main/java/io/openepi/soil/model/SoilPropertiesCodes.java deleted file mode 100644 index 3867ed7..0000000 --- a/src/main/java/io/openepi/soil/model/SoilPropertiesCodes.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets SoilPropertiesCodes - */ -@JsonAdapter(SoilPropertiesCodes.Adapter.class) -public enum SoilPropertiesCodes { - - BDOD("bdod"), - - CEC("cec"), - - CFVO("cfvo"), - - CLAY("clay"), - - NITROGEN("nitrogen"), - - OCD("ocd"), - - OCS("ocs"), - - PHH2O("phh2o"), - - SAND("sand"), - - SILT("silt"), - - SOC("soc"); - - private String value; - - SoilPropertiesCodes(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static SoilPropertiesCodes fromValue(String value) { - for (SoilPropertiesCodes b : SoilPropertiesCodes.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final SoilPropertiesCodes enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public SoilPropertiesCodes read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return SoilPropertiesCodes.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - SoilPropertiesCodes.fromValue(value); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilPropertyJSON.java b/src/main/java/io/openepi/soil/model/SoilPropertyJSON.java deleted file mode 100644 index af0074c..0000000 --- a/src/main/java/io/openepi/soil/model/SoilPropertyJSON.java +++ /dev/null @@ -1,271 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.soil.model.PointGeometry; -import io.openepi.soil.model.SoilLayerList; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * SoilPropertyJSON - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SoilPropertyJSON { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type; - - public static final String SERIALIZED_NAME_GEOMETRY = "geometry"; - @SerializedName(SERIALIZED_NAME_GEOMETRY) - private PointGeometry geometry; - - public static final String SERIALIZED_NAME_PROPERTIES = "properties"; - @SerializedName(SERIALIZED_NAME_PROPERTIES) - private SoilLayerList properties; - - public SoilPropertyJSON() { - } - - public SoilPropertyJSON type(Object type) { - this.type = type; - return this; - } - - /** - * The feature type of the geojson-object - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public SoilPropertyJSON geometry(PointGeometry geometry) { - this.geometry = geometry; - return this; - } - - /** - * The geometry of the queried location - * @return geometry - */ - @javax.annotation.Nonnull - public PointGeometry getGeometry() { - return geometry; - } - - public void setGeometry(PointGeometry geometry) { - this.geometry = geometry; - } - - - public SoilPropertyJSON properties(SoilLayerList properties) { - this.properties = properties; - return this; - } - - /** - * The queried soil property information - * @return properties - */ - @javax.annotation.Nonnull - public SoilLayerList getProperties() { - return properties; - } - - public void setProperties(SoilLayerList properties) { - this.properties = properties; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SoilPropertyJSON soilPropertyJSON = (SoilPropertyJSON) o; - return Objects.equals(this.type, soilPropertyJSON.type) && - Objects.equals(this.geometry, soilPropertyJSON.geometry) && - Objects.equals(this.properties, soilPropertyJSON.properties); - } - - @Override - public int hashCode() { - return Objects.hash(type, geometry, properties); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SoilPropertyJSON {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" geometry: ").append(toIndentedString(geometry)).append("\n"); - sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("geometry"); - openapiFields.add("properties"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("geometry"); - openapiRequiredFields.add("properties"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SoilPropertyJSON - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SoilPropertyJSON.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SoilPropertyJSON is not found in the empty JSON string", SoilPropertyJSON.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SoilPropertyJSON.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SoilPropertyJSON` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SoilPropertyJSON.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `geometry` - PointGeometry.validateJsonElement(jsonObj.get("geometry")); - // validate the required field `properties` - SoilLayerList.validateJsonElement(jsonObj.get("properties")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SoilPropertyJSON.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SoilPropertyJSON' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SoilPropertyJSON.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SoilPropertyJSON value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SoilPropertyJSON read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SoilPropertyJSON given an JSON string - * - * @param jsonString JSON string - * @return An instance of SoilPropertyJSON - * @throws IOException if the JSON string is invalid with respect to SoilPropertyJSON - */ - public static SoilPropertyJSON fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SoilPropertyJSON.class); - } - - /** - * Convert an instance of SoilPropertyJSON to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilPropertyUnit.java b/src/main/java/io/openepi/soil/model/SoilPropertyUnit.java deleted file mode 100644 index f34ab20..0000000 --- a/src/main/java/io/openepi/soil/model/SoilPropertyUnit.java +++ /dev/null @@ -1,304 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.soil.model.SoilConversionFactors; -import io.openepi.soil.model.SoilMappedUnits; -import io.openepi.soil.model.SoilTargetUnits; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * SoilPropertyUnit - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SoilPropertyUnit { - public static final String SERIALIZED_NAME_CONVERSION_FACTOR = "conversion_factor"; - @SerializedName(SERIALIZED_NAME_CONVERSION_FACTOR) - private SoilConversionFactors conversionFactor; - - public static final String SERIALIZED_NAME_MAPPED_UNITS = "mapped_units"; - @SerializedName(SERIALIZED_NAME_MAPPED_UNITS) - private SoilMappedUnits mappedUnits; - - public static final String SERIALIZED_NAME_TARGET_UNITS = "target_units"; - @SerializedName(SERIALIZED_NAME_TARGET_UNITS) - private SoilTargetUnits targetUnits; - - public static final String SERIALIZED_NAME_UNCERTAINTY_UNIT = "uncertainty_unit"; - @SerializedName(SERIALIZED_NAME_UNCERTAINTY_UNIT) - private String uncertaintyUnit; - - public SoilPropertyUnit() { - } - - public SoilPropertyUnit conversionFactor(SoilConversionFactors conversionFactor) { - this.conversionFactor = conversionFactor; - return this; - } - - /** - * The conversion factor - * @return conversionFactor - */ - @javax.annotation.Nonnull - public SoilConversionFactors getConversionFactor() { - return conversionFactor; - } - - public void setConversionFactor(SoilConversionFactors conversionFactor) { - this.conversionFactor = conversionFactor; - } - - - public SoilPropertyUnit mappedUnits(SoilMappedUnits mappedUnits) { - this.mappedUnits = mappedUnits; - return this; - } - - /** - * The mapped unit of the soil property - * @return mappedUnits - */ - @javax.annotation.Nonnull - public SoilMappedUnits getMappedUnits() { - return mappedUnits; - } - - public void setMappedUnits(SoilMappedUnits mappedUnits) { - this.mappedUnits = mappedUnits; - } - - - public SoilPropertyUnit targetUnits(SoilTargetUnits targetUnits) { - this.targetUnits = targetUnits; - return this; - } - - /** - * The target unit of the soil property - * @return targetUnits - */ - @javax.annotation.Nonnull - public SoilTargetUnits getTargetUnits() { - return targetUnits; - } - - public void setTargetUnits(SoilTargetUnits targetUnits) { - this.targetUnits = targetUnits; - } - - - public SoilPropertyUnit uncertaintyUnit(String uncertaintyUnit) { - this.uncertaintyUnit = uncertaintyUnit; - return this; - } - - /** - * The unit of the uncertainty - * @return uncertaintyUnit - */ - @javax.annotation.Nonnull - public String getUncertaintyUnit() { - return uncertaintyUnit; - } - - public void setUncertaintyUnit(String uncertaintyUnit) { - this.uncertaintyUnit = uncertaintyUnit; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SoilPropertyUnit soilPropertyUnit = (SoilPropertyUnit) o; - return Objects.equals(this.conversionFactor, soilPropertyUnit.conversionFactor) && - Objects.equals(this.mappedUnits, soilPropertyUnit.mappedUnits) && - Objects.equals(this.targetUnits, soilPropertyUnit.targetUnits) && - Objects.equals(this.uncertaintyUnit, soilPropertyUnit.uncertaintyUnit); - } - - @Override - public int hashCode() { - return Objects.hash(conversionFactor, mappedUnits, targetUnits, uncertaintyUnit); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SoilPropertyUnit {\n"); - sb.append(" conversionFactor: ").append(toIndentedString(conversionFactor)).append("\n"); - sb.append(" mappedUnits: ").append(toIndentedString(mappedUnits)).append("\n"); - sb.append(" targetUnits: ").append(toIndentedString(targetUnits)).append("\n"); - sb.append(" uncertaintyUnit: ").append(toIndentedString(uncertaintyUnit)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("conversion_factor"); - openapiFields.add("mapped_units"); - openapiFields.add("target_units"); - openapiFields.add("uncertainty_unit"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("conversion_factor"); - openapiRequiredFields.add("mapped_units"); - openapiRequiredFields.add("target_units"); - openapiRequiredFields.add("uncertainty_unit"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SoilPropertyUnit - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SoilPropertyUnit.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SoilPropertyUnit is not found in the empty JSON string", SoilPropertyUnit.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SoilPropertyUnit.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SoilPropertyUnit` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SoilPropertyUnit.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `conversion_factor` - SoilConversionFactors.validateJsonElement(jsonObj.get("conversion_factor")); - // validate the required field `mapped_units` - SoilMappedUnits.validateJsonElement(jsonObj.get("mapped_units")); - // validate the required field `target_units` - SoilTargetUnits.validateJsonElement(jsonObj.get("target_units")); - if (!jsonObj.get("uncertainty_unit").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `uncertainty_unit` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uncertainty_unit").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SoilPropertyUnit.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SoilPropertyUnit' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SoilPropertyUnit.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SoilPropertyUnit value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SoilPropertyUnit read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SoilPropertyUnit given an JSON string - * - * @param jsonString JSON string - * @return An instance of SoilPropertyUnit - * @throws IOException if the JSON string is invalid with respect to SoilPropertyUnit - */ - public static SoilPropertyUnit fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SoilPropertyUnit.class); - } - - /** - * Convert an instance of SoilPropertyUnit to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilPropertyValueTypes.java b/src/main/java/io/openepi/soil/model/SoilPropertyValueTypes.java deleted file mode 100644 index 6cd3e6e..0000000 --- a/src/main/java/io/openepi/soil/model/SoilPropertyValueTypes.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets SoilPropertyValueTypes - */ -@JsonAdapter(SoilPropertyValueTypes.Adapter.class) -public enum SoilPropertyValueTypes { - - MEAN("mean"), - - Q0_05("Q0.05"), - - Q0_5("Q0.5"), - - Q0_95("Q0.95"), - - UNCERTAINTY("uncertainty"); - - private String value; - - SoilPropertyValueTypes(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static SoilPropertyValueTypes fromValue(String value) { - for (SoilPropertyValueTypes b : SoilPropertyValueTypes.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final SoilPropertyValueTypes enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public SoilPropertyValueTypes read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return SoilPropertyValueTypes.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - SoilPropertyValueTypes.fromValue(value); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilPropertyValues.java b/src/main/java/io/openepi/soil/model/SoilPropertyValues.java deleted file mode 100644 index d3fac7a..0000000 --- a/src/main/java/io/openepi/soil/model/SoilPropertyValues.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.Arrays; -import org.openapitools.jackson.nullable.JsonNullable; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * SoilPropertyValues - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SoilPropertyValues { - public static final String SERIALIZED_NAME_MEAN = "mean"; - @SerializedName(SERIALIZED_NAME_MEAN) - private BigDecimal mean; - - public static final String SERIALIZED_NAME_Q005 = "Q0.05"; - @SerializedName(SERIALIZED_NAME_Q005) - private BigDecimal Q0_05; - - public static final String SERIALIZED_NAME_Q05 = "Q0.5"; - @SerializedName(SERIALIZED_NAME_Q05) - private BigDecimal Q0_5; - - public static final String SERIALIZED_NAME_Q095 = "Q0.95"; - @SerializedName(SERIALIZED_NAME_Q095) - private BigDecimal Q0_95; - - public static final String SERIALIZED_NAME_UNCERTAINTY = "uncertainty"; - @SerializedName(SERIALIZED_NAME_UNCERTAINTY) - private BigDecimal uncertainty; - - public SoilPropertyValues() { - } - - public SoilPropertyValues mean(BigDecimal mean) { - this.mean = mean; - return this; - } - - /** - * Get mean - * @return mean - */ - @javax.annotation.Nullable - public BigDecimal getMean() { - return mean; - } - - public void setMean(BigDecimal mean) { - this.mean = mean; - } - - - public SoilPropertyValues Q0_05(BigDecimal Q0_05) { - this.Q0_05 = Q0_05; - return this; - } - - /** - * Get Q0_05 - * @return Q0_05 - */ - @javax.annotation.Nullable - public BigDecimal getQ005() { - return Q0_05; - } - - public void setQ005(BigDecimal Q0_05) { - this.Q0_05 = Q0_05; - } - - - public SoilPropertyValues Q0_5(BigDecimal Q0_5) { - this.Q0_5 = Q0_5; - return this; - } - - /** - * Get Q0_5 - * @return Q0_5 - */ - @javax.annotation.Nullable - public BigDecimal getQ05() { - return Q0_5; - } - - public void setQ05(BigDecimal Q0_5) { - this.Q0_5 = Q0_5; - } - - - public SoilPropertyValues Q0_95(BigDecimal Q0_95) { - this.Q0_95 = Q0_95; - return this; - } - - /** - * Get Q0_95 - * @return Q0_95 - */ - @javax.annotation.Nullable - public BigDecimal getQ095() { - return Q0_95; - } - - public void setQ095(BigDecimal Q0_95) { - this.Q0_95 = Q0_95; - } - - - public SoilPropertyValues uncertainty(BigDecimal uncertainty) { - this.uncertainty = uncertainty; - return this; - } - - /** - * Get uncertainty - * @return uncertainty - */ - @javax.annotation.Nullable - public BigDecimal getUncertainty() { - return uncertainty; - } - - public void setUncertainty(BigDecimal uncertainty) { - this.uncertainty = uncertainty; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SoilPropertyValues soilPropertyValues = (SoilPropertyValues) o; - return Objects.equals(this.mean, soilPropertyValues.mean) && - Objects.equals(this.Q0_05, soilPropertyValues.Q0_05) && - Objects.equals(this.Q0_5, soilPropertyValues.Q0_5) && - Objects.equals(this.Q0_95, soilPropertyValues.Q0_95) && - Objects.equals(this.uncertainty, soilPropertyValues.uncertainty); - } - - private static boolean equalsNullable(JsonNullable a, JsonNullable b) { - return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); - } - - @Override - public int hashCode() { - return Objects.hash(mean, Q0_05, Q0_5, Q0_95, uncertainty); - } - - private static int hashCodeNullable(JsonNullable a) { - if (a == null) { - return 1; - } - return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SoilPropertyValues {\n"); - sb.append(" mean: ").append(toIndentedString(mean)).append("\n"); - sb.append(" Q0_05: ").append(toIndentedString(Q0_05)).append("\n"); - sb.append(" Q0_5: ").append(toIndentedString(Q0_5)).append("\n"); - sb.append(" Q0_95: ").append(toIndentedString(Q0_95)).append("\n"); - sb.append(" uncertainty: ").append(toIndentedString(uncertainty)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("mean"); - openapiFields.add("Q0.05"); - openapiFields.add("Q0.5"); - openapiFields.add("Q0.95"); - openapiFields.add("uncertainty"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SoilPropertyValues - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SoilPropertyValues.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SoilPropertyValues is not found in the empty JSON string", SoilPropertyValues.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SoilPropertyValues.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SoilPropertyValues` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SoilPropertyValues.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SoilPropertyValues' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SoilPropertyValues.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SoilPropertyValues value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SoilPropertyValues read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SoilPropertyValues given an JSON string - * - * @param jsonString JSON string - * @return An instance of SoilPropertyValues - * @throws IOException if the JSON string is invalid with respect to SoilPropertyValues - */ - public static SoilPropertyValues fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SoilPropertyValues.class); - } - - /** - * Convert an instance of SoilPropertyValues to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilTargetUnits.java b/src/main/java/io/openepi/soil/model/SoilTargetUnits.java deleted file mode 100644 index 4f95424..0000000 --- a/src/main/java/io/openepi/soil/model/SoilTargetUnits.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets SoilTargetUnits - */ -@JsonAdapter(SoilTargetUnits.Adapter.class) -public enum SoilTargetUnits { - - KG_DM_("kg/dm³"), - - CMOL_C_KG("cmol(c)/kg"), - - CM_100CM_("cm³/100cm³"), - - PERCENT("%"), - - G_KG("g/kg"), - - HG_M_("hg/m³"), - - KG_M_("kg/m²"), - - P_H("pH"); - - private String value; - - SoilTargetUnits(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static SoilTargetUnits fromValue(String value) { - for (SoilTargetUnits b : SoilTargetUnits.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final SoilTargetUnits enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public SoilTargetUnits read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return SoilTargetUnits.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - SoilTargetUnits.fromValue(value); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilTypeInfo.java b/src/main/java/io/openepi/soil/model/SoilTypeInfo.java deleted file mode 100644 index 7fb5724..0000000 --- a/src/main/java/io/openepi/soil/model/SoilTypeInfo.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.soil.model.SoilTypeProbability; -import io.openepi.soil.model.SoilTypes; -import org.openapitools.jackson.nullable.JsonNullable; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * SoilTypeInfo - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SoilTypeInfo { - public static final String SERIALIZED_NAME_MOST_PROBABLE_SOIL_TYPE = "most_probable_soil_type"; - @SerializedName(SERIALIZED_NAME_MOST_PROBABLE_SOIL_TYPE) - private SoilTypes mostProbableSoilType; - - public static final String SERIALIZED_NAME_PROBABILITIES = "probabilities"; - @SerializedName(SERIALIZED_NAME_PROBABILITIES) - private List probabilities; - - public SoilTypeInfo() { - } - - public SoilTypeInfo mostProbableSoilType(SoilTypes mostProbableSoilType) { - this.mostProbableSoilType = mostProbableSoilType; - return this; - } - - /** - * The most probable soil type at the queried location - * @return mostProbableSoilType - */ - @javax.annotation.Nonnull - public SoilTypes getMostProbableSoilType() { - return mostProbableSoilType; - } - - public void setMostProbableSoilType(SoilTypes mostProbableSoilType) { - this.mostProbableSoilType = mostProbableSoilType; - } - - - public SoilTypeInfo probabilities(List probabilities) { - this.probabilities = probabilities; - return this; - } - - public SoilTypeInfo addProbabilitiesItem(SoilTypeProbability probabilitiesItem) { - if (this.probabilities == null) { - this.probabilities = new ArrayList<>(); - } - this.probabilities.add(probabilitiesItem); - return this; - } - - /** - * Get probabilities - * @return probabilities - */ - @javax.annotation.Nullable - public List getProbabilities() { - return probabilities; - } - - public void setProbabilities(List probabilities) { - this.probabilities = probabilities; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SoilTypeInfo soilTypeInfo = (SoilTypeInfo) o; - return Objects.equals(this.mostProbableSoilType, soilTypeInfo.mostProbableSoilType) && - Objects.equals(this.probabilities, soilTypeInfo.probabilities); - } - - private static boolean equalsNullable(JsonNullable a, JsonNullable b) { - return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); - } - - @Override - public int hashCode() { - return Objects.hash(mostProbableSoilType, probabilities); - } - - private static int hashCodeNullable(JsonNullable a) { - if (a == null) { - return 1; - } - return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SoilTypeInfo {\n"); - sb.append(" mostProbableSoilType: ").append(toIndentedString(mostProbableSoilType)).append("\n"); - sb.append(" probabilities: ").append(toIndentedString(probabilities)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("most_probable_soil_type"); - openapiFields.add("probabilities"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("most_probable_soil_type"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SoilTypeInfo - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SoilTypeInfo.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SoilTypeInfo is not found in the empty JSON string", SoilTypeInfo.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SoilTypeInfo.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SoilTypeInfo` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SoilTypeInfo.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `most_probable_soil_type` - SoilTypes.validateJsonElement(jsonObj.get("most_probable_soil_type")); - if (jsonObj.get("probabilities") != null && !jsonObj.get("probabilities").isJsonNull()) { - JsonArray jsonArrayprobabilities = jsonObj.getAsJsonArray("probabilities"); - if (jsonArrayprobabilities != null) { - // ensure the json data is an array - if (!jsonObj.get("probabilities").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `probabilities` to be an array in the JSON string but got `%s`", jsonObj.get("probabilities").toString())); - } - - // validate the optional field `probabilities` (array) - for (int i = 0; i < jsonArrayprobabilities.size(); i++) { - SoilTypeProbability.validateJsonElement(jsonArrayprobabilities.get(i)); - }; - } - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SoilTypeInfo.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SoilTypeInfo' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SoilTypeInfo.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SoilTypeInfo value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SoilTypeInfo read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SoilTypeInfo given an JSON string - * - * @param jsonString JSON string - * @return An instance of SoilTypeInfo - * @throws IOException if the JSON string is invalid with respect to SoilTypeInfo - */ - public static SoilTypeInfo fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SoilTypeInfo.class); - } - - /** - * Convert an instance of SoilTypeInfo to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilTypeJSON.java b/src/main/java/io/openepi/soil/model/SoilTypeJSON.java deleted file mode 100644 index cc3898f..0000000 --- a/src/main/java/io/openepi/soil/model/SoilTypeJSON.java +++ /dev/null @@ -1,271 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.soil.model.PointGeometry; -import io.openepi.soil.model.SoilTypeInfo; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * SoilTypeJSON - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SoilTypeJSON { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type; - - public static final String SERIALIZED_NAME_GEOMETRY = "geometry"; - @SerializedName(SERIALIZED_NAME_GEOMETRY) - private PointGeometry geometry; - - public static final String SERIALIZED_NAME_PROPERTIES = "properties"; - @SerializedName(SERIALIZED_NAME_PROPERTIES) - private SoilTypeInfo properties; - - public SoilTypeJSON() { - } - - public SoilTypeJSON type(Object type) { - this.type = type; - return this; - } - - /** - * The feature type of the geojson-object - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public SoilTypeJSON geometry(PointGeometry geometry) { - this.geometry = geometry; - return this; - } - - /** - * The geometry of the queried location - * @return geometry - */ - @javax.annotation.Nonnull - public PointGeometry getGeometry() { - return geometry; - } - - public void setGeometry(PointGeometry geometry) { - this.geometry = geometry; - } - - - public SoilTypeJSON properties(SoilTypeInfo properties) { - this.properties = properties; - return this; - } - - /** - * The soil type information at the queried location - * @return properties - */ - @javax.annotation.Nonnull - public SoilTypeInfo getProperties() { - return properties; - } - - public void setProperties(SoilTypeInfo properties) { - this.properties = properties; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SoilTypeJSON soilTypeJSON = (SoilTypeJSON) o; - return Objects.equals(this.type, soilTypeJSON.type) && - Objects.equals(this.geometry, soilTypeJSON.geometry) && - Objects.equals(this.properties, soilTypeJSON.properties); - } - - @Override - public int hashCode() { - return Objects.hash(type, geometry, properties); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SoilTypeJSON {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" geometry: ").append(toIndentedString(geometry)).append("\n"); - sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("geometry"); - openapiFields.add("properties"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("geometry"); - openapiRequiredFields.add("properties"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SoilTypeJSON - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SoilTypeJSON.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SoilTypeJSON is not found in the empty JSON string", SoilTypeJSON.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SoilTypeJSON.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SoilTypeJSON` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SoilTypeJSON.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `geometry` - PointGeometry.validateJsonElement(jsonObj.get("geometry")); - // validate the required field `properties` - SoilTypeInfo.validateJsonElement(jsonObj.get("properties")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SoilTypeJSON.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SoilTypeJSON' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SoilTypeJSON.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SoilTypeJSON value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SoilTypeJSON read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SoilTypeJSON given an JSON string - * - * @param jsonString JSON string - * @return An instance of SoilTypeJSON - * @throws IOException if the JSON string is invalid with respect to SoilTypeJSON - */ - public static SoilTypeJSON fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SoilTypeJSON.class); - } - - /** - * Convert an instance of SoilTypeJSON to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilTypeProbability.java b/src/main/java/io/openepi/soil/model/SoilTypeProbability.java deleted file mode 100644 index 80b3ea6..0000000 --- a/src/main/java/io/openepi/soil/model/SoilTypeProbability.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.soil.model.SoilTypes; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * SoilTypeProbability - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SoilTypeProbability { - public static final String SERIALIZED_NAME_SOIL_TYPE = "soil_type"; - @SerializedName(SERIALIZED_NAME_SOIL_TYPE) - private SoilTypes soilType; - - public static final String SERIALIZED_NAME_PROBABILITY = "probability"; - @SerializedName(SERIALIZED_NAME_PROBABILITY) - private Integer probability; - - public SoilTypeProbability() { - } - - public SoilTypeProbability soilType(SoilTypes soilType) { - this.soilType = soilType; - return this; - } - - /** - * The soil type - * @return soilType - */ - @javax.annotation.Nonnull - public SoilTypes getSoilType() { - return soilType; - } - - public void setSoilType(SoilTypes soilType) { - this.soilType = soilType; - } - - - public SoilTypeProbability probability(Integer probability) { - this.probability = probability; - return this; - } - - /** - * The probability of the soil type as an integer between 0 and 100 - * @return probability - */ - @javax.annotation.Nonnull - public Integer getProbability() { - return probability; - } - - public void setProbability(Integer probability) { - this.probability = probability; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SoilTypeProbability soilTypeProbability = (SoilTypeProbability) o; - return Objects.equals(this.soilType, soilTypeProbability.soilType) && - Objects.equals(this.probability, soilTypeProbability.probability); - } - - @Override - public int hashCode() { - return Objects.hash(soilType, probability); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SoilTypeProbability {\n"); - sb.append(" soilType: ").append(toIndentedString(soilType)).append("\n"); - sb.append(" probability: ").append(toIndentedString(probability)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("soil_type"); - openapiFields.add("probability"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("soil_type"); - openapiRequiredFields.add("probability"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SoilTypeProbability - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SoilTypeProbability.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SoilTypeProbability is not found in the empty JSON string", SoilTypeProbability.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SoilTypeProbability.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SoilTypeProbability` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SoilTypeProbability.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `soil_type` - SoilTypes.validateJsonElement(jsonObj.get("soil_type")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SoilTypeProbability.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SoilTypeProbability' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SoilTypeProbability.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SoilTypeProbability value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SoilTypeProbability read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SoilTypeProbability given an JSON string - * - * @param jsonString JSON string - * @return An instance of SoilTypeProbability - * @throws IOException if the JSON string is invalid with respect to SoilTypeProbability - */ - public static SoilTypeProbability fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SoilTypeProbability.class); - } - - /** - * Convert an instance of SoilTypeProbability to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilTypeSummary.java b/src/main/java/io/openepi/soil/model/SoilTypeSummary.java deleted file mode 100644 index ec1c36f..0000000 --- a/src/main/java/io/openepi/soil/model/SoilTypeSummary.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.soil.model.SoilTypes; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * SoilTypeSummary - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SoilTypeSummary { - public static final String SERIALIZED_NAME_SOIL_TYPE = "soil_type"; - @SerializedName(SERIALIZED_NAME_SOIL_TYPE) - private SoilTypes soilType; - - public static final String SERIALIZED_NAME_COUNT = "count"; - @SerializedName(SERIALIZED_NAME_COUNT) - private Integer count; - - public SoilTypeSummary() { - } - - public SoilTypeSummary soilType(SoilTypes soilType) { - this.soilType = soilType; - return this; - } - - /** - * The soil type - * @return soilType - */ - @javax.annotation.Nonnull - public SoilTypes getSoilType() { - return soilType; - } - - public void setSoilType(SoilTypes soilType) { - this.soilType = soilType; - } - - - public SoilTypeSummary count(Integer count) { - this.count = count; - return this; - } - - /** - * The number of occurrences of the soil type within the queried bounding box - * @return count - */ - @javax.annotation.Nonnull - public Integer getCount() { - return count; - } - - public void setCount(Integer count) { - this.count = count; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SoilTypeSummary soilTypeSummary = (SoilTypeSummary) o; - return Objects.equals(this.soilType, soilTypeSummary.soilType) && - Objects.equals(this.count, soilTypeSummary.count); - } - - @Override - public int hashCode() { - return Objects.hash(soilType, count); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SoilTypeSummary {\n"); - sb.append(" soilType: ").append(toIndentedString(soilType)).append("\n"); - sb.append(" count: ").append(toIndentedString(count)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("soil_type"); - openapiFields.add("count"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("soil_type"); - openapiRequiredFields.add("count"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SoilTypeSummary - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SoilTypeSummary.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SoilTypeSummary is not found in the empty JSON string", SoilTypeSummary.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SoilTypeSummary.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SoilTypeSummary` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SoilTypeSummary.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `soil_type` - SoilTypes.validateJsonElement(jsonObj.get("soil_type")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SoilTypeSummary.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SoilTypeSummary' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SoilTypeSummary.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SoilTypeSummary value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SoilTypeSummary read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SoilTypeSummary given an JSON string - * - * @param jsonString JSON string - * @return An instance of SoilTypeSummary - * @throws IOException if the JSON string is invalid with respect to SoilTypeSummary - */ - public static SoilTypeSummary fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SoilTypeSummary.class); - } - - /** - * Convert an instance of SoilTypeSummary to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilTypeSummaryInfo.java b/src/main/java/io/openepi/soil/model/SoilTypeSummaryInfo.java deleted file mode 100644 index 1c3eb2b..0000000 --- a/src/main/java/io/openepi/soil/model/SoilTypeSummaryInfo.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.soil.model.SoilTypeSummary; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * SoilTypeSummaryInfo - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SoilTypeSummaryInfo { - public static final String SERIALIZED_NAME_SUMMARIES = "summaries"; - @SerializedName(SERIALIZED_NAME_SUMMARIES) - private List summaries = new ArrayList<>(); - - public SoilTypeSummaryInfo() { - } - - public SoilTypeSummaryInfo summaries(List summaries) { - this.summaries = summaries; - return this; - } - - public SoilTypeSummaryInfo addSummariesItem(SoilTypeSummary summariesItem) { - if (this.summaries == null) { - this.summaries = new ArrayList<>(); - } - this.summaries.add(summariesItem); - return this; - } - - /** - * The soil type summaries within the queried bounding box - * @return summaries - */ - @javax.annotation.Nonnull - public List getSummaries() { - return summaries; - } - - public void setSummaries(List summaries) { - this.summaries = summaries; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SoilTypeSummaryInfo soilTypeSummaryInfo = (SoilTypeSummaryInfo) o; - return Objects.equals(this.summaries, soilTypeSummaryInfo.summaries); - } - - @Override - public int hashCode() { - return Objects.hash(summaries); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SoilTypeSummaryInfo {\n"); - sb.append(" summaries: ").append(toIndentedString(summaries)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("summaries"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("summaries"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SoilTypeSummaryInfo - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SoilTypeSummaryInfo.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SoilTypeSummaryInfo is not found in the empty JSON string", SoilTypeSummaryInfo.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SoilTypeSummaryInfo.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SoilTypeSummaryInfo` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SoilTypeSummaryInfo.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the json data is an array - if (!jsonObj.get("summaries").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `summaries` to be an array in the JSON string but got `%s`", jsonObj.get("summaries").toString())); - } - - JsonArray jsonArraysummaries = jsonObj.getAsJsonArray("summaries"); - // validate the required field `summaries` (array) - for (int i = 0; i < jsonArraysummaries.size(); i++) { - SoilTypeSummary.validateJsonElement(jsonArraysummaries.get(i)); - }; - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SoilTypeSummaryInfo.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SoilTypeSummaryInfo' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SoilTypeSummaryInfo.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SoilTypeSummaryInfo value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SoilTypeSummaryInfo read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SoilTypeSummaryInfo given an JSON string - * - * @param jsonString JSON string - * @return An instance of SoilTypeSummaryInfo - * @throws IOException if the JSON string is invalid with respect to SoilTypeSummaryInfo - */ - public static SoilTypeSummaryInfo fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SoilTypeSummaryInfo.class); - } - - /** - * Convert an instance of SoilTypeSummaryInfo to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilTypeSummaryJSON.java b/src/main/java/io/openepi/soil/model/SoilTypeSummaryJSON.java deleted file mode 100644 index d94e7e9..0000000 --- a/src/main/java/io/openepi/soil/model/SoilTypeSummaryJSON.java +++ /dev/null @@ -1,271 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; -import io.openepi.soil.model.BoundingBoxGeometry; -import io.openepi.soil.model.SoilTypeSummaryInfo; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * SoilTypeSummaryJSON - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class SoilTypeSummaryJSON { - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private Object type; - - public static final String SERIALIZED_NAME_GEOMETRY = "geometry"; - @SerializedName(SERIALIZED_NAME_GEOMETRY) - private BoundingBoxGeometry geometry; - - public static final String SERIALIZED_NAME_PROPERTIES = "properties"; - @SerializedName(SERIALIZED_NAME_PROPERTIES) - private SoilTypeSummaryInfo properties; - - public SoilTypeSummaryJSON() { - } - - public SoilTypeSummaryJSON type(Object type) { - this.type = type; - return this; - } - - /** - * The feature type of this geojson-object - * @return type - */ - @javax.annotation.Nullable - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } - - - public SoilTypeSummaryJSON geometry(BoundingBoxGeometry geometry) { - this.geometry = geometry; - return this; - } - - /** - * The geometry of the queried location - * @return geometry - */ - @javax.annotation.Nonnull - public BoundingBoxGeometry getGeometry() { - return geometry; - } - - public void setGeometry(BoundingBoxGeometry geometry) { - this.geometry = geometry; - } - - - public SoilTypeSummaryJSON properties(SoilTypeSummaryInfo properties) { - this.properties = properties; - return this; - } - - /** - * The soil type summary information - * @return properties - */ - @javax.annotation.Nonnull - public SoilTypeSummaryInfo getProperties() { - return properties; - } - - public void setProperties(SoilTypeSummaryInfo properties) { - this.properties = properties; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SoilTypeSummaryJSON soilTypeSummaryJSON = (SoilTypeSummaryJSON) o; - return Objects.equals(this.type, soilTypeSummaryJSON.type) && - Objects.equals(this.geometry, soilTypeSummaryJSON.geometry) && - Objects.equals(this.properties, soilTypeSummaryJSON.properties); - } - - @Override - public int hashCode() { - return Objects.hash(type, geometry, properties); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SoilTypeSummaryJSON {\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" geometry: ").append(toIndentedString(geometry)).append("\n"); - sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("type"); - openapiFields.add("geometry"); - openapiFields.add("properties"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("type"); - openapiRequiredFields.add("geometry"); - openapiRequiredFields.add("properties"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to SoilTypeSummaryJSON - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!SoilTypeSummaryJSON.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in SoilTypeSummaryJSON is not found in the empty JSON string", SoilTypeSummaryJSON.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!SoilTypeSummaryJSON.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SoilTypeSummaryJSON` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : SoilTypeSummaryJSON.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the required field `geometry` - BoundingBoxGeometry.validateJsonElement(jsonObj.get("geometry")); - // validate the required field `properties` - SoilTypeSummaryInfo.validateJsonElement(jsonObj.get("properties")); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!SoilTypeSummaryJSON.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'SoilTypeSummaryJSON' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(SoilTypeSummaryJSON.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, SoilTypeSummaryJSON value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public SoilTypeSummaryJSON read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of SoilTypeSummaryJSON given an JSON string - * - * @param jsonString JSON string - * @return An instance of SoilTypeSummaryJSON - * @throws IOException if the JSON string is invalid with respect to SoilTypeSummaryJSON - */ - public static SoilTypeSummaryJSON fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, SoilTypeSummaryJSON.class); - } - - /** - * Convert an instance of SoilTypeSummaryJSON to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/SoilTypes.java b/src/main/java/io/openepi/soil/model/SoilTypes.java deleted file mode 100644 index 0ce720c..0000000 --- a/src/main/java/io/openepi/soil/model/SoilTypes.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets SoilTypes - */ -@JsonAdapter(SoilTypes.Adapter.class) -public enum SoilTypes { - - ACRISOLS("Acrisols"), - - ALBELUVISOLS("Albeluvisols"), - - ALISOLS("Alisols"), - - ANDOSOLS("Andosols"), - - ARENOSOLS("Arenosols"), - - CALCISOLS("Calcisols"), - - CAMBISOLS("Cambisols"), - - CHERNOZEMS("Chernozems"), - - CRYOSOLS("Cryosols"), - - DURISOLS("Durisols"), - - FERRALSOLS("Ferralsols"), - - FLUVISOLS("Fluvisols"), - - GLEYSOLS("Gleysols"), - - GYPSISOLS("Gypsisols"), - - HISTOSOLS("Histosols"), - - KASTANOZEMS("Kastanozems"), - - LEPTOSOLS("Leptosols"), - - LIXISOLS("Lixisols"), - - LUVISOLS("Luvisols"), - - NITISOLS("Nitisols"), - - PHAEOZEMS("Phaeozems"), - - PLANOSOLS("Planosols"), - - PLINTHOSOLS("Plinthosols"), - - PODZOLS("Podzols"), - - REGOSOLS("Regosols"), - - SOLONCHAKS("Solonchaks"), - - SOLONETZ("Solonetz"), - - STAGNOSOLS("Stagnosols"), - - UMBRISOLS("Umbrisols"), - - VERTISOLS("Vertisols"), - - NO_INFORMATION("No information"); - - private String value; - - SoilTypes(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static SoilTypes fromValue(String value) { - for (SoilTypes b : SoilTypes.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final SoilTypes enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public SoilTypes read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return SoilTypes.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - SoilTypes.fromValue(value); - } -} - diff --git a/src/main/java/io/openepi/soil/model/ValidationError.java b/src/main/java/io/openepi/soil/model/ValidationError.java deleted file mode 100644 index 5f756a6..0000000 --- a/src/main/java/io/openepi/soil/model/ValidationError.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import io.openepi.soil.model.ValidationErrorLocInner; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import io.openepi.soil.JSON; - -/** - * ValidationError - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class ValidationError { - public static final String SERIALIZED_NAME_LOC = "loc"; - @SerializedName(SERIALIZED_NAME_LOC) - private List loc = new ArrayList<>(); - - public static final String SERIALIZED_NAME_MSG = "msg"; - @SerializedName(SERIALIZED_NAME_MSG) - private String msg; - - public static final String SERIALIZED_NAME_TYPE = "type"; - @SerializedName(SERIALIZED_NAME_TYPE) - private String type; - - public ValidationError() { - } - - public ValidationError loc(List loc) { - this.loc = loc; - return this; - } - - public ValidationError addLocItem(ValidationErrorLocInner locItem) { - if (this.loc == null) { - this.loc = new ArrayList<>(); - } - this.loc.add(locItem); - return this; - } - - /** - * Get loc - * @return loc - */ - @javax.annotation.Nonnull - public List getLoc() { - return loc; - } - - public void setLoc(List loc) { - this.loc = loc; - } - - - public ValidationError msg(String msg) { - this.msg = msg; - return this; - } - - /** - * Get msg - * @return msg - */ - @javax.annotation.Nonnull - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - - public ValidationError type(String type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - */ - @javax.annotation.Nonnull - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ValidationError validationError = (ValidationError) o; - return Objects.equals(this.loc, validationError.loc) && - Objects.equals(this.msg, validationError.msg) && - Objects.equals(this.type, validationError.type); - } - - @Override - public int hashCode() { - return Objects.hash(loc, msg, type); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ValidationError {\n"); - sb.append(" loc: ").append(toIndentedString(loc)).append("\n"); - sb.append(" msg: ").append(toIndentedString(msg)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("loc"); - openapiFields.add("msg"); - openapiFields.add("type"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("loc"); - openapiRequiredFields.add("msg"); - openapiRequiredFields.add("type"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to ValidationError - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!ValidationError.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in ValidationError is not found in the empty JSON string", ValidationError.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!ValidationError.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ValidationError` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : ValidationError.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the json data is an array - if (!jsonObj.get("loc").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `loc` to be an array in the JSON string but got `%s`", jsonObj.get("loc").toString())); - } - - JsonArray jsonArrayloc = jsonObj.getAsJsonArray("loc"); - // validate the required field `loc` (array) - for (int i = 0; i < jsonArrayloc.size(); i++) { - ValidationErrorLocInner.validateJsonElement(jsonArrayloc.get(i)); - }; - if (!jsonObj.get("msg").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `msg` to be a primitive type in the JSON string but got `%s`", jsonObj.get("msg").toString())); - } - if (!jsonObj.get("type").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!ValidationError.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ValidationError' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(ValidationError.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, ValidationError value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public ValidationError read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of ValidationError given an JSON string - * - * @param jsonString JSON string - * @return An instance of ValidationError - * @throws IOException if the JSON string is invalid with respect to ValidationError - */ - public static ValidationError fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ValidationError.class); - } - - /** - * Convert an instance of ValidationError to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/io/openepi/soil/model/ValidationErrorLocInner.java b/src/main/java/io/openepi/soil/model/ValidationErrorLocInner.java deleted file mode 100644 index 681bdf9..0000000 --- a/src/main/java/io/openepi/soil/model/ValidationErrorLocInner.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Soil API - * This is a RESTful service that provides soil information based on data sourced from SoilGrids.
The data are freely available for use under the CC BY 4.0 license. - * - * The version of the OpenAPI document: 0.2.5 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package io.openepi.soil.model; - -import java.util.Objects; - - - -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.JsonPrimitive; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonParseException; - -import io.openepi.soil.JSON; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-07-22T14:23:35.781423+02:00[Europe/Oslo]", comments = "Generator version: 7.7.0") -public class ValidationErrorLocInner extends AbstractOpenApiSchema { - private static final Logger log = Logger.getLogger(ValidationErrorLocInner.class.getName()); - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!ValidationErrorLocInner.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ValidationErrorLocInner' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); - final TypeAdapter adapterInteger = gson.getDelegateAdapter(this, TypeToken.get(Integer.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, ValidationErrorLocInner value) throws IOException { - if (value == null || value.getActualInstance() == null) { - elementAdapter.write(out, null); - return; - } - - // check if the actual instance is of the type `String` - if (value.getActualInstance() instanceof String) { - JsonPrimitive primitive = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonPrimitive(); - elementAdapter.write(out, primitive); - return; - } - // check if the actual instance is of the type `Integer` - if (value.getActualInstance() instanceof Integer) { - JsonPrimitive primitive = adapterInteger.toJsonTree((Integer)value.getActualInstance()).getAsJsonPrimitive(); - elementAdapter.write(out, primitive); - return; - } - throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: Integer, String"); - } - - @Override - public ValidationErrorLocInner read(JsonReader in) throws IOException { - Object deserialized = null; - JsonElement jsonElement = elementAdapter.read(in); - - ArrayList errorMessages = new ArrayList<>(); - TypeAdapter actualAdapter = elementAdapter; - - // deserialize String - try { - // validate the JSON object to see if any exception is thrown - if (!jsonElement.getAsJsonPrimitive().isString()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); - } - actualAdapter = adapterString; - ValidationErrorLocInner ret = new ValidationErrorLocInner(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'String'", e); - } - // deserialize Integer - try { - // validate the JSON object to see if any exception is thrown - if (!jsonElement.getAsJsonPrimitive().isNumber()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); - } - actualAdapter = adapterInteger; - ValidationErrorLocInner ret = new ValidationErrorLocInner(); - ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); - return ret; - } catch (Exception e) { - // deserialization failed, continue - errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); - log.log(Level.FINER, "Input data does not match schema 'Integer'", e); - } - - throw new IOException(String.format("Failed deserialization for ValidationErrorLocInner: no class matches result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); - } - }.nullSafe(); - } - } - - // store a list of schema names defined in anyOf - public static final Map> schemas = new HashMap>(); - - public ValidationErrorLocInner() { - super("anyOf", Boolean.FALSE); - } - - public ValidationErrorLocInner(Object o) { - super("anyOf", Boolean.FALSE); - setActualInstance(o); - } - - static { - schemas.put("String", String.class); - schemas.put("Integer", Integer.class); - } - - @Override - public Map> getSchemas() { - return ValidationErrorLocInner.schemas; - } - - /** - * Set the instance that matches the anyOf child schema, check - * the instance parameter is valid against the anyOf child schemas: - * Integer, String - * - * It could be an instance of the 'anyOf' schemas. - */ - @Override - public void setActualInstance(Object instance) { - if (instance instanceof String) { - super.setActualInstance(instance); - return; - } - - if (instance instanceof Integer) { - super.setActualInstance(instance); - return; - } - - throw new RuntimeException("Invalid instance type. Must be Integer, String"); - } - - /** - * Get the actual instance, which can be the following: - * Integer, String - * - * @return The actual instance (Integer, String) - */ - @SuppressWarnings("unchecked") - @Override - public Object getActualInstance() { - return super.getActualInstance(); - } - - /** - * Get the actual instance of `String`. If the actual instance is not `String`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `String` - * @throws ClassCastException if the instance is not `String` - */ - public String getString() throws ClassCastException { - return (String)super.getActualInstance(); - } - /** - * Get the actual instance of `Integer`. If the actual instance is not `Integer`, - * the ClassCastException will be thrown. - * - * @return The actual instance of `Integer` - * @throws ClassCastException if the instance is not `Integer` - */ - public Integer getInteger() throws ClassCastException { - return (Integer)super.getActualInstance(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to ValidationErrorLocInner - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - // validate anyOf schemas one by one - ArrayList errorMessages = new ArrayList<>(); - // validate the json string with String - try { - if (!jsonElement.getAsJsonPrimitive().isString()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); - } - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); - // continue to the next one - } - // validate the json string with Integer - try { - if (!jsonElement.getAsJsonPrimitive().isNumber()) { - throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); - } - return; - } catch (Exception e) { - errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); - // continue to the next one - } - throw new IOException(String.format("The JSON string is invalid for ValidationErrorLocInner with anyOf schemas: Integer, String. no class match the result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); - } - - /** - * Create an instance of ValidationErrorLocInner given an JSON string - * - * @param jsonString JSON string - * @return An instance of ValidationErrorLocInner - * @throws IOException if the JSON string is invalid with respect to ValidationErrorLocInner - */ - public static ValidationErrorLocInner fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ValidationErrorLocInner.class); - } - - /** - * Convert an instance of ValidationErrorLocInner to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/test/java/io/openepi/crop_health/api/CropHealthApiTest.java b/src/test/java/io/openepi/crop_health/api/CropHealthApiTest.java deleted file mode 100644 index 54ef56a..0000000 --- a/src/test/java/io/openepi/crop_health/api/CropHealthApiTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package io.openepi.crop_health.api; - -import io.openepi.common.ApiException; -import io.openepi.crop_health.model.BinaryPredictionResponse; -import io.openepi.crop_health.model.MultiHLTPredictionResponse; -import io.openepi.crop_health.model.Ping200Response; -import io.openepi.crop_health.model.SingleHLTPredictionResponse; -import org.junit.jupiter.api.Test; - -import java.io.File; -import java.math.BigDecimal; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.BeforeEach; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * API tests for DefaultApi - */ -public class CropHealthApiTest { - - @Mock - private CropHealthApi api = new CropHealthApi(); - - @BeforeEach - public void setUp() throws Exception { - MockitoAnnotations.openMocks(this); - } - - @Test - public void pingTest() throws ApiException { - Ping200Response mockResponse = new Ping200Response(); - mockResponse.setStatus("Healthy"); - when(api.ping()).thenReturn(mockResponse); - - Ping200Response response = api.ping(); - assertEquals("Healthy", response.getStatus()); - } - - @Test - public void postPredictionBinaryTest() throws ApiException { - BinaryPredictionResponse mockResponse = new BinaryPredictionResponse(); - mockResponse.setHLT(new BigDecimal("0.5")); - File body = mock(File.class); - when(api.postPredictionBinary(body)).thenReturn(mockResponse); - - BinaryPredictionResponse response = api.postPredictionBinary(body); - assertEquals(new BigDecimal("0.5"), response.getHLT()); - } - - @Test - public void postPredictionMultiTest() throws ApiException { - MultiHLTPredictionResponse mockResponse = new MultiHLTPredictionResponse(); - mockResponse.setAlSBeans(new BigDecimal("0.5")); - mockResponse.setAnTCocoa(new BigDecimal("0.5")); - File body = mock(File.class); - when(api.postPredictionMulti(body)).thenReturn(mockResponse); - - MultiHLTPredictionResponse response = api.postPredictionMulti(body); - assertEquals(new BigDecimal("0.5"), response.getAlSBeans()); - assertEquals(new BigDecimal("0.5"), response.getAnTCocoa()); - } - - @Test - public void postPredictionSingleTest() throws ApiException { - SingleHLTPredictionResponse mockResponse = new SingleHLTPredictionResponse(); - mockResponse.setHLT(new BigDecimal("0.5")); - mockResponse.setALS(new BigDecimal("0.5")); - File body = mock(File.class); - when(api.postPredictionSingle(body)).thenReturn(mockResponse); - - SingleHLTPredictionResponse response = api.postPredictionSingle(body); - assertEquals(new BigDecimal("0.5"), response.getHLT()); - assertEquals(new BigDecimal("0.5"), response.getALS()); - } - -} diff --git a/src/test/java/io/openepi/deforestation/api/DeforestationApiTest.java b/src/test/java/io/openepi/deforestation/api/DeforestationApiTest.java deleted file mode 100644 index ff5a11e..0000000 --- a/src/test/java/io/openepi/deforestation/api/DeforestationApiTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package io.openepi.deforestation.api; - -import io.openepi.common.ApiException; -import io.openepi.deforestation.model.BasinProperties; -import io.openepi.deforestation.model.DeforestationBasinFeature; -import io.openepi.deforestation.model.DeforestationBasinGeoJSON; -import java.math.BigDecimal; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.ArrayList; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; - -/** - * API tests for DeforestationApi - */ -public class DeforestationApiTest { - - @Mock - private DeforestationApi api = new DeforestationApi(); - - @BeforeEach - public void setUp() throws Exception { - MockitoAnnotations.openMocks(this); - } - - @Test - public void getLossyearBasinTest() throws ApiException { - BigDecimal lon = new BigDecimal("30.06"); - BigDecimal lat = BigDecimal.valueOf(-1.94); - BigDecimal minLon = new BigDecimal("28.85"); - BigDecimal minLat = BigDecimal.valueOf(-2.84); - BigDecimal maxLon = new BigDecimal("30.90"); - BigDecimal maxLat = BigDecimal.valueOf(-1.04); - - DeforestationBasinGeoJSON mockResponse = new DeforestationBasinGeoJSON(); - - BasinProperties basinProperties = new BasinProperties(); - basinProperties.setStartYear(2001); - - DeforestationBasinFeature mockFeature = new DeforestationBasinFeature(); - mockFeature.setProperties(basinProperties); - ArrayList features = new ArrayList<>(); - features.add(mockFeature); - mockResponse.setFeatures(features); - - when(api.getLossyearBasin(lon, lat, null, null, null, null, null, null)).thenReturn(mockResponse); - when(api.getLossyearBasin(null, null, minLon, minLat, maxLon, maxLat, null, null)).thenReturn(mockResponse); - - DeforestationBasinGeoJSON response = api.getLossyearBasin(lon, lat, null, null, null, null, null, null); - assertEquals(response.getFeatures().get(0).getProperties().getStartYear(), 2001); - - response = api.getLossyearBasin(null, null, minLon, minLat, maxLon, maxLat, null, null); - assertEquals(2001, response.getFeatures().get(0).getProperties().getStartYear()); - } - -} diff --git a/src/test/java/io/openepi/flood/api/FloodApiTest.java b/src/test/java/io/openepi/flood/api/FloodApiTest.java deleted file mode 100644 index c78e503..0000000 --- a/src/test/java/io/openepi/flood/api/FloodApiTest.java +++ /dev/null @@ -1,114 +0,0 @@ -package io.openepi.flood.api; - -import io.openepi.common.ApiException; -import java.math.BigDecimal; - -import io.openepi.flood.model.*; - - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import static org.mockito.Mockito.when; -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * API tests for FloodApi - */ -public class FloodApiTest { - - @Mock - private FloodApi api = new FloodApi(); - - @BeforeEach - public void setUp() throws Exception { - MockitoAnnotations.openMocks(this); - } - - @Test - public void getDetailedForecastTest() throws ApiException { - BigDecimal lon = new BigDecimal("33.57"); - BigDecimal lat = BigDecimal.valueOf(-1.37); - Boolean includeNeighbors = false; - - BigDecimal minLon = new BigDecimal("33.5"); - BigDecimal maxLon = new BigDecimal("34.55"); - BigDecimal minLat = BigDecimal.valueOf(-1.4); - BigDecimal maxLat = BigDecimal.valueOf(-1.3); - - DetailedResponseModel mockResponse = new DetailedResponseModel(); - DetailedFeatureCollection mockFeatureCollection = new DetailedFeatureCollection(); - DetailedFeature mockFeature = new DetailedFeature(); - mockFeature.setId("123"); - mockFeatureCollection.addFeaturesItem(mockFeature); - mockResponse.setQueriedLocation(mockFeatureCollection); - - when(api.getDetailedForecast(lon, lat, null, null, null, null, includeNeighbors, null, null)).thenReturn(mockResponse); - when(api.getDetailedForecast(null, null, minLon, maxLon, minLat, maxLat, includeNeighbors, null, null)).thenReturn(mockResponse); - - DetailedResponseModel response = api.getDetailedForecast(lon, lat, null, null, null, null, includeNeighbors, null, null); - assertEquals("123", response.getQueriedLocation().getFeatures().get(0).getId()); - - response = api.getDetailedForecast(null, null, minLon, maxLon, minLat, maxLat, includeNeighbors, null, null); - assertEquals("123", response.getQueriedLocation().getFeatures().get(0).getId()); - } - - - @Test - public void getForecastSummaryTest() throws ApiException { - BigDecimal lon = new BigDecimal("33.57"); - BigDecimal lat = BigDecimal.valueOf(-1.37); - Boolean includeNeighbors = false; - - BigDecimal minLon = new BigDecimal("33.5"); - BigDecimal maxLon = new BigDecimal("34.55"); - BigDecimal minLat = BigDecimal.valueOf(-1.4); - BigDecimal maxLat = BigDecimal.valueOf(-1.3); - - SummaryResponseModel mockResponse = new SummaryResponseModel(); - SummaryFeatureCollection mockFeatureCollection = new SummaryFeatureCollection(); - SummaryFeature mockFeature = new SummaryFeature(); - mockFeature.setId("123"); - mockFeatureCollection.addFeaturesItem(mockFeature); - mockResponse.setQueriedLocation(mockFeatureCollection); - - when(api.getForecastSummary(lon, lat, null, null, null, null, includeNeighbors)).thenReturn(mockResponse); - when(api.getForecastSummary(null, null, minLon, maxLon, minLat, maxLat, includeNeighbors)).thenReturn(mockResponse); - - SummaryResponseModel response = api.getForecastSummary(lon, lat, null, null, null, null, includeNeighbors); - assertEquals("123", response.getQueriedLocation().getFeatures().get(0).getId()); - - response = api.getForecastSummary(null, null, minLon, maxLon, minLat, maxLat, includeNeighbors); - assertEquals("123", response.getQueriedLocation().getFeatures().get(0).getId()); - } - - @Test - public void getThresholdTest() throws ApiException { - BigDecimal lon = new BigDecimal("33.57"); - BigDecimal lat = BigDecimal.valueOf(-1.37); - - BigDecimal minLon = new BigDecimal("33.5"); - BigDecimal maxLon = new BigDecimal("34.55"); - BigDecimal minLat = BigDecimal.valueOf(-1.4); - BigDecimal maxLat = BigDecimal.valueOf(-1.3); - - ThresholdResponseModel mockResponse = new ThresholdResponseModel(); - ThresholdFeatureCollection mockFeatureCollection = new ThresholdFeatureCollection(); - ThresholdFeature mockFeature = new ThresholdFeature(); - mockFeature.setId("123"); - mockFeatureCollection.addFeaturesItem(mockFeature); - mockResponse.setQueriedLocation(mockFeatureCollection); - - when(api.getThreshold(lon, lat, null, null, null, null)).thenReturn(mockResponse); - when(api.getThreshold(null, null, minLon, maxLon, minLat, maxLat)).thenReturn(mockResponse); - - ThresholdResponseModel response = api.getThreshold(lon, lat, null, null, null, null); - assertEquals("123", response.getQueriedLocation().getFeatures().get(0).getId()); - - response = api.getThreshold(null, null, minLon, maxLon, minLat, maxLat); - assertEquals("123", response.getQueriedLocation().getFeatures().get(0).getId()); - } - -} diff --git a/src/test/java/io/openepi/geocoding/GeocodingClientIT.java b/src/test/java/io/openepi/geocoding/GeocodingClientIT.java new file mode 100644 index 0000000..4ba4134 --- /dev/null +++ b/src/test/java/io/openepi/geocoding/GeocodingClientIT.java @@ -0,0 +1,42 @@ +package io.openepi.geocoding; + +import io.openepi.geocoding.model.FeatureCollection; +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + + +public class GeocodingClientIT { + + private final String query = "Kigali, Rwanda"; + + @Test + public void testGeocode() { + FeatureCollection geocode = new GeocodingClient().geocode(query); + assertTrue(geocode.getFeatures().size() > 1); + } + + @Test + public void testGeocodeAsync() { + new GeocodingClient().geocodeAsync(query).thenAccept(geocode -> { + assertTrue(geocode.getFeatures().size() > 1); + }).join(); + } + + @Test + public void testReverse() { + double lat = -1.97; + double lon = 30.10; + FeatureCollection reverse = new GeocodingClient().reverse(lat, lon, 10); + assertTrue(reverse.getFeatures().size() > 1); + } + + @Test + public void testReverseAsync() { + double lat = -1.97; + double lon = 30.10; + new GeocodingClient().reverseAsync(lat, lon, 10, null).thenAccept(reverse -> { + assertTrue(reverse.getFeatures().size() > 1); + }).join(); + } +} diff --git a/src/test/java/io/openepi/geocoding/api/GeocodingApiTest.java b/src/test/java/io/openepi/geocoding/api/GeocodingApiTest.java deleted file mode 100644 index 8172c54..0000000 --- a/src/test/java/io/openepi/geocoding/api/GeocodingApiTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package io.openepi.geocoding.api; - -import java.math.BigDecimal; -import io.openepi.common.ApiException; -import io.openepi.geocoding.model.*; -import io.openepi.geocoding.model.Properties; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; - -/** - * API tests for GeocodingApi - */ -public class GeocodingApiTest { - - @Mock - private final GeocodingApi api = new GeocodingApi(); - - @BeforeEach - public void setUp() throws Exception { - MockitoAnnotations.openMocks(this); - } - - @Test - public void getGeocodingTest() throws ApiException { - String q = "Kigali, Rwanda"; - - FeatureCollection mockResponse = new FeatureCollection(); - Feature mockFeature = new Feature(); - Point mockPoint = new Point(); - List mockCoordinates = Arrays.asList("-1.97", "30.10"); - mockPoint.setCoordinates(mockCoordinates); - Geometry mockGeometry = new Geometry(mockPoint); - mockFeature.setGeometry(mockGeometry); - List mockFeatures = Arrays.asList(mockFeature); - mockResponse.setFeatures(mockFeatures); - - when(api.getGeocoding(q, null, null, null, null)).thenReturn(mockResponse); - - FeatureCollection response = api.getGeocoding(q, null, null, null, null); - assertEquals(Arrays.asList("-1.97", "30.10"), response.getFeatures().get(0).getGeometry().getPoint().getCoordinates()); - } - - @Test - public void getReverseGeocodingTest() throws ApiException { - BigDecimal lat = new BigDecimal("-1.97"); - BigDecimal lon = new BigDecimal("30.10"); - - FeatureCollection mockResponse = new FeatureCollection(); - Feature mockFeature = new Feature(); - Properties mockProperties = new Properties(); - mockProperties.setCountrycode("RW"); - mockFeature.setProperties(mockProperties); - List mockFeatures = Arrays.asList(mockFeature); - mockResponse.setFeatures(mockFeatures); - - when(api.getReverseGeocoding(lat, lon, null, null)).thenReturn(mockResponse); - - FeatureCollection response = api.getReverseGeocoding(lat, lon, null, null); - assertEquals("RW", response.getFeatures().get(0).getProperties().getCountrycode()); - } - -} diff --git a/src/test/java/io/openepi/soil/api/SoilApiTest.java b/src/test/java/io/openepi/soil/api/SoilApiTest.java deleted file mode 100644 index fc30ec5..0000000 --- a/src/test/java/io/openepi/soil/api/SoilApiTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.openepi.soil.api; - -import java.math.BigDecimal; -import io.openepi.common.ApiException; -import io.openepi.soil.model.*; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -import java.util.*; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; - -/** - * API tests for SoilApi - */ -public class SoilApiTest { - - @Mock - private SoilApi api = new SoilApi(); - - @BeforeEach - public void setUp() throws Exception { - MockitoAnnotations.openMocks(this); - } - - @Test - public void getSoilPropertyTest() throws ApiException { - BigDecimal lon = new BigDecimal(9.58); - BigDecimal lat = new BigDecimal(60.1); - List depths = Arrays.asList(SoilDepthLabels._0_5CM); - List properties = Arrays.asList(SoilPropertiesCodes.BDOD); - List values = Arrays.asList(SoilPropertyValueTypes.Q0_5); - - SoilPropertyJSON mockResponse = new SoilPropertyJSON(); - SoilLayerList layerList = new SoilLayerList(); - SoilLayer layer = new SoilLayer(); - layer.setCode(SoilPropertiesCodes.BDOD); - layerList.addLayersItem(layer); - mockResponse.setProperties(layerList); - - when(api.getSoilProperty(lon, lat, depths, properties, values)).thenReturn(mockResponse); - - SoilPropertyJSON response = api.getSoilProperty(lon, lat, depths, properties, values); - assertEquals(SoilPropertiesCodes.BDOD, response.getProperties().getLayers().get(0).getCode()); - } - - - @Test - public void getSoilTypeSummaryTest() throws ApiException { - BigDecimal minLon = new BigDecimal("9.5"); - BigDecimal maxLon = new BigDecimal("9.6"); - BigDecimal minLat = new BigDecimal("60.1"); - BigDecimal maxLat = new BigDecimal("60.12"); - - SoilTypeSummaryJSON mockResponse = new SoilTypeSummaryJSON(); - SoilTypeSummaryInfo type = new SoilTypeSummaryInfo(); - SoilTypeSummary summary = new SoilTypeSummary(); - summary.setSoilType(SoilTypes.ALBELUVISOLS); - type.addSummariesItem(summary); - mockResponse.setProperties(type); - - when(api.getSoilTypeSummary(minLon, maxLon, minLat, maxLat)).thenReturn(mockResponse); - - SoilTypeSummaryJSON response = api.getSoilTypeSummary(minLon, maxLon, minLat, maxLat); - assertEquals(SoilTypes.ALBELUVISOLS, response.getProperties().getSummaries().get(0).getSoilType()); - } - - - @Test - public void getSoilTypeTest() throws ApiException { - BigDecimal lon = new BigDecimal("9.58"); - BigDecimal lat = new BigDecimal("60.1"); - - SoilTypeJSON mockResponse = new SoilTypeJSON(); - SoilTypeInfo type = new SoilTypeInfo(); - type.setMostProbableSoilType(SoilTypes.ALBELUVISOLS); - mockResponse.setProperties(type); - - when(api.getSoilType(lon, lat, null)).thenReturn(mockResponse); - SoilTypeJSON response = api.getSoilType(lon, lat, null); - - assertEquals(SoilTypes.ALBELUVISOLS, response.getProperties().getMostProbableSoilType()); - } - -}