diff --git a/src/main/java/com/bandwidth/BandwidthClient.java b/src/main/java/com/bandwidth/BandwidthClient.java index e9141b8f..3abdd9e6 100644 --- a/src/main/java/com/bandwidth/BandwidthClient.java +++ b/src/main/java/com/bandwidth/BandwidthClient.java @@ -14,6 +14,7 @@ import java.util.AbstractMap.SimpleEntry; import java.util.HashMap; import java.util.Map; +import java.util.function.Consumer; /** * Gateway class for the library. @@ -27,6 +28,7 @@ public final class BandwidthClient implements Configuration { */ private MessagingClient messagingClient; private TwoFactorAuthClient twoFactorAuthClient; + private PhoneNumberLookupClient phoneNumberLookupClient; private VoiceClient voiceClient; private WebRtcClient webRtcClient; @@ -65,6 +67,11 @@ public final class BandwidthClient implements Configuration { */ private TwoFactorAuthBasicAuthManager twoFactorAuthBasicAuthManager; + /** + * PhoneNumberLookupBasicAuthManager. + */ + private PhoneNumberLookupBasicAuthManager phoneNumberLookupBasicAuthManager; + /** * VoiceBasicAuthManager. */ @@ -85,17 +92,18 @@ public final class BandwidthClient implements Configuration { */ private final HttpCallback httpCallback; - private BandwidthClient(Environment environment, String baseUrl, HttpClient httpClient, - long timeout, ReadonlyHttpClientConfiguration httpClientConfig, - String messagingBasicAuthUserName, String messagingBasicAuthPassword, - String twoFactorAuthBasicAuthUserName, String twoFactorAuthBasicAuthPassword, - String voiceBasicAuthUserName, String voiceBasicAuthPassword, - String webRtcBasicAuthUserName, String webRtcBasicAuthPassword, - Map authManagers, HttpCallback httpCallback) { + private BandwidthClient(Environment environment, String baseUrl, HttpClient httpClient, long timeout, + ReadonlyHttpClientConfiguration httpClientConfig, String messagingBasicAuthUserName, + String messagingBasicAuthPassword, String twoFactorAuthBasicAuthUserName, + String twoFactorAuthBasicAuthPassword, String phoneNumberLookupBasicAuthUserName, + String phoneNumberLookupBasicAuthPassword, String voiceBasicAuthUserName, + String voiceBasicAuthPassword, String webRtcBasicAuthUserName, + String webRtcBasicAuthPassword, Map authManagers, + HttpCallback httpCallback) { this.environment = environment; this.baseUrl = baseUrl; - this.httpClient = httpClient; this.timeout = timeout; + this.httpClient = httpClient; this.httpClientConfig = httpClientConfig; this.httpCallback = httpCallback; @@ -119,13 +127,26 @@ private BandwidthClient(Environment environment, String baseUrl, HttpClient http } if (!this.authManagers.containsKey("twoFactorAuth") - || !getTwoFactorAuthBasicAuthCredentials().equals(twoFactorAuthBasicAuthUserName, - twoFactorAuthBasicAuthPassword)) { + || !getTwoFactorAuthBasicAuthCredentials().equals( + twoFactorAuthBasicAuthUserName, twoFactorAuthBasicAuthPassword)) { this.twoFactorAuthBasicAuthManager = new TwoFactorAuthBasicAuthManager( twoFactorAuthBasicAuthUserName, twoFactorAuthBasicAuthPassword); this.authManagers.put("twoFactorAuth", twoFactorAuthBasicAuthManager); } + if (this.authManagers.containsKey("phoneNumberLookup")) { + this.phoneNumberLookupBasicAuthManager = + (PhoneNumberLookupBasicAuthManager) this.authManagers.get("phoneNumberLookup"); + } + + if (!this.authManagers.containsKey("phoneNumberLookup") + || !getPhoneNumberLookupBasicAuthCredentials().equals( + phoneNumberLookupBasicAuthUserName, phoneNumberLookupBasicAuthPassword)) { + this.phoneNumberLookupBasicAuthManager = new PhoneNumberLookupBasicAuthManager( + phoneNumberLookupBasicAuthUserName, phoneNumberLookupBasicAuthPassword); + this.authManagers.put("phoneNumberLookup", phoneNumberLookupBasicAuthManager); + } + if (this.authManagers.containsKey("voice")) { this.voiceBasicAuthManager = (VoiceBasicAuthManager) this.authManagers.get("voice"); } @@ -151,10 +172,11 @@ private BandwidthClient(Environment environment, String baseUrl, HttpClient http } - messagingClient = new MessagingClient(this); + messagingClient = new MessagingClient(this, httpCallback); twoFactorAuthClient = new TwoFactorAuthClient(this); - voiceClient = new VoiceClient(this); - webRtcClient = new WebRtcClient(this); + phoneNumberLookupClient = new PhoneNumberLookupClient(this, httpCallback); + voiceClient = new VoiceClient(this, httpCallback); + webRtcClient = new WebRtcClient(this, httpCallback); } /** @@ -180,6 +202,14 @@ public TwoFactorAuthClient getTwoFactorAuthClient() { return twoFactorAuthClient; } + /** + * Provides access to phoneNumberLookupClient Client. + * @return Returns the PhoneNumberLookupClient instance + */ + public PhoneNumberLookupClient getPhoneNumberLookupClient() { + return phoneNumberLookupClient; + } + /** * Provides access to voiceClient Client. * @return Returns the VoiceClient instance @@ -220,14 +250,6 @@ public HttpClient getHttpClient() { return httpClient; } - /** - * The timeout to use for making HTTP requests. - * @return timeout - */ - public long getTimeout() { - return timeout; - } - /** * Http Client Configuration instance. * @return httpClientConfig @@ -252,6 +274,14 @@ public TwoFactorAuthBasicAuthCredentials getTwoFactorAuthBasicAuthCredentials() return twoFactorAuthBasicAuthManager; } + /** + * The credentials to use with PhoneNumberLookupBasicAuth. + * @return phoneNumberLookupBasicAuthCredentials + */ + public PhoneNumberLookupBasicAuthCredentials getPhoneNumberLookupBasicAuthCredentials() { + return phoneNumberLookupBasicAuthManager; + } + /** * The credentials to use with VoiceBasicAuth. * @return voiceBasicAuthCredentials @@ -276,6 +306,26 @@ public Map getAuthManagers() { return authManagers; } + /** + * The timeout to use for making HTTP requests. + * @deprecated This method will be removed in a future version. Use + * {@link #getHttpClientConfig()} instead. + * + * @return timeout + */ + @Deprecated + public long timeout() { + return httpClientConfig.getTimeout(); + } + + /** + * The timeout to use for making HTTP requests. + * @return timeout + */ + public long getTimeout() { + return timeout; + } + /** * Get base URI by current environment. * @param server Server for which to get the base URI @@ -315,6 +365,9 @@ private static String environmentMapper(Environment environment, Server server) if (server.equals(Server.TWOFACTORAUTHDEFAULT)) { return "https://mfa.bandwidth.com/api/v1"; } + if (server.equals(Server.PHONENUMBERLOOKUPDEFAULT)) { + return "https://numbers.bandwidth.com/api/v1"; + } if (server.equals(Server.VOICEDEFAULT)) { return "https://voice.bandwidth.com"; } @@ -332,6 +385,9 @@ private static String environmentMapper(Environment environment, Server server) if (server.equals(Server.TWOFACTORAUTHDEFAULT)) { return "{base_url}"; } + if (server.equals(Server.PHONENUMBERLOOKUPDEFAULT)) { + return "{base_url}"; + } if (server.equals(Server.VOICEDEFAULT)) { return "{base_url}"; } @@ -371,13 +427,18 @@ public Builder newBuilder() { getTwoFactorAuthBasicAuthCredentials().getBasicAuthUserName(); builder.twoFactorAuthBasicAuthPassword = getTwoFactorAuthBasicAuthCredentials().getBasicAuthPassword(); + builder.phoneNumberLookupBasicAuthUserName = + getPhoneNumberLookupBasicAuthCredentials().getBasicAuthUserName(); + builder.phoneNumberLookupBasicAuthPassword = + getPhoneNumberLookupBasicAuthCredentials().getBasicAuthPassword(); builder.voiceBasicAuthUserName = getVoiceBasicAuthCredentials().getBasicAuthUserName(); builder.voiceBasicAuthPassword = getVoiceBasicAuthCredentials().getBasicAuthPassword(); builder.webRtcBasicAuthUserName = getWebRtcBasicAuthCredentials().getBasicAuthUserName(); builder.webRtcBasicAuthPassword = getWebRtcBasicAuthCredentials().getBasicAuthPassword(); builder.authManagers = authManagers; builder.httpCallback = httpCallback; - builder.setHttpClientConfig(httpClientConfig); + builder.httpClientConfig(configBldr -> configBldr = + ((HttpClientConfiguration) httpClientConfig).newBuilder()); return builder; } @@ -385,6 +446,7 @@ public Builder newBuilder() { * Class to build instances of {@link BandwidthClient}. */ public static class Builder { + private Environment environment = Environment.PRODUCTION; private String baseUrl = "https://www.example.com"; private HttpClient httpClient; @@ -393,13 +455,17 @@ public static class Builder { private String messagingBasicAuthPassword = "TODO: Replace"; private String twoFactorAuthBasicAuthUserName = "TODO: Replace"; private String twoFactorAuthBasicAuthPassword = "TODO: Replace"; + private String phoneNumberLookupBasicAuthUserName = "TODO: Replace"; + private String phoneNumberLookupBasicAuthPassword = "TODO: Replace"; private String voiceBasicAuthUserName = "TODO: Replace"; private String voiceBasicAuthPassword = "TODO: Replace"; private String webRtcBasicAuthUserName = "TODO: Replace"; private String webRtcBasicAuthPassword = "TODO: Replace"; private Map authManagers = null; private HttpCallback httpCallback = null; - private HttpClientConfiguration httpClientConfig; + private HttpClientConfiguration.Builder httpClientConfigBuilder = + new HttpClientConfiguration.Builder(); + /** * Credentials setter for MessagingBasicAuth. @@ -439,6 +505,25 @@ public Builder twoFactorAuthBasicAuthCredentials(String basicAuthUserName, return this; } + /** + * Credentials setter for PhoneNumberLookupBasicAuth. + * @param basicAuthUserName String value for phoneNumberLookupBasicAuthUserName. + * @param basicAuthPassword String value for phoneNumberLookupBasicAuthPassword. + * @return Builder + */ + public Builder phoneNumberLookupBasicAuthCredentials(String basicAuthUserName, + String basicAuthPassword) { + if (basicAuthUserName == null) { + throw new NullPointerException("BasicAuthUserName cannot be null."); + } + if (basicAuthPassword == null) { + throw new NullPointerException("BasicAuthPassword cannot be null."); + } + this.phoneNumberLookupBasicAuthUserName = basicAuthUserName; + this.phoneNumberLookupBasicAuthPassword = basicAuthPassword; + return this; + } + /** * Credentials setter for VoiceBasicAuth. * @param basicAuthUserName String value for voiceBasicAuthUserName. @@ -499,13 +584,14 @@ public Builder baseUrl(String baseUrl) { /** * The timeout to use for making HTTP requests. + * @deprecated This method will be removed in a future version. Use + * {@link #httpClientConfig(Consumer) httpClientConfig} instead. * @param timeout must be greater then 0. * @return Builder */ + @Deprecated public Builder timeout(long timeout) { - if (timeout > 0) { - this.timeout = timeout; - } + this.httpClientConfigBuilder.timeout(timeout); return this; } @@ -519,9 +605,16 @@ public Builder httpCallback(HttpCallback httpCallback) { return this; } - - private void setHttpClientConfig(ReadonlyHttpClientConfiguration httpClientConfig) { - this.timeout = httpClientConfig.getTimeout(); + /** + * Setter for the Builder of httpClientConfiguration, takes in an operation to be performed + * on the builder instance of HTTP client configuration. + * + * @param action Consumer for the builder of httpClientConfiguration. + * @return Builder + */ + public Builder httpClientConfig(Consumer action) { + action.accept(httpClientConfigBuilder); + return this; } /** @@ -529,15 +622,15 @@ private void setHttpClientConfig(ReadonlyHttpClientConfiguration httpClientConfi * @return BandwidthClient */ public BandwidthClient build() { - httpClientConfig = new HttpClientConfiguration(); - httpClientConfig.setTimeout(timeout); + HttpClientConfiguration httpClientConfig = httpClientConfigBuilder.build(); httpClient = new OkClient(httpClientConfig); return new BandwidthClient(environment, baseUrl, httpClient, timeout, httpClientConfig, messagingBasicAuthUserName, messagingBasicAuthPassword, twoFactorAuthBasicAuthUserName, twoFactorAuthBasicAuthPassword, + phoneNumberLookupBasicAuthUserName, phoneNumberLookupBasicAuthPassword, voiceBasicAuthUserName, voiceBasicAuthPassword, webRtcBasicAuthUserName, webRtcBasicAuthPassword, authManagers, httpCallback); } } -} \ No newline at end of file +} diff --git a/src/main/java/com/bandwidth/Configuration.java b/src/main/java/com/bandwidth/Configuration.java index b0c0329c..95dcbf97 100644 --- a/src/main/java/com/bandwidth/Configuration.java +++ b/src/main/java/com/bandwidth/Configuration.java @@ -26,16 +26,17 @@ public interface Configuration { String getBaseUrl(); /** - * The timeout to use for making HTTP requests. - * @return a copy of timeout + * Http Client Configuration instance. + * See available [builder methods here](#httpclientconfiguration.builder-class). + * @return a copy of httpClientConfig */ - long getTimeout(); + ReadonlyHttpClientConfiguration getHttpClientConfig(); /** - * Http Client Configuration instance. - * @return a copy of httpClientConfig + * The timeout to use for making HTTP requests. The timeout to use for making HTTP requests. + * @return a copy of timeout */ - ReadonlyHttpClientConfiguration getHttpClientConfig(); + long timeout(); /** * The credentials to use with MessagingBasicAuth. @@ -49,6 +50,12 @@ public interface Configuration { */ TwoFactorAuthBasicAuthCredentials getTwoFactorAuthBasicAuthCredentials(); + /** + * The credentials to use with PhoneNumberLookupBasicAuth. + * @return phoneNumberLookupBasicAuthCredentials + */ + PhoneNumberLookupBasicAuthCredentials getPhoneNumberLookupBasicAuthCredentials(); + /** * The credentials to use with VoiceBasicAuth. * @return voiceBasicAuthCredentials diff --git a/src/main/java/com/bandwidth/DateTimeHelper.java b/src/main/java/com/bandwidth/DateTimeHelper.java index 972b9ffd..c1de0bb1 100644 --- a/src/main/java/com/bandwidth/DateTimeHelper.java +++ b/src/main/java/com/bandwidth/DateTimeHelper.java @@ -6,7 +6,6 @@ package com.bandwidth; - import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; @@ -23,7 +22,9 @@ import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -62,7 +63,7 @@ public static LocalDateTime fromUnixTimestamp(String date) { * @return The converted String */ public static String toUnixTimestamp(LocalDateTime value) { - return Long.toString(value.toEpochSecond(java.time.ZoneOffset.UTC)); + return value == null ? null : Long.toString(value.toEpochSecond(java.time.ZoneOffset.UTC)); } /** @@ -81,6 +82,63 @@ public static List toUnixTimestamp(List values) { return valuesAsString; } + /** + * Convert a Map of DateTime objects to Unix Timestamp strings. + * @param values The Map of DateTime objects to convert + * @return The Map of converted Strings + */ + public static Map toUnixTimestamp(Map values) { + if (values == null) { + return null; + } + Map valuesAsString = new HashMap<>(); + for (Map.Entry value: values.entrySet()) { + valuesAsString.put(value.getKey(), toUnixTimestamp(value.getValue())); + } + return valuesAsString; + } + + /** + * Convert a DateTime object to a Unix Timestamp Long. + * @param value The DateTime object to convert + * @return The converted Long + */ + public static Long toUnixTimestampLong(LocalDateTime value) { + return value == null ? null : value.toEpochSecond(java.time.ZoneOffset.UTC); + } + + /** + * Convert a List of DateTime objects to Unix Timestamp Longs. + * @param values The List of DateTime objects to convert + * @return The list of converted Longs. + */ + public static List toUnixTimestampLong(List values) { + if (values == null) { + return null; + } + List valuesAsLong = new ArrayList<>(); + for (LocalDateTime value : values) { + valuesAsLong.add(toUnixTimestampLong(value)); + } + return valuesAsLong; + } + + /** + * Convert a Map of DateTime objects to Unix Timestamp Longs. + * @param values The Map of DateTime objects to convert + * @return The Map of converted Longs. + */ + public static Map toUnixTimestampLong(Map values) { + if (values == null) { + return null; + } + Map valuesAsLong = new HashMap<>(); + for (Map.Entry value: values.entrySet()) { + valuesAsLong.put(value.getKey(), toUnixTimestampLong(value.getValue())); + } + return valuesAsLong; + } + /** * Parse a datetime string in Rfc1123 format to a DateTime object. * @param date The datetime string in Rfc1123 format @@ -96,7 +154,8 @@ public static LocalDateTime fromRfc1123DateTime(String date) { * @return The converted String */ public static String toRfc1123DateTime(LocalDateTime value) { - return RFC1123_DATE_TIME_FORMATTER.format(value.atZone(ZoneId.of("GMT"))); + return value == null ? null + : RFC1123_DATE_TIME_FORMATTER.format(value.atZone(ZoneId.of("GMT"))); } /** @@ -115,6 +174,22 @@ public static List toRfc1123DateTime(List values) { return valuesAsString; } + /** + * Convert a Map of DateTime objects to Rfc1123 formatted strings. + * @param values The Map of DateTime objects to convert + * @return The Map of converted Strings + */ + public static Map toRfc1123DateTime(Map values) { + if (values == null) { + return null; + } + Map valuesAsString = new HashMap<>(); + for (Map.Entry value: values.entrySet()) { + valuesAsString.put(value.getKey(), toRfc1123DateTime(value.getValue())); + } + return valuesAsString; + } + /** * Parse a datetime string in Rfc8601(Rfc3339) format to a DateTime object. * @param date The datetime string in Rfc8601(Rfc3339) format @@ -136,7 +211,7 @@ public static LocalDateTime fromRfc8601DateTime(String date) { * @return The converted String */ public static String toRfc8601DateTime(LocalDateTime value) { - return value.toString() + "Z"; + return value == null ? null : value.toString() + "Z"; } /** @@ -155,6 +230,22 @@ public static List toRfc8601DateTime(List values) { return valuesAsString; } + /** + * Convert a Map of DateTime objects to Rfc8601(Rfc3339) formatted strings. + * @param values The Map of DateTime objects to convert + * @return The Map of converted Strings + */ + public static Map toRfc8601DateTime(Map values) { + if (values == null) { + return null; + } + Map valuesAsString = new HashMap<>(); + for (Map.Entry value: values.entrySet()) { + valuesAsString.put(value.getKey(), toRfc8601DateTime(value.getValue())); + } + return valuesAsString; + } + /** * Parse a simple date string to a LocalDate object. * @param date The date string @@ -170,7 +261,7 @@ public static LocalDate fromSimpleDate(String date) { * @return The converted Strings */ public static String toSimpleDate(LocalDate value) { - return value.toString(); + return value == null ? null : value.toString(); } /** @@ -189,10 +280,27 @@ public static List toSimpleDate(List values) { return valuesAsString; } + /** + * Convert a Map of LocalDate objects to strings. + * @param values The Map of LocalDate objects to convert + * @return The Map of converted Strings + */ + public static Map toSimpleDate(Map values) { + if (values == null) { + return null; + } + Map valuesAsString = new HashMap<>(); + for (Map.Entry value: values.entrySet()) { + valuesAsString.put(value.getKey(), toSimpleDate(value.getValue())); + } + return valuesAsString; + } + /** * A class to handle deserialization of DateTime objects to Unix Timestamps. */ public static class UnixTimestampDeserializer extends JsonDeserializer { + @SuppressWarnings("unused") @Override public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { @@ -204,10 +312,11 @@ public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) * A class to handle serialization of Unix Timestamps to DateTime objects. */ public static class UnixTimestampSerializer extends JsonSerializer { + @SuppressWarnings("unused") @Override public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeNumber(toUnixTimestamp(value)); + jgen.writeObject(toUnixTimestampLong(value)); } } @@ -215,6 +324,7 @@ public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvide * A class to handle deserialization of DateTime objects to Rfc1123 format strings. */ public static class Rfc1123DateTimeDeserializer extends JsonDeserializer { + @SuppressWarnings("unused") @Override public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { @@ -226,6 +336,7 @@ public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) * A class to handle serialization of Rfc1123 format strings to DateTime objects. */ public static class Rfc1123DateTimeSerializer extends JsonSerializer { + @SuppressWarnings("unused") @Override public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { @@ -237,6 +348,7 @@ public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvide * A class to handle deserialization of DateTime objects to Rfc8601(Rfc3339) format strings. */ public static class Rfc8601DateTimeDeserializer extends JsonDeserializer { + @SuppressWarnings("unused") @Override public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { @@ -248,6 +360,7 @@ public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) * A class to handle serialization of Rfc8601(Rfc3339) format strings to DateTime objects. */ public static class Rfc8601DateTimeSerializer extends JsonSerializer { + @SuppressWarnings("unused") @Override public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { @@ -259,6 +372,7 @@ public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvide * A class to handle deserialization of date strings to LocalDate objects. */ public static class SimpleDateDeserializer extends JsonDeserializer { + @SuppressWarnings("unused") @Override public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { @@ -270,6 +384,7 @@ public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) * A class to handle serialization of LocalDate objects to date strings. */ public static class SimpleDateSerializer extends JsonSerializer { + @SuppressWarnings("unused") @Override public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { diff --git a/src/main/java/com/bandwidth/MessagingClient.java b/src/main/java/com/bandwidth/MessagingClient.java index 60f282c6..91cefb06 100644 --- a/src/main/java/com/bandwidth/MessagingClient.java +++ b/src/main/java/com/bandwidth/MessagingClient.java @@ -6,8 +6,9 @@ package com.bandwidth; -import com.bandwidth.messaging.controllers.*; +import com.bandwidth.http.client.HttpCallback; import com.bandwidth.http.client.OkClient; +import com.bandwidth.messaging.controllers.*; public final class MessagingClient { private final BandwidthClient config; @@ -20,9 +21,10 @@ public final class MessagingClient { /** * Default constructor. */ - public MessagingClient(BandwidthClient config) { + public MessagingClient(BandwidthClient config, HttpCallback httpCallback) { this.config = config; - client = new APIController(config, config.getHttpClient(), config.getAuthManagers()); + client = new APIController(config, config.getHttpClient(), config.getAuthManagers(), + httpCallback); } public static void shutdown() { diff --git a/src/main/java/com/bandwidth/PhoneNumberLookupBasicAuthCredentials.java b/src/main/java/com/bandwidth/PhoneNumberLookupBasicAuthCredentials.java new file mode 100644 index 00000000..8a4c2a20 --- /dev/null +++ b/src/main/java/com/bandwidth/PhoneNumberLookupBasicAuthCredentials.java @@ -0,0 +1,33 @@ +/* + * BandwidthLib + * + * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). + */ + +package com.bandwidth; + +/** + * Interface for defining the behavior of Basic Authentication. + */ +public interface PhoneNumberLookupBasicAuthCredentials { + + /** + * String value for basicAuthUserName. + * @return basicAuthUserName + */ + String getBasicAuthUserName(); + + /** + * String value for basicAuthPassword. + * @return basicAuthPassword + */ + String getBasicAuthPassword(); + + /** + * Checks if provided credentials matched with existing ones. + * @param basicAuthUserName String value for credentials. + * @param basicAuthPassword String value for credentials. + * @return true if credentials matched. + */ + boolean equals(String basicAuthUserName, String basicAuthPassword); +} \ No newline at end of file diff --git a/src/main/java/com/bandwidth/PhoneNumberLookupBasicAuthManager.java b/src/main/java/com/bandwidth/PhoneNumberLookupBasicAuthManager.java new file mode 100644 index 00000000..05832cfb --- /dev/null +++ b/src/main/java/com/bandwidth/PhoneNumberLookupBasicAuthManager.java @@ -0,0 +1,86 @@ +/* + * BandwidthLib + * + * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). + */ + +package com.bandwidth; + +import com.bandwidth.http.request.HttpRequest; +import java.util.Base64; +import java.util.concurrent.CompletableFuture; + +/** + * Utility class for authorization and token management. + */ +public class PhoneNumberLookupBasicAuthManager implements AuthManager, PhoneNumberLookupBasicAuthCredentials { + + private String basicAuthUserName; + + private String basicAuthPassword; + + /** + * Constructor. + * @param username String value for username. + * @param password String value for password. + */ + public PhoneNumberLookupBasicAuthManager(String username, String password) { + this.basicAuthUserName = username; + this.basicAuthPassword = password; + } + + /** + * String value for basicAuthUserName. + * @return basicAuthUserName + */ + public String getBasicAuthUserName() { + return basicAuthUserName; + } + + /** + * String value for basicAuthPassword. + * @return basicAuthPassword + */ + public String getBasicAuthPassword() { + return basicAuthPassword; + } + + /** + * Checks if provided credentials matched with existing ones. + * @param basicAuthUserName String value for credentials. + * @param basicAuthPassword String value for credentials. + * @return true if credentials matched. + */ + public boolean equals(String basicAuthUserName, String basicAuthPassword) { + return basicAuthUserName.equals(getBasicAuthUserName()) + && basicAuthPassword.equals(getBasicAuthPassword()); + } + + /** + * Converts this PhoneNumberLookupBasicAuthManager into string format. + * @return String representation of this class + */ + @Override + public String toString() { + return "PhoneNumberLookupBasicAuthManager [" + "basicAuthUserName=" + basicAuthUserName + + ", basicAuthPassword=" + basicAuthPassword + "]"; + } + + /** + * Adds authentication to the given HttpRequest. + */ + public HttpRequest apply(HttpRequest httpRequest) { + String authCredentials = basicAuthUserName + ":" + basicAuthPassword; + httpRequest.getHeaders().add("Authorization", "Basic " + Base64.getEncoder().encodeToString(authCredentials.getBytes())); + return httpRequest; + } + + /** + * Asynchronously adds authentication to the given HttpRequest. + */ + public CompletableFuture applyAsync(HttpRequest httpRequest) { + String authCredentials = basicAuthUserName + ":" + basicAuthPassword; + httpRequest.getHeaders().add("Authorization", "Basic " + Base64.getEncoder().encodeToString(authCredentials.getBytes())); + return CompletableFuture.completedFuture(httpRequest); + } +} diff --git a/src/main/java/com/bandwidth/PhoneNumberLookupClient.java b/src/main/java/com/bandwidth/PhoneNumberLookupClient.java new file mode 100644 index 00000000..c60c796c --- /dev/null +++ b/src/main/java/com/bandwidth/PhoneNumberLookupClient.java @@ -0,0 +1,41 @@ +/* + * BandwidthLib + * + * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). + */ + +package com.bandwidth; + +import com.bandwidth.http.client.HttpCallback; +import com.bandwidth.http.client.OkClient; +import com.bandwidth.phonenumberlookup.controllers.*; + +public final class PhoneNumberLookupClient { + private final BandwidthClient config; + + /** + * Private store for controllers. + */ + private APIController client; + + /** + * Default constructor. + */ + public PhoneNumberLookupClient(BandwidthClient config, HttpCallback httpCallback) { + this.config = config; + client = new APIController(config, config.getHttpClient(), config.getAuthManagers(), + httpCallback); + } + + public static void shutdown() { + OkClient.shutdown(); + } + + public APIController getAPIController() { + return client; + } + + public Configuration getConfiguration() { + return config; + } +} \ No newline at end of file diff --git a/src/main/java/com/bandwidth/Server.java b/src/main/java/com/bandwidth/Server.java index 499db38f..b3418d56 100644 --- a/src/main/java/com/bandwidth/Server.java +++ b/src/main/java/com/bandwidth/Server.java @@ -20,6 +20,8 @@ public enum Server { TWOFACTORAUTHDEFAULT, + PHONENUMBERLOOKUPDEFAULT, + VOICEDEFAULT, WEBRTCDEFAULT; @@ -32,12 +34,14 @@ public enum Server { ENUM_DEFAULT.value = "default"; MESSAGINGDEFAULT.value = "MessagingDefault"; TWOFACTORAUTHDEFAULT.value = "TwoFactorAuthDefault"; + PHONENUMBERLOOKUPDEFAULT.value = "PhoneNumberLookupDefault"; VOICEDEFAULT.value = "VoiceDefault"; WEBRTCDEFAULT.value = "WebRtcDefault"; valueMap.put("default", ENUM_DEFAULT); valueMap.put("MessagingDefault", MESSAGINGDEFAULT); valueMap.put("TwoFactorAuthDefault", TWOFACTORAUTHDEFAULT); + valueMap.put("PhoneNumberLookupDefault", PHONENUMBERLOOKUPDEFAULT); valueMap.put("VoiceDefault", VOICEDEFAULT); valueMap.put("WebRtcDefault", WEBRTCDEFAULT); } diff --git a/src/main/java/com/bandwidth/VoiceClient.java b/src/main/java/com/bandwidth/VoiceClient.java index 755eb8b4..8a0fa019 100644 --- a/src/main/java/com/bandwidth/VoiceClient.java +++ b/src/main/java/com/bandwidth/VoiceClient.java @@ -6,8 +6,9 @@ package com.bandwidth; -import com.bandwidth.voice.controllers.*; +import com.bandwidth.http.client.HttpCallback; import com.bandwidth.http.client.OkClient; +import com.bandwidth.voice.controllers.*; public final class VoiceClient { private final BandwidthClient config; @@ -20,9 +21,10 @@ public final class VoiceClient { /** * Default constructor. */ - public VoiceClient(BandwidthClient config) { + public VoiceClient(BandwidthClient config, HttpCallback httpCallback) { this.config = config; - client = new APIController(config, config.getHttpClient(), config.getAuthManagers()); + client = new APIController(config, config.getHttpClient(), config.getAuthManagers(), + httpCallback); } public static void shutdown() { diff --git a/src/main/java/com/bandwidth/WebRtcClient.java b/src/main/java/com/bandwidth/WebRtcClient.java index 583c297c..3955202e 100644 --- a/src/main/java/com/bandwidth/WebRtcClient.java +++ b/src/main/java/com/bandwidth/WebRtcClient.java @@ -6,8 +6,9 @@ package com.bandwidth; -import com.bandwidth.webrtc.controllers.*; +import com.bandwidth.http.client.HttpCallback; import com.bandwidth.http.client.OkClient; +import com.bandwidth.webrtc.controllers.*; public final class WebRtcClient { private final BandwidthClient config; @@ -20,9 +21,10 @@ public final class WebRtcClient { /** * Default constructor. */ - public WebRtcClient(BandwidthClient config) { + public WebRtcClient(BandwidthClient config, HttpCallback httpCallback) { this.config = config; - client = new APIController(config, config.getHttpClient(), config.getAuthManagers()); + client = new APIController(config, config.getHttpClient(), config.getAuthManagers(), + httpCallback); } public static void shutdown() { diff --git a/src/main/java/com/bandwidth/http/Headers.java b/src/main/java/com/bandwidth/http/Headers.java index bca143df..4d1f870a 100644 --- a/src/main/java/com/bandwidth/http/Headers.java +++ b/src/main/java/com/bandwidth/http/Headers.java @@ -115,7 +115,7 @@ public Map> asMultimap() { * @param headerMap A Map containing header names and values as Entry pairs. * @return A Map of header names and values. */ - private static Map> cloneHeaderMap(Map> headerMap) { + private Map> cloneHeaderMap(Map> headerMap) { Map> copy = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (Map.Entry> kv : headerMap.entrySet()) { if (kv.getValue() != null) { diff --git a/src/main/java/com/bandwidth/http/client/HttpClient.java b/src/main/java/com/bandwidth/http/client/HttpClient.java index 868a12c9..b503f065 100644 --- a/src/main/java/com/bandwidth/http/client/HttpClient.java +++ b/src/main/java/com/bandwidth/http/client/HttpClient.java @@ -22,35 +22,23 @@ public interface HttpClient { /** - * Execute a given HttpRequest to get string response back. - * @param request The given HttpRequest to execute. - * @return CompletableFuture of HttpResponse after execution + * Execute a given HttpRequest to get string/binary response back. + * @param request The given HttpRequest to execute. + * @param hasBinaryResponse Whether the response is binary or string. + * @return CompletableFuture of HttpResponse after execution. */ - public CompletableFuture executeAsStringAsync(final HttpRequest request); + public CompletableFuture executeAsync(final HttpRequest request, + boolean hasBinaryResponse); /** - * Execute a given HttpRequest to get binary response back. - * @param request The given HttpRequest to execute. - * @return CompletableFuture of HttpResponse after execution + * Execute a given HttpRequest to get string/binary response back. + * @param request The given HttpRequest to execute. + * @param hasBinaryResponse Whether the response is binary or string. + * @return The converted http response. + * @throws IOException exception to be thrown while converting response. */ - public CompletableFuture executeAsBinaryAsync(final HttpRequest request); - - /** - * Execute a given HttpRequest to get binary response back. - * @param request The given HttpRequest to execute. - * @return HttpResponse after execution - * @throws IOException Signals that an I/O exception of some sort has occurred. - */ - public HttpResponse executeAsBinary(final HttpRequest request) throws IOException; - - /** - * Execute a given HttpRequest to get string response back. - * @param request The given HttpRequest to execute. - * @return HttpResponse after execution - * @throws IOException Signals that an I/O exception of some sort has occurred. - */ - public HttpResponse executeAsString(final HttpRequest request) throws IOException; - + public HttpResponse execute(final HttpRequest request, boolean hasBinaryResponse) + throws IOException; /** * Create a simple HTTP GET request. diff --git a/src/main/java/com/bandwidth/http/client/HttpClientConfiguration.java b/src/main/java/com/bandwidth/http/client/HttpClientConfiguration.java index e5b9a925..098f2cd4 100644 --- a/src/main/java/com/bandwidth/http/client/HttpClientConfiguration.java +++ b/src/main/java/com/bandwidth/http/client/HttpClientConfiguration.java @@ -6,35 +6,134 @@ package com.bandwidth.http.client; - +import com.bandwidth.http.request.HttpMethod; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; /** * Class to hold HTTP Client Configuration. */ public class HttpClientConfiguration implements ReadonlyHttpClientConfiguration { - private long timeout; + /** + * The timeout in seconds to use for making HTTP requests. + */ + private final long timeout; + + /** + * The number of retries to make. + */ + private final int numberOfRetries; + + /** + * To use in calculation of wait time for next request in case of failure. + */ + private final int backOffFactor; + + /** + * To use in calculation of wait time for next request in case of failure. + */ + private final long retryInterval; + + /** + * Http status codes to retry against. + */ + private final Set httpStatusCodesToRetry; + + /** + * Http methods to retry against. + */ + private final Set httpMethodsToRetry; + + /** + * The maximum wait time for overall retrying requests. + */ + private final long maxBackOff; + + /** + * Whether to retry on request timeout. + */ + private final boolean shouldRetryOnTimeout; /** * Default Constructor. */ - public HttpClientConfiguration() { + private HttpClientConfiguration(long timeout, int numberOfRetries, int backOffFactor, + long retryInterval, Set httpStatusCodesToRetry, + Set httpMethodsToRetry, long maxBackOff, boolean shouldRetryOnTimeout) { + this.timeout = timeout; + this.numberOfRetries = numberOfRetries; + this.backOffFactor = backOffFactor; + this.retryInterval = retryInterval; + this.httpStatusCodesToRetry = httpStatusCodesToRetry; + this.httpMethodsToRetry = httpMethodsToRetry; + this.maxBackOff = maxBackOff; + this.shouldRetryOnTimeout = shouldRetryOnTimeout; } /** - * Getter for timeout. - * @return the timeout in seconds + * The timeout in seconds to use for making HTTP requests. + * @return timeout */ public long getTimeout() { return timeout; } /** - * Setter for timeout. - * @param timeout The timeout to set in seconds. + * The number of retries to make. + * @return numberOfRetries */ - public void setTimeout(long timeout) { - this.timeout = timeout; + public int getNumberOfRetries() { + return numberOfRetries; + } + + /** + * To use in calculation of wait time for next request in case of failure. + * @return backOffFactor + */ + public int getBackOffFactor() { + return backOffFactor; + } + + /** + * To use in calculation of wait time for next request in case of failure. + * @return retryInterval + */ + public long getRetryInterval() { + return retryInterval; + } + + /** + * Http status codes to retry against. + * @return httpStatusCodesToRetry + */ + public Set getHttpStatusCodesToRetry() { + return httpStatusCodesToRetry; + } + + /** + * Http methods to retry against. + * @return httpMethodsToRetry + */ + public Set getHttpMethodsToRetry() { + return httpMethodsToRetry; + } + + /** + * The maximum wait time for overall retrying requests. + * @return maxBackOff + */ + public long getMaxBackOff() { + return maxBackOff; + } + + /** + * Whether to retry on request timeout. + * @return shouldRetryOnTimeout + */ + public boolean shouldRetryOnTimeout() { + return shouldRetryOnTimeout; } /** @@ -43,6 +142,160 @@ public void setTimeout(long timeout) { */ @Override public String toString() { - return "HttpClientConfiguration [" + "timeout=" + timeout + "]"; + return "HttpClientConfiguration [" + "timeout=" + timeout + ", numberOfRetries=" + + numberOfRetries + ", backOffFactor=" + backOffFactor + ", retryInterval=" + + retryInterval + ", httpStatusCodesToRetry=" + httpStatusCodesToRetry + + ", httpMethodsToRetry=" + httpMethodsToRetry + ", maxBackOff=" + maxBackOff + + ", shouldRetryOnTimeout=" + shouldRetryOnTimeout + "]"; + } + + /** + * Builds a new {@link HttpClientConfiguration.Builder} object. Creates the instance with the + * current state. + * + * @return a new {@link HttpClientConfiguration.Builder} object + */ + public Builder newBuilder() { + return new Builder() + .timeout(timeout) + .numberOfRetries(numberOfRetries) + .backOffFactor(backOffFactor) + .retryInterval(retryInterval) + .httpStatusCodesToRetry(httpStatusCodesToRetry) + .httpMethodsToRetry(httpMethodsToRetry) + .maxBackOff(maxBackOff) + .shouldRetryOnTimeout(shouldRetryOnTimeout); + } + + /** + * Class to build instances of {@link HttpClientConfiguration}. + */ + public static class Builder { + + private long timeout = 0; + private int numberOfRetries = 0; + private int backOffFactor = 2; + private long retryInterval = 1; + private Set httpStatusCodesToRetry = new HashSet<>(); + private Set httpMethodsToRetry = new HashSet<>(); + private long maxBackOff = 0; + private boolean shouldRetryOnTimeout = true; + + /** + * Default Constructor to initiate builder with default properties. + */ + public Builder() { + // setting default values + httpStatusCodesToRetry.addAll(Arrays.asList(408, 413, 429, 500, 502, 503, 504, 521, 522, + 524, 408, 413, 429, 500, 502, 503, 504, 521, 522, 524)); + httpMethodsToRetry.addAll(Arrays.asList(HttpMethod.GET, HttpMethod.PUT, HttpMethod.GET, + HttpMethod.PUT)); + } + + /** + * The timeout in seconds to use for making HTTP requests.. + * @param timeout The timeout to set. + * @return Builder + */ + public Builder timeout(long timeout) { + if (timeout > 0) { + this.timeout = timeout; + } + return this; + } + + /** + * The number of retries to make.. + * @param numberOfRetries The numberOfRetries to set. + * @return Builder + */ + public Builder numberOfRetries(int numberOfRetries) { + if (numberOfRetries >= 0) { + this.numberOfRetries = numberOfRetries; + } + return this; + } + + /** + * To use in calculation of wait time for next request in case of failure.. + * @param backOffFactor The backOffFactor to set. + * @return Builder + */ + public Builder backOffFactor(int backOffFactor) { + if (backOffFactor >= 1) { + this.backOffFactor = backOffFactor; + } + return this; + } + + /** + * To use in calculation of wait time for next request in case of failure.. + * @param retryInterval The retryInterval to set. + * @return Builder + */ + public Builder retryInterval(long retryInterval) { + if (retryInterval >= 0) { + this.retryInterval = retryInterval; + } + return this; + } + + /** + * Http status codes to retry against.. + * @param httpStatusCodesToRetry The httpStatusCodesToRetry to set. + * @return Builder + */ + public Builder httpStatusCodesToRetry(Set httpStatusCodesToRetry) { + this.httpStatusCodesToRetry.clear(); + if (httpStatusCodesToRetry != null) { + this.httpStatusCodesToRetry.addAll(httpStatusCodesToRetry); + } + return this; + } + + /** + * Http methods to retry against.. + * @param httpMethodsToRetry The httpMethodsToRetry to set. + * @return Builder + */ + public Builder httpMethodsToRetry(Set httpMethodsToRetry) { + this.httpMethodsToRetry.clear(); + if (httpMethodsToRetry != null) { + this.httpMethodsToRetry.addAll(httpMethodsToRetry); + } + return this; + } + + /** + * The maximum wait time for overall retrying requests.. + * @param maxBackOff The maxBackOff to set. + * @return Builder + */ + public Builder maxBackOff(long maxBackOff) { + if (maxBackOff > 0) { + this.maxBackOff = maxBackOff; + } + return this; + } + + /** + * Whether to retry on request timeout. + * @param shouldRetryOnTimeout The shouldRetryOnTimeout to set + * @return Builder + */ + public Builder shouldRetryOnTimeout(boolean shouldRetryOnTimeout) { + this.shouldRetryOnTimeout = shouldRetryOnTimeout; + return this; + } + + /** + * Builds a new HttpClientConfiguration object using the set fields. + * @return {@link HttpClientConfiguration} + */ + public HttpClientConfiguration build() { + return new HttpClientConfiguration(timeout, numberOfRetries, backOffFactor, + retryInterval, httpStatusCodesToRetry, httpMethodsToRetry, maxBackOff, + shouldRetryOnTimeout); + } } } \ No newline at end of file diff --git a/src/main/java/com/bandwidth/http/client/OkClient.java b/src/main/java/com/bandwidth/http/client/OkClient.java index eae29d7f..159ad252 100644 --- a/src/main/java/com/bandwidth/http/client/OkClient.java +++ b/src/main/java/com/bandwidth/http/client/OkClient.java @@ -32,9 +32,9 @@ public class OkClient implements HttpClient { private static final Object syncObject = new Object(); private static volatile okhttp3.OkHttpClient defaultOkHttpClient; - + /** - * Private instance of the okhttp3.OkHttpClient + * Private instance of the okhttp3.OkHttpClient. */ private okhttp3.OkHttpClient client; @@ -42,12 +42,20 @@ public class OkClient implements HttpClient { * Default constructor. * @param httpClientConfig The specified http client configuration. */ - public OkClient(HttpClientConfiguration httpClientConfig) { + public OkClient(ReadonlyHttpClientConfiguration httpClientConfig) { okhttp3.OkHttpClient.Builder clientBuilder = getDefaultOkHttpClient().newBuilder(); - clientBuilder.callTimeout(httpClientConfig.getTimeout(), TimeUnit.SECONDS) - .readTimeout(httpClientConfig.getTimeout(), TimeUnit.SECONDS) + clientBuilder.readTimeout(httpClientConfig.getTimeout(), TimeUnit.SECONDS) .writeTimeout(httpClientConfig.getTimeout(), TimeUnit.SECONDS) .connectTimeout(httpClientConfig.getTimeout(), TimeUnit.SECONDS); + // If retries are allowed then RetryInterceptor must be registered + if (httpClientConfig.getNumberOfRetries() > 0) { + clientBuilder.callTimeout(httpClientConfig.getMaxBackOff(), TimeUnit.SECONDS) + .addInterceptor(new RetryInterceptor(httpClientConfig)); + } else { + clientBuilder.callTimeout(httpClientConfig.getTimeout(), TimeUnit.SECONDS); + } + + clientBuilder.addInterceptor(new HttpRedirectInterceptor(true)); this.client = clientBuilder.build(); } @@ -59,8 +67,7 @@ private okhttp3.OkHttpClient getDefaultOkHttpClient() { synchronized (syncObject) { if (defaultOkHttpClient == null) { defaultOkHttpClient = new okhttp3.OkHttpClient.Builder() - .addInterceptor(new HttpRedirectInterceptor(true)) - .retryOnConnectionFailure(true) + .retryOnConnectionFailure(false) .callTimeout(0, TimeUnit.SECONDS) .build(); } @@ -80,44 +87,29 @@ public static void shutdown() { } /** - * Execute a given HttpRequest to get string response back. - * @param httpRequest The given HttpRequest to execute - * @return CompletableFuture of HttpResponse after execution + * Execute a given HttpRequest to get string/binary response back. + * @param httpRequest The given HttpRequest to execute. + * @param hasBinaryResponse Whether the response is binary or string. + * @return CompletableFuture of HttpResponse after execution. */ - public CompletableFuture executeAsStringAsync(final HttpRequest httpRequest) { + public CompletableFuture executeAsync(final HttpRequest httpRequest, + boolean hasBinaryResponse) { okhttp3.Request okHttpRequest = convertRequest(httpRequest); - final CompletableFuture callBack = new CompletableFuture<>(); - client.newCall(okHttpRequest).enqueue(new okhttp3.Callback() { - - public void onFailure(okhttp3.Call call, IOException e) { - publishResponse(null, httpRequest, callBack, e, false); - } - - public void onResponse(okhttp3.Call call, okhttp3.Response okHttpResponse) { - publishResponse(okHttpResponse, httpRequest, callBack, null, false); - okHttpResponse.close(); - } - }); - - return callBack; - } + + RetryInterceptor retryInterceptor = getRetryInterceptor(); + if (retryInterceptor != null) { + retryInterceptor.addRequestEntry(okHttpRequest); + } - /** - * Execute a given HttpRequest to get binary response back. - * @param httpRequest The given HttpRequest to execute. - * @return CompletableFuture of HttpResponse after execution - */ - public CompletableFuture executeAsBinaryAsync(final HttpRequest httpRequest) { - okhttp3.Request okHttpRequest = convertRequest(httpRequest); final CompletableFuture callBack = new CompletableFuture<>(); client.newCall(okHttpRequest).enqueue(new okhttp3.Callback() { public void onFailure(okhttp3.Call call, IOException e) { - publishResponse(null, httpRequest, callBack, e, true); + publishResponse(null, httpRequest, callBack, e, hasBinaryResponse); } public void onResponse(okhttp3.Call call, okhttp3.Response okHttpResponse) { - publishResponse(okHttpResponse, httpRequest, callBack, null, true); + publishResponse(okHttpResponse, httpRequest, callBack, null, hasBinaryResponse); } }); @@ -125,38 +117,51 @@ public void onResponse(okhttp3.Call call, okhttp3.Response okHttpResponse) { } /** - * Execute a given HttpRequest to get string response back. - * @param httpRequest The given HttpRequest to execute. + * Execute a given HttpRequest to get string/binary response back. + * @param httpRequest The given HttpRequest to execute. + * @param hasBinaryResponse Whether the response is binary or string. + * @return The converted http response. + * @throws IOException exception to be thrown while converting response. */ - public HttpResponse executeAsString(HttpRequest httpRequest) throws IOException { + public HttpResponse execute(HttpRequest httpRequest, boolean hasBinaryResponse) + throws IOException { okhttp3.Request okHttpRequest = convertRequest(httpRequest); - okhttp3.Response okHttpResponse = client.newCall(okHttpRequest).execute(); - return convertResponse(okHttpResponse, false); + + RetryInterceptor retryInterceptor = getRetryInterceptor(); + if (retryInterceptor != null) { + retryInterceptor.addRequestEntry(okHttpRequest); + } + + okhttp3.Response okHttpResponse = null; + okHttpResponse = client.newCall(okHttpRequest).execute(); + return convertResponse(httpRequest, okHttpResponse, hasBinaryResponse); } /** - * Execute a given HttpRequest to get binary response back. - * @param httpRequest The given HttpRequest to execute. + * Returns RetryInterceptor instance registered with client. + * @return The RetryInterceptor instance. */ - public HttpResponse executeAsBinary(HttpRequest httpRequest) throws IOException { - okhttp3.Request okHttpRequest = convertRequest(httpRequest); - okhttp3.Response okHttpResponse = client.newCall(okHttpRequest).execute(); - return convertResponse(okHttpResponse, true); + private RetryInterceptor getRetryInterceptor() { + return (RetryInterceptor) this.client.interceptors().stream() + .filter(interceptor -> interceptor instanceof RetryInterceptor).findFirst() + .orElse(null); } /** * Publishes success or failure result as HttpResponse from a HttpRequest. - * @param okHttpResponse The okhttp response to publish. - * @param httpRequest The internal http request. - * @param completionBlock The success and failure code block reference to invoke the delegate. - * @param error The reported errors for getting the http response. + * @param okHttpResponse The okhttp response to publish. + * @param httpRequest The internal http request. + * @param completionBlock The success and failure code block reference to invoke the delegate. + * @param error The reported errors for getting the http response. + * @param hasBinaryResponse Whether the response is binary or string. + * @return The converted http response. */ - private static HttpResponse publishResponse(okhttp3.Response okHttpResponse, + private HttpResponse publishResponse(okhttp3.Response okHttpResponse, HttpRequest httpRequest, CompletableFuture completionBlock, - Throwable error, boolean binaryResponse) { + Throwable error, boolean hasBinaryResponse) { HttpResponse httpResponse = null; try { - httpResponse = OkClient.convertResponse(okHttpResponse, binaryResponse); + httpResponse = convertResponse(httpRequest, okHttpResponse, hasBinaryResponse); // if there are no errors, pass on to the callback function if (error == null && httpResponse != null) { @@ -172,33 +177,34 @@ private static HttpResponse publishResponse(okhttp3.Response okHttpResponse, /** * Converts a given OkHttp response into our internal http response model. - * @param response The given OkHttp response. + * @param response The given OkHttp response. + * @param hasBinaryResponse Whether the response is binary or string. * @return The converted http response. * @throws IOException exception to be thrown while converting response. */ - private static HttpResponse convertResponse(okhttp3.Response response, - boolean binaryResponse) throws IOException { + protected static HttpResponse convertResponse(HttpRequest request, okhttp3.Response response, + boolean hasBinaryResponse) throws IOException { HttpResponse httpResponse = null; - if (null == response) { - return null; - } - - okhttp3.ResponseBody responseBody = response.body(); + if (response != null) { - Headers headers = new Headers(response.headers().toMultimap()); + okhttp3.ResponseBody responseBody = response.body(); - if (binaryResponse) { - InputStream responseStream = responseBody.byteStream(); - httpResponse = new HttpResponse(response.code(), headers, responseStream); - } else { - String responseString = responseBody.string(); - InputStream responseStream = new ByteArrayInputStream(responseString.getBytes()); - httpResponse = new HttpStringResponse(response.code(), headers, responseStream, - responseString); + Headers headers = new Headers(response.headers().toMultimap()); - responseBody.close(); - response.close(); + if (hasBinaryResponse) { + InputStream responseStream = responseBody.byteStream(); + httpResponse = new HttpResponse(response.code(), headers, responseStream); + } else { + String responseString = responseBody.string(); + InputStream responseStream = new ByteArrayInputStream( + responseString.getBytes()); + httpResponse = new HttpStringResponse(response.code(), headers, responseStream, + responseString); + + responseBody.close(); + response.close(); + } } return httpResponse; @@ -206,10 +212,10 @@ private static HttpResponse convertResponse(okhttp3.Response response, /** * Converts a given internal http request into an okhttp request model. - * @param httpRequest The given http request in internal format - * @return The converted okhttp request + * @param httpRequest The given http request in internal format. + * @return The converted okhttp request */ - private static okhttp3.Request convertRequest(HttpRequest httpRequest) { + private okhttp3.Request convertRequest(HttpRequest httpRequest) { okhttp3.RequestBody requestBody; if (httpRequest instanceof HttpBodyRequest) { @@ -217,7 +223,7 @@ private static okhttp3.Request convertRequest(HttpRequest httpRequest) { // set request media type String contentType; Object body = ((HttpBodyRequest) httpRequest).getBody(); - + // set request body if (body instanceof FileWrapper) { FileWrapper file = (FileWrapper) body; @@ -290,7 +296,7 @@ private static okhttp3.Request convertRequest(HttpRequest httpRequest) { // set query parameters ApiHelper.appendUrlWithQueryParameters(urlBuilder, httpRequest.getQueryParameters()); - //validate and preprocess url + // validate and preprocess url String url = ApiHelper.cleanUrl(urlBuilder); // build the request diff --git a/src/main/java/com/bandwidth/http/client/ReadonlyHttpClientConfiguration.java b/src/main/java/com/bandwidth/http/client/ReadonlyHttpClientConfiguration.java index 39f1d419..5a3924d6 100644 --- a/src/main/java/com/bandwidth/http/client/ReadonlyHttpClientConfiguration.java +++ b/src/main/java/com/bandwidth/http/client/ReadonlyHttpClientConfiguration.java @@ -6,6 +6,8 @@ package com.bandwidth.http.client; +import com.bandwidth.http.request.HttpMethod; +import java.util.Set; /** * Interface for holding HTTP Client Configuration. @@ -13,8 +15,51 @@ public interface ReadonlyHttpClientConfiguration { /** - * Long value for timeout. - * @return the timeout + * The timeout in seconds to use for making HTTP requests. + * @return a copy of timeout */ - public long getTimeout(); + long getTimeout(); + + /** + * The number of retries to make. + * @return a copy of numberOfRetries + */ + int getNumberOfRetries(); + + /** + * To use in calculation of wait time for next request in case of failure. + * @return a copy of backOffFactor + */ + int getBackOffFactor(); + + /** + * To use in calculation of wait time for next request in case of failure. + * @return a copy of retryInterval + */ + long getRetryInterval(); + + /** + * Http status codes to retry against. + * @return a copy of httpStatusCodesToRetry + */ + Set getHttpStatusCodesToRetry(); + + /** + * Http methods to retry against. + * @return a copy of httpMethodsToRetry + */ + Set getHttpMethodsToRetry(); + + /** + * The maximum wait time for overall retrying requests. + * @return a copy of maxBackOff + */ + long getMaxBackOff(); + + /** + * Whether to retry on request timeout. + * @return a copy of shouldRetryOnTimeout + */ + boolean shouldRetryOnTimeout(); + } \ No newline at end of file diff --git a/src/main/java/com/bandwidth/http/client/RetryInterceptor.java b/src/main/java/com/bandwidth/http/client/RetryInterceptor.java new file mode 100644 index 00000000..e580036a --- /dev/null +++ b/src/main/java/com/bandwidth/http/client/RetryInterceptor.java @@ -0,0 +1,277 @@ +/* + * BandwidthLib + * + * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). + */ + +package com.bandwidth.http.client; + +import com.bandwidth.http.request.HttpMethod; +import java.io.IOException; +import java.net.SocketException; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.TimeUnit; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +/** + * RetryInterceptor intercepts and retry requests if failed based on configuration. + */ +public class RetryInterceptor implements Interceptor { + + private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER = + DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z") + .withZone(ZoneId.of("GMT")); + + /** + * To keep track of requests being sent and its current state. + */ + private final ConcurrentMap requestEntries; + + /** + * User specified retry configurations. + */ + private final ReadonlyHttpClientConfiguration httpClientConfiguration; + + /** + * Default Constructor, Initializes the httpClientConfiguration attribute. + * + * @param httpClientConfig the user specified configurations. + */ + public RetryInterceptor(ReadonlyHttpClientConfiguration httpClientConfig) { + this.httpClientConfiguration = httpClientConfig; + requestEntries = new ConcurrentHashMap<>(); + } + + /** + * Intercepts and retry requests if failed based on configuration. + * @see okhttp3.Interceptor#intercept(okhttp3.Interceptor.Chain) + */ + @SuppressWarnings("resource") + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + RequestState requestState = getRequestState(request); + Response response = null; + try { + response = chain.proceed(request); + } catch (IOException ioException) { + if (httpClientConfiguration.shouldRetryOnTimeout() + && httpClientConfiguration.getNumberOfRetries() > 0) { + response = retryOnTimeout(chain, request, requestState, ioException); + } + } + while (requestState != null && needToRetry(request, response)) { + requestState.retryCount++; + // Performing wait time calculation. + calculateWaitTime(requestState, response); + + // Checking total wait time against allowed max back-off time + if (hasWaitTimeLimitExceeded(requestState)) { + break; + } + + + // Waiting before making next request + holdExecution(requestState); + // proceeding with execution of next request + try { + response.close(); + response = chain.proceed(request); + } catch (SocketException socketException) { + response = chain.proceed(request); + } catch (IOException ioException) { + if (httpClientConfiguration.shouldRetryOnTimeout() + && httpClientConfiguration.getNumberOfRetries() > 0) { + response = retryOnTimeout(chain, request, requestState, ioException); + } + } + + } + + this.requestEntries.remove(request); + return response; + } + + /** + * Adds entry into Request entry map. + * @param okHttpRequest the OK HTTP Request. + */ + public void addRequestEntry(Request okHttpRequest) { + this.requestEntries.put(okHttpRequest, new RequestState()); + } + + /** + * Checks if the overall wait time has reached to its limit. + * @param requestState the current state of request entry. + * @return true if total wait time exceeds maximum back-off time. + */ + private boolean hasWaitTimeLimitExceeded(RequestState requestState) { + return this.httpClientConfiguration.getMaxBackOff() > 0 + && toMilliseconds(this.httpClientConfiguration + .getMaxBackOff()) < requestState.totalWaitTimeInMilliSeconds; + } + + + /** + * Checks if the retry request is to be made against provided response. + * @param request the HTTP request. + * @param response the HTTP response. + * @return true if request is needed to be retried. + */ + private boolean needToRetry(Request request, Response response) { + + return (getRequestState(request).retryCount < this.httpClientConfiguration + .getNumberOfRetries() + && this.httpClientConfiguration.getHttpMethodsToRetry() + .contains(HttpMethod.valueOf(request.method())) + && response != null && (this.httpClientConfiguration.getHttpStatusCodesToRetry() + .contains(response.code()) || hasRetryAfterHeader(response))); + } + + /** + * Calculates the wait time for next request. + * @param requestState the current state of request entry. + * @param response the HTTP response. + */ + private void calculateWaitTime(RequestState requestState, Response response) { + long retryAfterHeaderValue = 0; + if (hasRetryAfterHeader(response)) { + retryAfterHeaderValue = getCalculatedHeaderValue(response.header("Retry-After")); + } + long calculatedBackOffInMilliSeconds = getCalculatedBackOffValue(requestState); + requestState.currentWaitInMilliSeconds = + calculatedBackOffInMilliSeconds > retryAfterHeaderValue + ? calculatedBackOffInMilliSeconds + : retryAfterHeaderValue; + requestState.totalWaitTimeInMilliSeconds += requestState.currentWaitInMilliSeconds; + } + + /** + * Checks if the response contains Retry-After header. + * @param response the HTTP response. + * @return true if response contains Retry-After header. + */ + private boolean hasRetryAfterHeader(Response response) { + String retryAfter = response.header("Retry-After"); + if (retryAfter != null && !retryAfter.isEmpty()) { + return true; + } + return false; + } + + /** + * Analyzes the header value and checks the header if it contains date in proper format or + * seconds. If header value is date then it calculates the delta time in milliseconds. + * @param headerValue the retry-after header value. + * @return long value of calculated wait time in milliseconds. + */ + private long getCalculatedHeaderValue(String headerValue) { + try { + return toMilliseconds(Long.parseLong(headerValue)); + } catch (NumberFormatException nfe) { + long requestAtValueInSeconds = LocalDateTime + .parse(headerValue, RFC1123_DATE_TIME_FORMATTER).toEpochSecond(ZoneOffset.UTC); + long currentDateTimeInSeconds = LocalDateTime + .now(ZoneOffset.UTC).toEpochSecond(ZoneOffset.UTC); + return toMilliseconds(requestAtValueInSeconds - currentDateTimeInSeconds); + } + } + + /** + * Calculates the back-off value based on a formula which uses back-off factor and retry Count. + * @param requestState the current state of request entry. + * @return long value of back-off time based on formula in milliseconds. + */ + private long getCalculatedBackOffValue(RequestState requestState) { + return (long) (1000 * this.httpClientConfiguration.getRetryInterval() + * Math.pow(this.httpClientConfiguration.getBackOffFactor(), + requestState.retryCount - 1) + Math.random() * 100); + } + + /** + * Holds the execution for stored wait time in milliseconds of this thread. + * @param requestState the current state of request entry. + */ + private void holdExecution(RequestState requestState) { + try { + TimeUnit.MILLISECONDS.sleep(requestState.currentWaitInMilliSeconds); + } catch (InterruptedException e) { + // No handler needed + } + } + + /** + * Converts the seconds to milliseconds. + * @param seconds The seconds to convert. + * @return long value of milliseconds. + */ + private long toMilliseconds(long seconds) { + return seconds * 1000; + } + + /** + * getter for current request state entry from map. + * @param okHttpRequest the OK HTTP Request. + * @return RequestEntry the current request entry. + */ + private RequestState getRequestState(Request okHttpRequest) { + return this.requestEntries.get(okHttpRequest); + } + + /** + * Retries on the request which caused the request timeout to occur based on HTTP Client + * Configurations. + * @param chain The interceptor chain. + * @param request The OkHttp request. + * @param exception The thrown exception. + * @return The OKHttp response. + * @throws IOException the same exception which was thrown while retrying. + */ + private okhttp3.Response retryOnTimeout(Chain chain, Request request, RequestState requestState, + IOException exception) throws IOException { + + while (requestState.retryCount++ < httpClientConfiguration.getNumberOfRetries() + && !this.hasWaitTimeLimitExceeded(requestState)) { + + try { + return chain.proceed(request); + } catch (IOException ioException) { + exception = ioException; + } finally { + requestState.totalWaitTimeInMilliSeconds += + toMilliseconds(httpClientConfiguration.getTimeout()); + } + } + + throw exception; + } + + + /** + * Class to hold the request info until request completes. + */ + private class RequestState { + + /** + * To keep track of requests count. + */ + private int retryCount = 0; + + /** + * To store the wait time for next request. + */ + private long currentWaitInMilliSeconds = 0; + + /** + * To keep track of overall wait time. + */ + private long totalWaitTimeInMilliSeconds = 0; + } +} \ No newline at end of file diff --git a/src/main/java/com/bandwidth/http/request/MultipartFileWrapper.java b/src/main/java/com/bandwidth/http/request/MultipartFileWrapper.java index caef2ca6..24c87d75 100644 --- a/src/main/java/com/bandwidth/http/request/MultipartFileWrapper.java +++ b/src/main/java/com/bandwidth/http/request/MultipartFileWrapper.java @@ -8,13 +8,16 @@ import com.bandwidth.http.Headers; import com.bandwidth.utilities.FileWrapper; +import com.fasterxml.jackson.annotation.JsonInclude; /** * Class to wrap file and headers to be sent as part of a multipart request. */ public class MultipartFileWrapper { + @JsonInclude(JsonInclude.Include.NON_NULL) private FileWrapper fileWrapper; + @JsonInclude(JsonInclude.Include.NON_NULL) private Headers headers; /** diff --git a/src/main/java/com/bandwidth/http/request/MultipartWrapper.java b/src/main/java/com/bandwidth/http/request/MultipartWrapper.java index 401f7726..c30076f9 100644 --- a/src/main/java/com/bandwidth/http/request/MultipartWrapper.java +++ b/src/main/java/com/bandwidth/http/request/MultipartWrapper.java @@ -7,22 +7,25 @@ package com.bandwidth.http.request; import com.bandwidth.http.Headers; +import com.fasterxml.jackson.annotation.JsonInclude; /** * Class to wrap byteArray and headers to be sent as part of a multipart request. */ public class MultipartWrapper { - private byte[] byteArray; + @JsonInclude(JsonInclude.Include.NON_NULL) + private String serializedObj; + @JsonInclude(JsonInclude.Include.NON_NULL) private Headers headers; /** * Initialization constructor. - * @param byteArray Array of bytes + * @param serializedObj Serialized string of object to be wrapped. * @param headers Headers for wrapping */ - public MultipartWrapper(byte[] byteArray, Headers headers) { - this.byteArray = byteArray; + public MultipartWrapper(String serializedObj, Headers headers) { + this.serializedObj = serializedObj; this.headers = headers; } @@ -31,7 +34,7 @@ public MultipartWrapper(byte[] byteArray, Headers headers) { * @return Array of bytes. */ public byte[] getByteArray() { - return byteArray; + return serializedObj.getBytes(); } /** diff --git a/src/main/java/com/bandwidth/internal/OptionalNullable.java b/src/main/java/com/bandwidth/internal/OptionalNullable.java new file mode 100644 index 00000000..47369e02 --- /dev/null +++ b/src/main/java/com/bandwidth/internal/OptionalNullable.java @@ -0,0 +1,157 @@ +/* + * BandwidthLib + * + * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). + */ + +package com.bandwidth.internal; + +import com.bandwidth.DateTimeHelper; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; +import java.io.IOException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +/** + * Class to encapsulate fields which are Optional as well as Nullable. It also + * provides helper methods to create OptionalNullable generic type, and to + * extract value from it. + * @param Type of the encapsulated field. + */ +public class OptionalNullable { + + /** + * Private store for encapsulated object's value. + */ + private T value; + + private OptionalNullable(T value) { + this.value = value; + } + + /** + * Converts this OptionalNullable into string format. + * @return String representation of this class + */ + @Override + public String toString() { + return "" + value; + } + + /** + * Creates an OptionalNullable instance with the provided value. + * @param Type of the provided object. + * @param value Value of the provided object. + * @return {@link OptionalNullable} instance encapsulating given value. + */ + public static OptionalNullable of(T value) { + return new OptionalNullable(value); + } + + /** + * Extracts the encapsulated value from the given OptionalNullable. + * @param Type of the expected value. + * @param optionalNullable OptionalNullable instance to get value. + * @return Value of the extracted field. + */ + public static T getFrom(OptionalNullable optionalNullable) { + return (optionalNullable == null) ? null : optionalNullable.value; + } + + /** + * JsonSerializer for the {@link OptionalNullable} instance. It is used to + * Serialize an {@link OptionalNullable} as its encapsulated object. + */ + public static class Serializer extends JsonSerializer> { + @Override + public void serialize(OptionalNullable object, JsonGenerator jgen, + SerializerProvider provider) throws IOException { + jgen.writeObject(object.value); + } + } + + /** + * A class to handle serialization of Unix Timestamps to DateTime objects. + */ + public static class UnixTimestampSerializer extends JsonSerializer> { + @SuppressWarnings("unchecked") + @Override + public void serialize(OptionalNullable object, JsonGenerator jgen, + SerializerProvider provider) throws IOException { + if (object.value instanceof List) { + jgen.writeObject( + DateTimeHelper.toUnixTimestampLong((List) object.value)); + } else if (object.value instanceof Map) { + jgen.writeObject(DateTimeHelper + .toUnixTimestampLong((Map) object.value)); + } else { + jgen.writeObject(DateTimeHelper.toUnixTimestampLong((LocalDateTime) object.value)); + } + } + } + + /** + * A class to handle serialization of Rfc1123 format strings to DateTime + * objects. + */ + public static class Rfc1123DateTimeSerializer extends JsonSerializer> { + @SuppressWarnings("unchecked") + @Override + public void serialize(OptionalNullable object, JsonGenerator jgen, + SerializerProvider provider) throws IOException { + if (object.value instanceof List) { + jgen.writeObject( + DateTimeHelper.toRfc1123DateTime((List) object.value)); + } else if (object.value instanceof Map) { + jgen.writeObject(DateTimeHelper + .toRfc1123DateTime((Map) object.value)); + } else { + jgen.writeString(DateTimeHelper.toRfc1123DateTime((LocalDateTime) object.value)); + } + } + } + + /** + * A class to handle serialization of Rfc8601(Rfc3339) format strings to + * DateTime objects. + */ + public static class Rfc8601DateTimeSerializer extends JsonSerializer> { + @SuppressWarnings("unchecked") + @Override + public void serialize(OptionalNullable object, JsonGenerator jgen, + SerializerProvider provider) throws IOException { + if (object.value instanceof List) { + jgen.writeObject( + DateTimeHelper.toRfc8601DateTime((List) object.value)); + } else if (object.value instanceof Map) { + jgen.writeObject(DateTimeHelper + .toRfc8601DateTime((Map) object.value)); + } else { + jgen.writeString(DateTimeHelper.toRfc8601DateTime((LocalDateTime) object.value)); + } + } + } + + /** + * A class to handle serialization of LocalDate objects to date strings. + */ + public static class SimpleDateSerializer extends JsonSerializer> { + @SuppressWarnings("unchecked") + @Override + public void serialize(OptionalNullable object, JsonGenerator jgen, + SerializerProvider provider) throws IOException { + if (object.value instanceof List) { + jgen.writeObject(DateTimeHelper.toSimpleDate((List) object.value)); + } else if (object.value instanceof Map) { + jgen.writeObject( + DateTimeHelper.toSimpleDate((Map) object.value)); + } else { + jgen.writeString(DateTimeHelper.toSimpleDate((LocalDate) object.value)); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/com/bandwidth/messaging/controllers/APIController.java b/src/main/java/com/bandwidth/messaging/controllers/APIController.java index 30ee9b52..217309ab 100644 --- a/src/main/java/com/bandwidth/messaging/controllers/APIController.java +++ b/src/main/java/com/bandwidth/messaging/controllers/APIController.java @@ -78,7 +78,7 @@ public ApiResponse> listMedia( HttpRequest request = buildListMediaRequest(userId, continuationToken); authManagers.get("messaging").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleListMediaResponse(context); @@ -97,7 +97,7 @@ public CompletableFuture>> listMediaAsync( return makeHttpCallAsync(() -> buildListMediaRequest(userId, continuationToken), req -> authManagers.get("messaging").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleListMediaResponse(context)); } @@ -195,7 +195,7 @@ public ApiResponse getMedia( HttpRequest request = buildGetMediaRequest(userId, mediaId); authManagers.get("messaging").apply(request); - HttpResponse response = getClientInstance().executeAsBinary(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetMediaResponse(context); @@ -213,7 +213,7 @@ public CompletableFuture> getMediaAsync( return makeHttpCallAsync(() -> buildGetMediaRequest(userId, mediaId), req -> authManagers.get("messaging").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetMediaResponse(context)); } @@ -318,7 +318,7 @@ public ApiResponse uploadMedia( contentType, cacheControl); authManagers.get("messaging").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleUploadMediaResponse(context); @@ -346,7 +346,7 @@ public CompletableFuture> uploadMediaAsync( contentType, cacheControl), req -> authManagers.get("messaging").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleUploadMediaResponse(context)); } @@ -447,7 +447,7 @@ public ApiResponse deleteMedia( HttpRequest request = buildDeleteMediaRequest(userId, mediaId); authManagers.get("messaging").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleDeleteMediaResponse(context); @@ -465,7 +465,7 @@ public CompletableFuture> deleteMediaAsync( return makeHttpCallAsync(() -> buildDeleteMediaRequest(userId, mediaId), req -> authManagers.get("messaging").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleDeleteMediaResponse(context)); } @@ -583,7 +583,7 @@ public ApiResponse getMessages( messageStatus, errorCode, fromDateTime, toDateTime, pageToken, limit); authManagers.get("messaging").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetMessagesResponse(context); @@ -626,7 +626,7 @@ public CompletableFuture> getMessagesAsync( limit), req -> authManagers.get("messaging").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetMessagesResponse(context)); } @@ -745,7 +745,7 @@ public ApiResponse createMessage( HttpRequest request = buildCreateMessageRequest(userId, body); authManagers.get("messaging").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleCreateMessageResponse(context); @@ -763,7 +763,7 @@ public CompletableFuture> createMessageAsync( return makeHttpCallAsync(() -> buildCreateMessageRequest(userId, body), req -> authManagers.get("messaging").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleCreateMessageResponse(context)); } @@ -849,4 +849,4 @@ private ApiResponse handleCreateMessageResponse( return new ApiResponse(response.getStatusCode(), response.getHeaders(), result); } -} \ No newline at end of file +} diff --git a/src/main/java/com/bandwidth/phonenumberlookup/controllers/APIController.java b/src/main/java/com/bandwidth/phonenumberlookup/controllers/APIController.java new file mode 100644 index 00000000..9a4aabc5 --- /dev/null +++ b/src/main/java/com/bandwidth/phonenumberlookup/controllers/APIController.java @@ -0,0 +1,890 @@ +/* + * BandwidthLib + * + * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). + */ + +package com.bandwidth.phonenumberlookup.controllers; + +import com.bandwidth.ApiHelper; +import com.bandwidth.AuthManager; +import com.bandwidth.Configuration; +import com.bandwidth.Server; +import com.bandwidth.controllers.BaseController; +import com.bandwidth.exceptions.ApiException; +import com.bandwidth.http.Headers; +import com.bandwidth.http.client.HttpCallback; +import com.bandwidth.http.client.HttpClient; +import com.bandwidth.http.client.HttpContext; +import com.bandwidth.http.request.HttpRequest; +import com.bandwidth.http.response.ApiResponse; +import com.bandwidth.http.response.HttpResponse; +import com.bandwidth.http.response.HttpStringResponse; +import com.bandwidth.phonenumberlookup.exceptions.AccountsTnlookup400ErrorException; +import com.bandwidth.phonenumberlookup.models.OrderRequest; +import com.bandwidth.phonenumberlookup.models.OrderResponse; +import com.bandwidth.phonenumberlookup.models.OrderStatus; +import com.fasterxml.jackson.core.JsonProcessingException; +import java.io.IOException; +import java.util.AbstractMap.SimpleEntry; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +/** + * This class lists all the endpoints of the groups. + */ +public final class APIController extends BaseController { + + /** + * Initializes the controller. + * @param config Configurations added in client. + * @param httpClient Send HTTP requests and read the responses. + * @param authManagers Apply authorization to requests. + */ + public APIController(Configuration config, HttpClient httpClient, + Map authManagers) { + super(config, httpClient, authManagers); + } + + /** + * Initializes the controller with HTTPCallback. + * @param config Configurations added in client. + * @param httpClient Send HTTP requests and read the responses. + * @param authManagers Apply authorization to requests. + * @param httpCallback Callback to be called before and after the HTTP call. + */ + public APIController(Configuration config, HttpClient httpClient, + Map authManagers, HttpCallback httpCallback) { + super(config, httpClient, authManagers, httpCallback); + } + + /** + * Create a TN Lookup Order. + * @param accountId Required parameter: The ID of the Bandwidth account that the user belongs + * to. + * @param body Required parameter: Example: + * @return Returns the OrderResponse wrapped in ApiResponse response from the API call + * @throws ApiException Represents error response from the server. + * @throws IOException Signals that an I/O exception of some sort has occurred. + */ + public ApiResponse createLookupRequest( + final String accountId, + final OrderRequest body) throws ApiException, IOException { + HttpRequest request = buildCreateLookupRequestRequest(accountId, body); + authManagers.get("phoneNumberLookup").apply(request); + + HttpResponse response = getClientInstance().execute(request, false); + HttpContext context = new HttpContext(request, response); + + return handleCreateLookupRequestResponse(context); + } + + /** + * Create a TN Lookup Order. + * @param accountId Required parameter: The ID of the Bandwidth account that the user belongs + * to. + * @param body Required parameter: Example: + * @return Returns the OrderResponse wrapped in ApiResponse response from the API call + */ + public CompletableFuture> createLookupRequestAsync( + final String accountId, + final OrderRequest body) { + return makeHttpCallAsync(() -> buildCreateLookupRequestRequest(accountId, body), + req -> authManagers.get("phoneNumberLookup").applyAsync(req) + .thenCompose(request -> getClientInstance() + .executeAsync(request, false)), + context -> handleCreateLookupRequestResponse(context)); + } + + /** + * Builds the HttpRequest object for createLookupRequest. + */ + private HttpRequest buildCreateLookupRequestRequest( + final String accountId, + final OrderRequest body) throws JsonProcessingException { + //the base uri for api requests + String baseUri = config.getBaseUri(Server.PHONENUMBERLOOKUPDEFAULT); + + //prepare query string for API call + final StringBuilder queryBuilder = new StringBuilder(baseUri + + "/accounts/{accountId}/tnlookup"); + + //process template parameters + Map> templateParameters = new HashMap<>(); + templateParameters.put("accountId", + new SimpleEntry(accountId, false)); + ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters); + + //load all headers for the outgoing API request + Headers headers = new Headers(); + headers.add("user-agent", BaseController.userAgent); + headers.add("accept", "application/json"); + headers.add("content-type", "application/json"); + + //prepare and invoke the API call request to fetch the response + String bodyJson = ApiHelper.serialize(body); + HttpRequest request = getClientInstance().postBody(queryBuilder, headers, null, bodyJson); + + // Invoke the callback before request if its not null + if (getHttpCallback() != null) { + getHttpCallback().onBeforeRequest(request); + } + + return request; + } + + /** + * Processes the response for createLookupRequest. + * @return An object of type OrderResponse + */ + private ApiResponse handleCreateLookupRequestResponse( + HttpContext context) throws ApiException, IOException { + HttpResponse response = context.getResponse(); + + //invoke the callback after response if its not null + if (getHttpCallback() != null) { + getHttpCallback().onAfterResponse(context); + } + + //Error handling using HTTP status codes + int responseCode = response.getStatusCode(); + + if (responseCode == 400) { + throw new AccountsTnlookup400ErrorException("Bad Request. Ensure that your request payload is properly formatted and that the telephone numbers used are valid.", context); + } + if (responseCode == 401) { + throw new ApiException("Unauthorized. Ensure that you are using the proper credentials for the environment you are accessing, your user has the proper role assigned to it, and that your Bandwidth account is enabled for TN Lookup access.", context); + } + if (responseCode == 415) { + throw new ApiException("Invalid content-type. Ensure that your content-type header is set to application/json.", context); + } + if (responseCode == 429) { + throw new ApiException("Too Many Requests. Reduce the amount of requests that you are sending in order to avoid receiving this status code.", context); + } + if (responseCode == 500) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 501) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 502) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 503) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 504) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 505) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 506) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 507) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 508) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 509) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 510) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 511) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 512) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 513) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 514) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 515) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 516) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 517) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 518) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 519) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 520) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 521) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 522) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 523) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 524) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 525) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 526) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 527) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 528) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 529) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 530) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 531) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 532) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 533) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 534) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 535) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 536) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 537) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 538) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 539) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 540) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 541) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 542) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 543) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 544) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 545) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 546) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 547) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 548) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 549) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 550) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 551) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 552) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 553) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 554) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 555) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 556) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 557) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 558) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 559) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 560) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 561) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 562) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 563) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 564) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 565) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 566) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 567) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 568) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 569) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 570) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 571) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 572) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 573) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 574) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 575) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 576) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 577) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 578) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 579) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 580) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 581) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 582) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 583) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 584) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 585) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 586) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 587) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 588) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 589) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 590) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 591) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 592) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 593) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 594) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 595) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 596) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 597) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 598) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 599) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + //handle errors defined at the API level + validateResponse(response, context); + + //extract result from the http response + String responseBody = ((HttpStringResponse) response).getBody(); + OrderResponse result = ApiHelper.deserialize(responseBody, + OrderResponse.class); + + return new ApiResponse(response.getStatusCode(), response.getHeaders(), result); + } + + /** + * Query an existing TN Lookup Order. + * @param accountId Required parameter: The ID of the Bandwidth account that the user belongs + * to. + * @param requestId Required parameter: Example: + * @return Returns the OrderStatus wrapped in ApiResponse response from the API call + * @throws ApiException Represents error response from the server. + * @throws IOException Signals that an I/O exception of some sort has occurred. + */ + public ApiResponse getLookupRequestStatus( + final String accountId, + final String requestId) throws ApiException, IOException { + HttpRequest request = buildGetLookupRequestStatusRequest(accountId, requestId); + authManagers.get("phoneNumberLookup").apply(request); + + HttpResponse response = getClientInstance().execute(request, false); + HttpContext context = new HttpContext(request, response); + + return handleGetLookupRequestStatusResponse(context); + } + + /** + * Query an existing TN Lookup Order. + * @param accountId Required parameter: The ID of the Bandwidth account that the user belongs + * to. + * @param requestId Required parameter: Example: + * @return Returns the OrderStatus wrapped in ApiResponse response from the API call + */ + public CompletableFuture> getLookupRequestStatusAsync( + final String accountId, + final String requestId) { + return makeHttpCallAsync(() -> buildGetLookupRequestStatusRequest(accountId, requestId), + req -> authManagers.get("phoneNumberLookup").applyAsync(req) + .thenCompose(request -> getClientInstance() + .executeAsync(request, false)), + context -> handleGetLookupRequestStatusResponse(context)); + } + + /** + * Builds the HttpRequest object for getLookupRequestStatus. + */ + private HttpRequest buildGetLookupRequestStatusRequest( + final String accountId, + final String requestId) { + //the base uri for api requests + String baseUri = config.getBaseUri(Server.PHONENUMBERLOOKUPDEFAULT); + + //prepare query string for API call + final StringBuilder queryBuilder = new StringBuilder(baseUri + + "/accounts/{accountId}/tnlookup/{requestId}"); + + //process template parameters + Map> templateParameters = new HashMap<>(); + templateParameters.put("accountId", + new SimpleEntry(accountId, false)); + templateParameters.put("requestId", + new SimpleEntry(requestId, false)); + ApiHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters); + + //load all headers for the outgoing API request + Headers headers = new Headers(); + headers.add("user-agent", BaseController.userAgent); + headers.add("accept", "application/json"); + + //prepare and invoke the API call request to fetch the response + HttpRequest request = getClientInstance().get(queryBuilder, headers, null, null); + + // Invoke the callback before request if its not null + if (getHttpCallback() != null) { + getHttpCallback().onBeforeRequest(request); + } + + return request; + } + + /** + * Processes the response for getLookupRequestStatus. + * @return An object of type OrderStatus + */ + private ApiResponse handleGetLookupRequestStatusResponse( + HttpContext context) throws ApiException, IOException { + HttpResponse response = context.getResponse(); + + //invoke the callback after response if its not null + if (getHttpCallback() != null) { + getHttpCallback().onAfterResponse(context); + } + + //Error handling using HTTP status codes + int responseCode = response.getStatusCode(); + + if (responseCode == 400) { + throw new ApiException("Bad Request. Ensure that you have set the requestId as a URL path parameter.", context); + } + if (responseCode == 401) { + throw new ApiException("Unauthorized. Ensure that you are using the proper credentials for the environment you are accessing, your user has the proper role assigned to it, and that your Bandwidth account is enabled for TN Lookup access.", context); + } + if (responseCode == 404) { + throw new ApiException("RequestId not found. Ensure that the requestId used in the URL path is valid and maps to a previous request that was submitted.", context); + } + if (responseCode == 429) { + throw new ApiException("Too Many Requests. Reduce the amount of requests that you are sending in order to avoid receiving this status code.", context); + } + if (responseCode == 500) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 501) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 502) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 503) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 504) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 505) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 506) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 507) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 508) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 509) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 510) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 511) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 512) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 513) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 514) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 515) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 516) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 517) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 518) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 519) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 520) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 521) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 522) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 523) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 524) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 525) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 526) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 527) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 528) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 529) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 530) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 531) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 532) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 533) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 534) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 535) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 536) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 537) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 538) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 539) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 540) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 541) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 542) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 543) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 544) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 545) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 546) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 547) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 548) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 549) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 550) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 551) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 552) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 553) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 554) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 555) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 556) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 557) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 558) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 559) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 560) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 561) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 562) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 563) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 564) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 565) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 566) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 567) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 568) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 569) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 570) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 571) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 572) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 573) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 574) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 575) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 576) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 577) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 578) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 579) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 580) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 581) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 582) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 583) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 584) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 585) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 586) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 587) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 588) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 589) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 590) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 591) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 592) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 593) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 594) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 595) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 596) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 597) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 598) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + if (responseCode == 599) { + throw new ApiException("Unexpected error. Please contact Bandwidth Support if your requests are receiving this status code for an extended period of time.", context); + } + //handle errors defined at the API level + validateResponse(response, context); + + //extract result from the http response + String responseBody = ((HttpStringResponse) response).getBody(); + OrderStatus result = ApiHelper.deserialize(responseBody, + OrderStatus.class); + + return new ApiResponse(response.getStatusCode(), response.getHeaders(), result); + } + +} \ No newline at end of file diff --git a/src/main/java/com/bandwidth/phonenumberlookup/exceptions/AccountsTnlookup400ErrorException.java b/src/main/java/com/bandwidth/phonenumberlookup/exceptions/AccountsTnlookup400ErrorException.java new file mode 100644 index 00000000..b80c3967 --- /dev/null +++ b/src/main/java/com/bandwidth/phonenumberlookup/exceptions/AccountsTnlookup400ErrorException.java @@ -0,0 +1,51 @@ +/* + * BandwidthLib + * + * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). + */ + +package com.bandwidth.phonenumberlookup.exceptions; + +import com.bandwidth.exceptions.ApiException; +import com.bandwidth.http.client.HttpContext; +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonSetter; + +/** + * This is a model class for AccountsTnlookup400ErrorException type. + */ +public class AccountsTnlookup400ErrorException + extends ApiException { + private static final long serialVersionUID = -8196860678854372L; + private String message; + + /** + * Initialization constructor. + * @param reason The reason for throwing exception + * @param context The http context of the API exception + */ + public AccountsTnlookup400ErrorException(String reason, HttpContext context) { + super(reason, context); + } + + + /** + * Getter for Message. + * A description of what validation error occurred. + * @return Returns the String + */ + @JsonGetter("message") + public String getMessage() { + return this.message; + } + + /** + * Setter for Message. + * A description of what validation error occurred. + * @param message Value for String + */ + @JsonSetter("message") + private void setMessage(String message) { + this.message = message; + } +} diff --git a/src/main/java/com/bandwidth/phonenumberlookup/models/OrderRequest.java b/src/main/java/com/bandwidth/phonenumberlookup/models/OrderRequest.java new file mode 100644 index 00000000..2996b513 --- /dev/null +++ b/src/main/java/com/bandwidth/phonenumberlookup/models/OrderRequest.java @@ -0,0 +1,100 @@ +/* + * BandwidthLib + * + * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). + */ + +package com.bandwidth.phonenumberlookup.models; + +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonSetter; +import java.util.List; + +/** + * This is a model class for OrderRequest type. + */ +public class OrderRequest { + @JsonInclude(JsonInclude.Include.NON_NULL) + private List tns; + + /** + * Default constructor. + */ + public OrderRequest() { + } + + /** + * Initialization constructor. + * @param tns List of String value for tns. + */ + public OrderRequest( + List tns) { + this.tns = tns; + } + + /** + * Getter for Tns. + * @return Returns the List of String + */ + @JsonGetter("tns") + public List getTns() { + return tns; + } + + /** + * Setter for Tns. + * @param tns Value for List of String + */ + @JsonSetter("tns") + public void setTns(List tns) { + this.tns = tns; + } + + /** + * Converts this OrderRequest into string format. + * @return String representation of this class + */ + @Override + public String toString() { + return "OrderRequest [" + "tns=" + tns + "]"; + } + + /** + * Builds a new {@link OrderRequest.Builder} object. + * Creates the instance with the state of the current model. + * @return a new {@link OrderRequest.Builder} object + */ + public Builder toBuilder() { + Builder builder = new Builder() + .tns(getTns()); + return builder; + } + + /** + * Class to build instances of {@link OrderRequest}. + */ + public static class Builder { + private List tns; + + + + /** + * Setter for tns. + * @param tns List of String value for tns. + * @return Builder + */ + public Builder tns(List tns) { + this.tns = tns; + return this; + } + + /** + * Builds a new {@link OrderRequest} object using the set fields. + * @return {@link OrderRequest} + */ + public OrderRequest build() { + return new OrderRequest(tns); + } + } +} diff --git a/src/main/java/com/bandwidth/phonenumberlookup/models/OrderResponse.java b/src/main/java/com/bandwidth/phonenumberlookup/models/OrderResponse.java new file mode 100644 index 00000000..6ee3f59f --- /dev/null +++ b/src/main/java/com/bandwidth/phonenumberlookup/models/OrderResponse.java @@ -0,0 +1,134 @@ +/* + * BandwidthLib + * + * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). + */ + +package com.bandwidth.phonenumberlookup.models; + +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonSetter; + +/** + * This is a model class for OrderResponse type. + */ +public class OrderResponse { + @JsonInclude(JsonInclude.Include.NON_NULL) + private String requestId; + @JsonInclude(JsonInclude.Include.NON_NULL) + private String status; + + /** + * Default constructor. + */ + public OrderResponse() { + } + + /** + * Initialization constructor. + * @param requestId String value for requestId. + * @param status String value for status. + */ + public OrderResponse( + String requestId, + String status) { + this.requestId = requestId; + this.status = status; + } + + /** + * Getter for RequestId. + * @return Returns the String + */ + @JsonGetter("requestId") + public String getRequestId() { + return requestId; + } + + /** + * Setter for RequestId. + * @param requestId Value for String + */ + @JsonSetter("requestId") + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + /** + * Getter for Status. + * @return Returns the String + */ + @JsonGetter("status") + public String getStatus() { + return status; + } + + /** + * Setter for Status. + * @param status Value for String + */ + @JsonSetter("status") + public void setStatus(String status) { + this.status = status; + } + + /** + * Converts this OrderResponse into string format. + * @return String representation of this class + */ + @Override + public String toString() { + return "OrderResponse [" + "requestId=" + requestId + ", status=" + status + "]"; + } + + /** + * Builds a new {@link OrderResponse.Builder} object. + * Creates the instance with the state of the current model. + * @return a new {@link OrderResponse.Builder} object + */ + public Builder toBuilder() { + Builder builder = new Builder() + .requestId(getRequestId()) + .status(getStatus()); + return builder; + } + + /** + * Class to build instances of {@link OrderResponse}. + */ + public static class Builder { + private String requestId; + private String status; + + + + /** + * Setter for requestId. + * @param requestId String value for requestId. + * @return Builder + */ + public Builder requestId(String requestId) { + this.requestId = requestId; + return this; + } + + /** + * Setter for status. + * @param status String value for status. + * @return Builder + */ + public Builder status(String status) { + this.status = status; + return this; + } + + /** + * Builds a new {@link OrderResponse} object using the set fields. + * @return {@link OrderResponse} + */ + public OrderResponse build() { + return new OrderResponse(requestId, status); + } + } +} diff --git a/src/main/java/com/bandwidth/phonenumberlookup/models/OrderStatus.java b/src/main/java/com/bandwidth/phonenumberlookup/models/OrderStatus.java new file mode 100644 index 00000000..92a48021 --- /dev/null +++ b/src/main/java/com/bandwidth/phonenumberlookup/models/OrderStatus.java @@ -0,0 +1,214 @@ +/* + * BandwidthLib + * + * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). + */ + +package com.bandwidth.phonenumberlookup.models; + +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonSetter; +import java.util.List; + +/** + * This is a model class for OrderStatus type. + */ +public class OrderStatus { + @JsonInclude(JsonInclude.Include.NON_NULL) + private String requestId; + @JsonInclude(JsonInclude.Include.NON_NULL) + private String status; + @JsonInclude(JsonInclude.Include.NON_NULL) + private List failedTelephoneNumbers; + @JsonInclude(JsonInclude.Include.NON_NULL) + private List result; + + /** + * Default constructor. + */ + public OrderStatus() { + } + + /** + * Initialization constructor. + * @param requestId String value for requestId. + * @param status String value for status. + * @param failedTelephoneNumbers List of String value for failedTelephoneNumbers. + * @param result List of Result value for result. + */ + public OrderStatus( + String requestId, + String status, + List failedTelephoneNumbers, + List result) { + this.requestId = requestId; + this.status = status; + this.failedTelephoneNumbers = failedTelephoneNumbers; + this.result = result; + } + + /** + * Getter for RequestId. + * The requestId. + * @return Returns the String + */ + @JsonGetter("requestId") + public String getRequestId() { + return requestId; + } + + /** + * Setter for RequestId. + * The requestId. + * @param requestId Value for String + */ + @JsonSetter("requestId") + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + /** + * Getter for Status. + * The status of the request (IN_PROGRESS, COMPLETE, PARTIAL_COMPLETE, or FAILED). + * @return Returns the String + */ + @JsonGetter("status") + public String getStatus() { + return status; + } + + /** + * Setter for Status. + * The status of the request (IN_PROGRESS, COMPLETE, PARTIAL_COMPLETE, or FAILED). + * @param status Value for String + */ + @JsonSetter("status") + public void setStatus(String status) { + this.status = status; + } + + /** + * Getter for FailedTelephoneNumbers. + * The telephone numbers whose lookup failed + * @return Returns the List of String + */ + @JsonGetter("failedTelephoneNumbers") + public List getFailedTelephoneNumbers() { + return failedTelephoneNumbers; + } + + /** + * Setter for FailedTelephoneNumbers. + * The telephone numbers whose lookup failed + * @param failedTelephoneNumbers Value for List of String + */ + @JsonSetter("failedTelephoneNumbers") + public void setFailedTelephoneNumbers(List failedTelephoneNumbers) { + this.failedTelephoneNumbers = failedTelephoneNumbers; + } + + /** + * Getter for Result. + * The carrier information results for the specified telephone number. + * @return Returns the List of Result + */ + @JsonGetter("result") + public List getResult() { + return result; + } + + /** + * Setter for Result. + * The carrier information results for the specified telephone number. + * @param result Value for List of Result + */ + @JsonSetter("result") + public void setResult(List result) { + this.result = result; + } + + /** + * Converts this OrderStatus into string format. + * @return String representation of this class + */ + @Override + public String toString() { + return "OrderStatus [" + "requestId=" + requestId + ", status=" + status + + ", failedTelephoneNumbers=" + failedTelephoneNumbers + ", result=" + result + "]"; + } + + /** + * Builds a new {@link OrderStatus.Builder} object. + * Creates the instance with the state of the current model. + * @return a new {@link OrderStatus.Builder} object + */ + public Builder toBuilder() { + Builder builder = new Builder() + .requestId(getRequestId()) + .status(getStatus()) + .failedTelephoneNumbers(getFailedTelephoneNumbers()) + .result(getResult()); + return builder; + } + + /** + * Class to build instances of {@link OrderStatus}. + */ + public static class Builder { + private String requestId; + private String status; + private List failedTelephoneNumbers; + private List result; + + + + /** + * Setter for requestId. + * @param requestId String value for requestId. + * @return Builder + */ + public Builder requestId(String requestId) { + this.requestId = requestId; + return this; + } + + /** + * Setter for status. + * @param status String value for status. + * @return Builder + */ + public Builder status(String status) { + this.status = status; + return this; + } + + /** + * Setter for failedTelephoneNumbers. + * @param failedTelephoneNumbers List of String value for failedTelephoneNumbers. + * @return Builder + */ + public Builder failedTelephoneNumbers(List failedTelephoneNumbers) { + this.failedTelephoneNumbers = failedTelephoneNumbers; + return this; + } + + /** + * Setter for result. + * @param result List of Result value for result. + * @return Builder + */ + public Builder result(List result) { + this.result = result; + return this; + } + + /** + * Builds a new {@link OrderStatus} object using the set fields. + * @return {@link OrderStatus} + */ + public OrderStatus build() { + return new OrderStatus(requestId, status, failedTelephoneNumbers, result); + } + } +} diff --git a/src/main/java/com/bandwidth/phonenumberlookup/models/Result.java b/src/main/java/com/bandwidth/phonenumberlookup/models/Result.java new file mode 100644 index 00000000..41317531 --- /dev/null +++ b/src/main/java/com/bandwidth/phonenumberlookup/models/Result.java @@ -0,0 +1,402 @@ +/* + * BandwidthLib + * + * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). + */ + +package com.bandwidth.phonenumberlookup.models; + +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonSetter; + +/** + * This is a model class for Result type. + */ +public class Result { + @JsonInclude(JsonInclude.Include.NON_NULL) + private Integer responseCode; + @JsonInclude(JsonInclude.Include.NON_NULL) + private String message; + @JsonInclude(JsonInclude.Include.NON_NULL) + private String e164Format; + @JsonInclude(JsonInclude.Include.NON_NULL) + private String formatted; + @JsonInclude(JsonInclude.Include.NON_NULL) + private String country; + @JsonInclude(JsonInclude.Include.NON_NULL) + private String lineType; + @JsonInclude(JsonInclude.Include.NON_NULL) + private String lineProvider; + @JsonInclude(JsonInclude.Include.NON_NULL) + private String mobileCountryCode; + @JsonInclude(JsonInclude.Include.NON_NULL) + private String mobileNetworkCode; + + /** + * Default constructor. + */ + public Result() { + } + + /** + * Initialization constructor. + * @param responseCode Integer value for responseCode. + * @param message String value for message. + * @param e164Format String value for e164Format. + * @param formatted String value for formatted. + * @param country String value for country. + * @param lineType String value for lineType. + * @param lineProvider String value for lineProvider. + * @param mobileCountryCode String value for mobileCountryCode. + * @param mobileNetworkCode String value for mobileNetworkCode. + */ + public Result( + Integer responseCode, + String message, + String e164Format, + String formatted, + String country, + String lineType, + String lineProvider, + String mobileCountryCode, + String mobileNetworkCode) { + this.responseCode = responseCode; + this.message = message; + this.e164Format = e164Format; + this.formatted = formatted; + this.country = country; + this.lineType = lineType; + this.lineProvider = lineProvider; + this.mobileCountryCode = mobileCountryCode; + this.mobileNetworkCode = mobileNetworkCode; + } + + /** + * Getter for ResponseCode. + * Our vendor's response code. + * @return Returns the Integer + */ + @JsonGetter("Response Code") + public Integer getResponseCode() { + return responseCode; + } + + /** + * Setter for ResponseCode. + * Our vendor's response code. + * @param responseCode Value for Integer + */ + @JsonSetter("Response Code") + public void setResponseCode(Integer responseCode) { + this.responseCode = responseCode; + } + + /** + * Getter for Message. + * Message associated with the response code. + * @return Returns the String + */ + @JsonGetter("Message") + public String getMessage() { + return message; + } + + /** + * Setter for Message. + * Message associated with the response code. + * @param message Value for String + */ + @JsonSetter("Message") + public void setMessage(String message) { + this.message = message; + } + + /** + * Getter for E164Format. + * The telephone number in E.164 format. + * @return Returns the String + */ + @JsonGetter("E.164 Format") + public String getE164Format() { + return e164Format; + } + + /** + * Setter for E164Format. + * The telephone number in E.164 format. + * @param e164Format Value for String + */ + @JsonSetter("E.164 Format") + public void setE164Format(String e164Format) { + this.e164Format = e164Format; + } + + /** + * Getter for Formatted. + * The formatted version of the telephone number. + * @return Returns the String + */ + @JsonGetter("Formatted") + public String getFormatted() { + return formatted; + } + + /** + * Setter for Formatted. + * The formatted version of the telephone number. + * @param formatted Value for String + */ + @JsonSetter("Formatted") + public void setFormatted(String formatted) { + this.formatted = formatted; + } + + /** + * Getter for Country. + * The country of the telephone number. + * @return Returns the String + */ + @JsonGetter("Country") + public String getCountry() { + return country; + } + + /** + * Setter for Country. + * The country of the telephone number. + * @param country Value for String + */ + @JsonSetter("Country") + public void setCountry(String country) { + this.country = country; + } + + /** + * Getter for LineType. + * The line type of the telephone number. + * @return Returns the String + */ + @JsonGetter("Line Type") + public String getLineType() { + return lineType; + } + + /** + * Setter for LineType. + * The line type of the telephone number. + * @param lineType Value for String + */ + @JsonSetter("Line Type") + public void setLineType(String lineType) { + this.lineType = lineType; + } + + /** + * Getter for LineProvider. + * The service provider of the telephone number. + * @return Returns the String + */ + @JsonGetter("Line Provider") + public String getLineProvider() { + return lineProvider; + } + + /** + * Setter for LineProvider. + * The service provider of the telephone number. + * @param lineProvider Value for String + */ + @JsonSetter("Line Provider") + public void setLineProvider(String lineProvider) { + this.lineProvider = lineProvider; + } + + /** + * Getter for MobileCountryCode. + * The first half of the Home Network Identity (HNI). + * @return Returns the String + */ + @JsonGetter("Mobile Country Code") + public String getMobileCountryCode() { + return mobileCountryCode; + } + + /** + * Setter for MobileCountryCode. + * The first half of the Home Network Identity (HNI). + * @param mobileCountryCode Value for String + */ + @JsonSetter("Mobile Country Code") + public void setMobileCountryCode(String mobileCountryCode) { + this.mobileCountryCode = mobileCountryCode; + } + + /** + * Getter for MobileNetworkCode. + * The second half of the HNI. + * @return Returns the String + */ + @JsonGetter("Mobile Network Code") + public String getMobileNetworkCode() { + return mobileNetworkCode; + } + + /** + * Setter for MobileNetworkCode. + * The second half of the HNI. + * @param mobileNetworkCode Value for String + */ + @JsonSetter("Mobile Network Code") + public void setMobileNetworkCode(String mobileNetworkCode) { + this.mobileNetworkCode = mobileNetworkCode; + } + + /** + * Converts this Result into string format. + * @return String representation of this class + */ + @Override + public String toString() { + return "Result [" + "responseCode=" + responseCode + ", message=" + message + + ", e164Format=" + e164Format + ", formatted=" + formatted + ", country=" + country + + ", lineType=" + lineType + ", lineProvider=" + lineProvider + + ", mobileCountryCode=" + mobileCountryCode + ", mobileNetworkCode=" + + mobileNetworkCode + "]"; + } + + /** + * Builds a new {@link Result.Builder} object. + * Creates the instance with the state of the current model. + * @return a new {@link Result.Builder} object + */ + public Builder toBuilder() { + Builder builder = new Builder() + .responseCode(getResponseCode()) + .message(getMessage()) + .e164Format(getE164Format()) + .formatted(getFormatted()) + .country(getCountry()) + .lineType(getLineType()) + .lineProvider(getLineProvider()) + .mobileCountryCode(getMobileCountryCode()) + .mobileNetworkCode(getMobileNetworkCode()); + return builder; + } + + /** + * Class to build instances of {@link Result}. + */ + public static class Builder { + private Integer responseCode; + private String message; + private String e164Format; + private String formatted; + private String country; + private String lineType; + private String lineProvider; + private String mobileCountryCode; + private String mobileNetworkCode; + + + + /** + * Setter for responseCode. + * @param responseCode Integer value for responseCode. + * @return Builder + */ + public Builder responseCode(Integer responseCode) { + this.responseCode = responseCode; + return this; + } + + /** + * Setter for message. + * @param message String value for message. + * @return Builder + */ + public Builder message(String message) { + this.message = message; + return this; + } + + /** + * Setter for e164Format. + * @param e164Format String value for e164Format. + * @return Builder + */ + public Builder e164Format(String e164Format) { + this.e164Format = e164Format; + return this; + } + + /** + * Setter for formatted. + * @param formatted String value for formatted. + * @return Builder + */ + public Builder formatted(String formatted) { + this.formatted = formatted; + return this; + } + + /** + * Setter for country. + * @param country String value for country. + * @return Builder + */ + public Builder country(String country) { + this.country = country; + return this; + } + + /** + * Setter for lineType. + * @param lineType String value for lineType. + * @return Builder + */ + public Builder lineType(String lineType) { + this.lineType = lineType; + return this; + } + + /** + * Setter for lineProvider. + * @param lineProvider String value for lineProvider. + * @return Builder + */ + public Builder lineProvider(String lineProvider) { + this.lineProvider = lineProvider; + return this; + } + + /** + * Setter for mobileCountryCode. + * @param mobileCountryCode String value for mobileCountryCode. + * @return Builder + */ + public Builder mobileCountryCode(String mobileCountryCode) { + this.mobileCountryCode = mobileCountryCode; + return this; + } + + /** + * Setter for mobileNetworkCode. + * @param mobileNetworkCode String value for mobileNetworkCode. + * @return Builder + */ + public Builder mobileNetworkCode(String mobileNetworkCode) { + this.mobileNetworkCode = mobileNetworkCode; + return this; + } + + /** + * Builds a new {@link Result} object using the set fields. + * @return {@link Result} + */ + public Result build() { + return new Result(responseCode, message, e164Format, formatted, country, lineType, + lineProvider, mobileCountryCode, mobileNetworkCode); + } + } +} diff --git a/src/main/java/com/bandwidth/twofactorauth/controllers/MFAController.java b/src/main/java/com/bandwidth/twofactorauth/controllers/MFAController.java index 2d3ee34b..6cc6f53c 100644 --- a/src/main/java/com/bandwidth/twofactorauth/controllers/MFAController.java +++ b/src/main/java/com/bandwidth/twofactorauth/controllers/MFAController.java @@ -77,7 +77,7 @@ public ApiResponse createVoiceTwoFactor( HttpRequest request = buildCreateVoiceTwoFactorRequest(accountId, body); authManagers.get("twoFactorAuth").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleCreateVoiceTwoFactorResponse(context); @@ -95,7 +95,7 @@ public CompletableFuture> createVoiceTwoFact return makeHttpCallAsync(() -> buildCreateVoiceTwoFactorRequest(accountId, body), req -> authManagers.get("twoFactorAuth").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleCreateVoiceTwoFactorResponse(context)); } @@ -189,7 +189,7 @@ public ApiResponse createMessagingTwoFactor( HttpRequest request = buildCreateMessagingTwoFactorRequest(accountId, body); authManagers.get("twoFactorAuth").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleCreateMessagingTwoFactorResponse(context); @@ -207,7 +207,7 @@ public CompletableFuture> createMessagin return makeHttpCallAsync(() -> buildCreateMessagingTwoFactorRequest(accountId, body), req -> authManagers.get("twoFactorAuth").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleCreateMessagingTwoFactorResponse(context)); } @@ -301,7 +301,7 @@ public ApiResponse createVerifyTwoFactor( HttpRequest request = buildCreateVerifyTwoFactorRequest(accountId, body); authManagers.get("twoFactorAuth").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleCreateVerifyTwoFactorResponse(context); @@ -319,7 +319,7 @@ public CompletableFuture> createVerifyT return makeHttpCallAsync(() -> buildCreateVerifyTwoFactorRequest(accountId, body), req -> authManagers.get("twoFactorAuth").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleCreateVerifyTwoFactorResponse(context)); } @@ -402,4 +402,4 @@ private ApiResponse handleCreateVerifyTwoFactorResp return new ApiResponse(response.getStatusCode(), response.getHeaders(), result); } -} \ No newline at end of file +} diff --git a/src/main/java/com/bandwidth/utilities/FileWrapper.java b/src/main/java/com/bandwidth/utilities/FileWrapper.java index b8064af8..16381b40 100644 --- a/src/main/java/com/bandwidth/utilities/FileWrapper.java +++ b/src/main/java/com/bandwidth/utilities/FileWrapper.java @@ -6,6 +6,7 @@ package com.bandwidth.utilities; +import com.fasterxml.jackson.annotation.JsonInclude; import java.io.File; /** @@ -13,7 +14,9 @@ */ public class FileWrapper { + @JsonInclude(JsonInclude.Include.NON_NULL) private File file; + @JsonInclude(JsonInclude.Include.NON_NULL) private String contentType; /** diff --git a/src/main/java/com/bandwidth/voice/controllers/APIController.java b/src/main/java/com/bandwidth/voice/controllers/APIController.java index acefd94b..46934522 100644 --- a/src/main/java/com/bandwidth/voice/controllers/APIController.java +++ b/src/main/java/com/bandwidth/voice/controllers/APIController.java @@ -84,7 +84,7 @@ public ApiResponse createCall( HttpRequest request = buildCreateCallRequest(accountId, body); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleCreateCallResponse(context); @@ -102,7 +102,7 @@ public CompletableFuture> createCallAsync( return makeHttpCallAsync(() -> buildCreateCallRequest(accountId, body), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleCreateCallResponse(context)); } @@ -205,7 +205,7 @@ public ApiResponse getCallState( HttpRequest request = buildGetCallStateRequest(accountId, callId); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetCallStateResponse(context); @@ -223,7 +223,7 @@ public CompletableFuture> getCallStateAsync( return makeHttpCallAsync(() -> buildGetCallStateRequest(accountId, callId), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetCallStateResponse(context)); } @@ -327,7 +327,7 @@ public ApiResponse modifyCall( HttpRequest request = buildModifyCallRequest(accountId, callId, body); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleModifyCallResponse(context); @@ -347,7 +347,7 @@ public CompletableFuture> modifyCallAsync( return makeHttpCallAsync(() -> buildModifyCallRequest(accountId, callId, body), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleModifyCallResponse(context)); } @@ -448,7 +448,7 @@ public ApiResponse modifyCallRecordingState( HttpRequest request = buildModifyCallRecordingStateRequest(accountId, callId, body); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleModifyCallRecordingStateResponse(context); @@ -469,7 +469,7 @@ public CompletableFuture> modifyCallRecordingStateAsync( body), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleModifyCallRecordingStateResponse(context)); } @@ -570,7 +570,7 @@ public ApiResponse> getQueryMetadataForAccountAn HttpRequest request = buildGetQueryMetadataForAccountAndCallRequest(accountId, callId); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetQueryMetadataForAccountAndCallResponse(context); @@ -590,7 +590,7 @@ public CompletableFuture>> getQueryM callId), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetQueryMetadataForAccountAndCallResponse(context)); } @@ -694,7 +694,7 @@ public ApiResponse getMetadataForRecording( HttpRequest request = buildGetMetadataForRecordingRequest(accountId, callId, recordingId); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetMetadataForRecordingResponse(context); @@ -715,7 +715,7 @@ public CompletableFuture> getMetadataForR recordingId), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetMetadataForRecordingResponse(context)); } @@ -822,7 +822,7 @@ public ApiResponse deleteRecording( HttpRequest request = buildDeleteRecordingRequest(accountId, callId, recordingId); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleDeleteRecordingResponse(context); @@ -842,7 +842,7 @@ public CompletableFuture> deleteRecordingAsync( return makeHttpCallAsync(() -> buildDeleteRecordingRequest(accountId, callId, recordingId), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleDeleteRecordingResponse(context)); } @@ -944,7 +944,7 @@ public ApiResponse getStreamRecordingMedia( HttpRequest request = buildGetStreamRecordingMediaRequest(accountId, callId, recordingId); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsBinary(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetStreamRecordingMediaResponse(context); @@ -965,7 +965,7 @@ public CompletableFuture> getStreamRecordingMediaAsync( recordingId), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetStreamRecordingMediaResponse(context)); } @@ -1068,7 +1068,7 @@ public ApiResponse deleteRecordingMedia( HttpRequest request = buildDeleteRecordingMediaRequest(accountId, callId, recordingId); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleDeleteRecordingMediaResponse(context); @@ -1089,7 +1089,7 @@ public CompletableFuture> deleteRecordingMediaAsync( recordingId), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleDeleteRecordingMediaResponse(context)); } @@ -1191,7 +1191,7 @@ public ApiResponse getRecordingTranscription( HttpRequest request = buildGetRecordingTranscriptionRequest(accountId, callId, recordingId); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetRecordingTranscriptionResponse(context); @@ -1212,7 +1212,7 @@ public CompletableFuture> getRecordingTranscr recordingId), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetRecordingTranscriptionResponse(context)); } @@ -1322,7 +1322,7 @@ public ApiResponse createTranscribeRecording( body); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleCreateTranscribeRecordingResponse(context); @@ -1345,7 +1345,7 @@ public CompletableFuture> createTranscribeRecordingAsync( recordingId, body), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleCreateTranscribeRecordingResponse(context)); } @@ -1453,7 +1453,7 @@ public ApiResponse deleteRecordingTranscription( recordingId); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleDeleteRecordingTranscriptionResponse(context); @@ -1474,7 +1474,7 @@ public CompletableFuture> deleteRecordingTranscriptionAsync( recordingId), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleDeleteRecordingTranscriptionResponse(context)); } @@ -1583,7 +1583,7 @@ public ApiResponse> getConferencesByAccount( name, minCreatedTime, maxCreatedTime); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetConferencesByAccountResponse(context); @@ -1610,7 +1610,7 @@ public CompletableFuture>> getConferencesByAc pageToken, name, minCreatedTime, maxCreatedTime), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetConferencesByAccountResponse(context)); } @@ -1724,7 +1724,7 @@ public ApiResponse getConferenceById( HttpRequest request = buildGetConferenceByIdRequest(accountId, conferenceId); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetConferenceByIdResponse(context); @@ -1742,7 +1742,7 @@ public CompletableFuture> getConferenceByIdAsync( return makeHttpCallAsync(() -> buildGetConferenceByIdRequest(accountId, conferenceId), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetConferenceByIdResponse(context)); } @@ -1846,7 +1846,7 @@ public ApiResponse modifyConference( HttpRequest request = buildModifyConferenceRequest(accountId, conferenceId, body); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleModifyConferenceResponse(context); @@ -1866,7 +1866,7 @@ public CompletableFuture> modifyConferenceAsync( return makeHttpCallAsync(() -> buildModifyConferenceRequest(accountId, conferenceId, body), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleModifyConferenceResponse(context)); } @@ -1970,7 +1970,7 @@ public ApiResponse modifyConferenceMember( body); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleModifyConferenceMemberResponse(context); @@ -1993,7 +1993,7 @@ public CompletableFuture> modifyConferenceMemberAsync( callId, body), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleModifyConferenceMemberResponse(context)); } @@ -2098,7 +2098,7 @@ public ApiResponse getConferenceMember( HttpRequest request = buildGetConferenceMemberRequest(accountId, conferenceId, memberId); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetConferenceMemberResponse(context); @@ -2119,7 +2119,7 @@ public CompletableFuture> getConferenceMembe memberId), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetConferenceMemberResponse(context)); } @@ -2227,7 +2227,7 @@ public ApiResponse> getQueryMetadataFo conferenceId); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetQueryMetadataForAccountAndConferenceResponse(context); @@ -2247,7 +2247,7 @@ public CompletableFuture>> accountId, conferenceId), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetQueryMetadataForAccountAndConferenceResponse(context)); } @@ -2352,7 +2352,7 @@ public ApiResponse getMetadataForConferenceRecording( recordingId); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetMetadataForConferenceRecordingResponse(context); @@ -2373,7 +2373,7 @@ public CompletableFuture> getMetadataForC conferenceId, recordingId), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetMetadataForConferenceRecordingResponse(context)); } @@ -2482,7 +2482,7 @@ public ApiResponse getStreamConferenceRecordingMedia( recordingId); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsBinary(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetStreamConferenceRecordingMediaResponse(context); @@ -2503,7 +2503,7 @@ public CompletableFuture> getStreamConferenceRecordingM conferenceId, recordingId), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetStreamConferenceRecordingMediaResponse(context)); } @@ -2614,7 +2614,7 @@ public ApiResponse> getQueryMetadataForAccount( minStartTime, maxStartTime); authManagers.get("voice").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetQueryMetadataForAccountResponse(context); @@ -2641,7 +2641,7 @@ public CompletableFuture>> getQueryM minStartTime, maxStartTime), req -> authManagers.get("voice").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetQueryMetadataForAccountResponse(context)); } @@ -2738,4 +2738,4 @@ private ApiResponse> handleGetQueryMetadataForAc return new ApiResponse>(response.getStatusCode(), response.getHeaders(), result); } -} \ No newline at end of file +} diff --git a/src/main/java/com/bandwidth/webrtc/controllers/APIController.java b/src/main/java/com/bandwidth/webrtc/controllers/APIController.java index 78225783..30ec66e0 100644 --- a/src/main/java/com/bandwidth/webrtc/controllers/APIController.java +++ b/src/main/java/com/bandwidth/webrtc/controllers/APIController.java @@ -76,7 +76,7 @@ public ApiResponse createParticipant( HttpRequest request = buildCreateParticipantRequest(accountId, body); authManagers.get("webRtc").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleCreateParticipantResponse(context); @@ -95,7 +95,7 @@ public CompletableFuture> createPartic return makeHttpCallAsync(() -> buildCreateParticipantRequest(accountId, body), req -> authManagers.get("webRtc").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleCreateParticipantResponse(context)); } @@ -189,7 +189,7 @@ public ApiResponse getParticipant( HttpRequest request = buildGetParticipantRequest(accountId, participantId); authManagers.get("webRtc").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetParticipantResponse(context); @@ -207,7 +207,7 @@ public CompletableFuture> getParticipantAsync( return makeHttpCallAsync(() -> buildGetParticipantRequest(accountId, participantId), req -> authManagers.get("webRtc").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetParticipantResponse(context)); } @@ -300,7 +300,7 @@ public ApiResponse deleteParticipant( HttpRequest request = buildDeleteParticipantRequest(accountId, participantId); authManagers.get("webRtc").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleDeleteParticipantResponse(context); @@ -318,7 +318,7 @@ public CompletableFuture> deleteParticipantAsync( return makeHttpCallAsync(() -> buildDeleteParticipantRequest(accountId, participantId), req -> authManagers.get("webRtc").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleDeleteParticipantResponse(context)); } @@ -407,7 +407,7 @@ public ApiResponse createSession( HttpRequest request = buildCreateSessionRequest(accountId, body); authManagers.get("webRtc").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleCreateSessionResponse(context); @@ -426,7 +426,7 @@ public CompletableFuture> createSessionAsync( return makeHttpCallAsync(() -> buildCreateSessionRequest(accountId, body), req -> authManagers.get("webRtc").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleCreateSessionResponse(context)); } @@ -520,7 +520,7 @@ public ApiResponse getSession( HttpRequest request = buildGetSessionRequest(accountId, sessionId); authManagers.get("webRtc").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetSessionResponse(context); @@ -538,7 +538,7 @@ public CompletableFuture> getSessionAsync( return makeHttpCallAsync(() -> buildGetSessionRequest(accountId, sessionId), req -> authManagers.get("webRtc").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetSessionResponse(context)); } @@ -631,7 +631,7 @@ public ApiResponse deleteSession( HttpRequest request = buildDeleteSessionRequest(accountId, sessionId); authManagers.get("webRtc").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleDeleteSessionResponse(context); @@ -649,7 +649,7 @@ public CompletableFuture> deleteSessionAsync( return makeHttpCallAsync(() -> buildDeleteSessionRequest(accountId, sessionId), req -> authManagers.get("webRtc").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleDeleteSessionResponse(context)); } @@ -737,7 +737,7 @@ public ApiResponse> listSessionParticipants( HttpRequest request = buildListSessionParticipantsRequest(accountId, sessionId); authManagers.get("webRtc").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleListSessionParticipantsResponse(context); @@ -755,7 +755,7 @@ public CompletableFuture>> listSessionParticipants return makeHttpCallAsync(() -> buildListSessionParticipantsRequest(accountId, sessionId), req -> authManagers.get("webRtc").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleListSessionParticipantsResponse(context)); } @@ -852,7 +852,7 @@ public ApiResponse addParticipantToSession( participantId, body); authManagers.get("webRtc").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleAddParticipantToSessionResponse(context); @@ -875,7 +875,7 @@ public CompletableFuture> addParticipantToSessionAsync( participantId, body), req -> authManagers.get("webRtc").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleAddParticipantToSessionResponse(context)); } @@ -972,7 +972,7 @@ public ApiResponse removeParticipantFromSession( sessionId); authManagers.get("webRtc").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleRemoveParticipantFromSessionResponse(context); @@ -994,7 +994,7 @@ public CompletableFuture> removeParticipantFromSessionAsync( participantId, sessionId), req -> authManagers.get("webRtc").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleRemoveParticipantFromSessionResponse(context)); } @@ -1088,7 +1088,7 @@ public ApiResponse getParticipantSubscriptions( sessionId); authManagers.get("webRtc").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleGetParticipantSubscriptionsResponse(context); @@ -1109,7 +1109,7 @@ public CompletableFuture> getParticipantSubscriptions participantId, sessionId), req -> authManagers.get("webRtc").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleGetParticipantSubscriptionsResponse(context)); } @@ -1212,7 +1212,7 @@ public ApiResponse updateParticipantSubscriptions( sessionId, body); authManagers.get("webRtc").apply(request); - HttpResponse response = getClientInstance().executeAsString(request); + HttpResponse response = getClientInstance().execute(request, false); HttpContext context = new HttpContext(request, response); return handleUpdateParticipantSubscriptionsResponse(context); @@ -1237,7 +1237,7 @@ public CompletableFuture> updateParticipantSubscriptionsAsync( participantId, sessionId, body), req -> authManagers.get("webRtc").applyAsync(req) .thenCompose(request -> getClientInstance() - .executeAsStringAsync(request)), + .executeAsync(request, false)), context -> handleUpdateParticipantSubscriptionsResponse(context)); } diff --git a/src/main/java/com/bandwidth/webrtc/exceptions/ErrorException.java b/src/main/java/com/bandwidth/webrtc/exceptions/ErrorException.java index b8d8c9ed..907bb088 100644 --- a/src/main/java/com/bandwidth/webrtc/exceptions/ErrorException.java +++ b/src/main/java/com/bandwidth/webrtc/exceptions/ErrorException.java @@ -32,7 +32,7 @@ public ErrorException(String reason, HttpContext context) { /** * Getter for Code. - * @return Returns the int + * @return Returns the int */ @JsonGetter("code") public int getCode() { @@ -41,16 +41,16 @@ public int getCode() { /** * Setter for Code. - * @param value Value for int + * @param code Value for int */ @JsonSetter("code") - private void setCode(int value) { - this.code = value; + private void setCode(int code) { + this.code = code; } /** * Getter for Message. - * @return Returns the String + * @return Returns the String */ @JsonGetter("message") public String getMessage() { @@ -59,10 +59,10 @@ public String getMessage() { /** * Setter for Message. - * @param value Value for String + * @param message Value for String */ @JsonSetter("message") - private void setMessage(String value) { - this.message = value; + private void setMessage(String message) { + this.message = message; } } diff --git a/src/main/java/com/bandwidth/webrtc/models/AccountsParticipantsResponse.java b/src/main/java/com/bandwidth/webrtc/models/AccountsParticipantsResponse.java index 947145b9..bd33e2ca 100644 --- a/src/main/java/com/bandwidth/webrtc/models/AccountsParticipantsResponse.java +++ b/src/main/java/com/bandwidth/webrtc/models/AccountsParticipantsResponse.java @@ -7,13 +7,16 @@ package com.bandwidth.webrtc.models; import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; /** * This is a model class for AccountsParticipantsResponse type. */ public class AccountsParticipantsResponse { + @JsonInclude(JsonInclude.Include.NON_NULL) private Participant participant; + @JsonInclude(JsonInclude.Include.NON_NULL) private String token; /** @@ -24,8 +27,8 @@ public AccountsParticipantsResponse() { /** * Initialization constructor. - * @param participant Participant value for participant. - * @param token String value for token. + * @param participant Participant value for participant. + * @param token String value for token. */ public AccountsParticipantsResponse( Participant participant, @@ -41,7 +44,7 @@ public AccountsParticipantsResponse( */ @JsonGetter("participant") public Participant getParticipant() { - return this.participant; + return participant; } /** @@ -62,7 +65,7 @@ public void setParticipant(Participant participant) { */ @JsonGetter("token") public String getToken() { - return this.token; + return token; } /** @@ -109,7 +112,7 @@ public static class Builder { /** * Setter for participant. - * @param participant Participant value for participant. + * @param participant Participant value for participant. * @return Builder */ public Builder participant(Participant participant) { @@ -119,7 +122,7 @@ public Builder participant(Participant participant) { /** * Setter for token. - * @param token String value for token. + * @param token String value for token. * @return Builder */ public Builder token(String token) { diff --git a/src/main/java/com/bandwidth/webrtc/models/DeviceApiVersionEnum.java b/src/main/java/com/bandwidth/webrtc/models/DeviceApiVersionEnum.java index 70e86738..f6d65e3a 100644 --- a/src/main/java/com/bandwidth/webrtc/models/DeviceApiVersionEnum.java +++ b/src/main/java/com/bandwidth/webrtc/models/DeviceApiVersionEnum.java @@ -23,11 +23,11 @@ public enum DeviceApiVersionEnum { private String value; static { - V3.value = "v3"; - V2.value = "v2"; + V3.value = "V3"; + V2.value = "V2"; - valueMap.put("v3", V3); - valueMap.put("v2", V2); + valueMap.put("V3", V3); + valueMap.put("V2", V2); } /** diff --git a/src/main/java/com/bandwidth/webrtc/models/Participant.java b/src/main/java/com/bandwidth/webrtc/models/Participant.java index 429cfaac..160992bd 100644 --- a/src/main/java/com/bandwidth/webrtc/models/Participant.java +++ b/src/main/java/com/bandwidth/webrtc/models/Participant.java @@ -6,37 +6,48 @@ package com.bandwidth.webrtc.models; +import com.bandwidth.internal.OptionalNullable; import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.util.List; /** * This is a model class for Participant type. */ public class Participant { + @JsonInclude(JsonInclude.Include.NON_NULL) private String id; - private String callbackUrl; + @JsonInclude(JsonInclude.Include.NON_NULL) + private OptionalNullable callbackUrl; + @JsonInclude(JsonInclude.Include.NON_NULL) private List publishPermissions; + @JsonInclude(JsonInclude.Include.NON_NULL) private List sessions; + @JsonInclude(JsonInclude.Include.NON_NULL) private Subscriptions subscriptions; + @JsonInclude(JsonInclude.Include.NON_NULL) private String tag; + @JsonInclude(JsonInclude.Include.NON_NULL) private DeviceApiVersionEnum deviceApiVersion; /** * Default constructor. */ public Participant() { + deviceApiVersion = DeviceApiVersionEnum.V2; } /** * Initialization constructor. - * @param id String value for id. - * @param callbackUrl String value for callbackUrl. - * @param publishPermissions List of PublishPermissionEnum value for publishPermissions. - * @param sessions List of String value for sessions. - * @param subscriptions Subscriptions value for subscriptions. - * @param tag String value for tag. - * @param deviceApiVersion DeviceApiVersionEnum value for deviceApiVersion. + * @param id String value for id. + * @param callbackUrl String value for callbackUrl. + * @param publishPermissions List of PublishPermissionEnum value for publishPermissions. + * @param sessions List of String value for sessions. + * @param subscriptions Subscriptions value for subscriptions. + * @param tag String value for tag. + * @param deviceApiVersion DeviceApiVersionEnum value for deviceApiVersion. */ public Participant( String id, @@ -47,6 +58,21 @@ public Participant( String tag, DeviceApiVersionEnum deviceApiVersion) { this.id = id; + this.callbackUrl = OptionalNullable.of(callbackUrl); + this.publishPermissions = publishPermissions; + this.sessions = sessions; + this.subscriptions = subscriptions; + this.tag = tag; + this.deviceApiVersion = deviceApiVersion; + } + + /** + * Internal initialization constructor. + */ + protected Participant(String id, OptionalNullable callbackUrl, + List publishPermissions, List sessions, + Subscriptions subscriptions, String tag, DeviceApiVersionEnum deviceApiVersion) { + this.id = id; this.callbackUrl = callbackUrl; this.publishPermissions = publishPermissions; this.sessions = sessions; @@ -62,7 +88,7 @@ public Participant( */ @JsonGetter("id") public String getId() { - return this.id; + return id; } /** @@ -75,14 +101,24 @@ public void setId(String id) { this.id = id; } + /** + * Internal Getter for CallbackUrl. + * Full callback url to use for notifications about this participant + * @return Returns the Internal String + */ + @JsonGetter("callbackUrl") + @JsonSerialize(using = OptionalNullable.Serializer.class) + protected OptionalNullable internalGetCallbackUrl() { + return this.callbackUrl; + } + /** * Getter for CallbackUrl. * Full callback url to use for notifications about this participant * @return Returns the String */ - @JsonGetter("callbackUrl") public String getCallbackUrl() { - return this.callbackUrl; + return OptionalNullable.getFrom(callbackUrl); } /** @@ -92,7 +128,15 @@ public String getCallbackUrl() { */ @JsonSetter("callbackUrl") public void setCallbackUrl(String callbackUrl) { - this.callbackUrl = callbackUrl; + this.callbackUrl = OptionalNullable.of(callbackUrl); + } + + /** + * UnSetter for CallbackUrl. + * Full callback url to use for notifications about this participant + */ + public void unsetCallbackUrl() { + callbackUrl = null; } /** @@ -102,7 +146,7 @@ public void setCallbackUrl(String callbackUrl) { */ @JsonGetter("publishPermissions") public List getPublishPermissions() { - return this.publishPermissions; + return publishPermissions; } /** @@ -122,7 +166,7 @@ public void setPublishPermissions(List publishPermissions */ @JsonGetter("sessions") public List getSessions() { - return this.sessions; + return sessions; } /** @@ -141,7 +185,7 @@ public void setSessions(List sessions) { */ @JsonGetter("subscriptions") public Subscriptions getSubscriptions() { - return this.subscriptions; + return subscriptions; } /** @@ -160,7 +204,7 @@ public void setSubscriptions(Subscriptions subscriptions) { */ @JsonGetter("tag") public String getTag() { - return this.tag; + return tag; } /** @@ -180,7 +224,7 @@ public void setTag(String tag) { */ @JsonGetter("deviceApiVersion") public DeviceApiVersionEnum getDeviceApiVersion() { - return this.deviceApiVersion; + return deviceApiVersion; } /** @@ -213,12 +257,12 @@ public String toString() { public Builder toBuilder() { Builder builder = new Builder() .id(getId()) - .callbackUrl(getCallbackUrl()) .publishPermissions(getPublishPermissions()) .sessions(getSessions()) .subscriptions(getSubscriptions()) .tag(getTag()) .deviceApiVersion(getDeviceApiVersion()); + builder.callbackUrl = internalGetCallbackUrl(); return builder; } @@ -227,7 +271,7 @@ public Builder toBuilder() { */ public static class Builder { private String id; - private String callbackUrl; + private OptionalNullable callbackUrl; private List publishPermissions; private List sessions; private Subscriptions subscriptions; @@ -238,7 +282,7 @@ public static class Builder { /** * Setter for id. - * @param id String value for id. + * @param id String value for id. * @return Builder */ public Builder id(String id) { @@ -248,17 +292,26 @@ public Builder id(String id) { /** * Setter for callbackUrl. - * @param callbackUrl String value for callbackUrl. + * @param callbackUrl String value for callbackUrl. * @return Builder */ public Builder callbackUrl(String callbackUrl) { - this.callbackUrl = callbackUrl; + this.callbackUrl = OptionalNullable.of(callbackUrl); + return this; + } + + /** + * UnSetter for callbackUrl. + * @return Builder + */ + public Builder unsetCallbackUrl() { + callbackUrl = null; return this; } /** * Setter for publishPermissions. - * @param publishPermissions List of PublishPermissionEnum value for publishPermissions. + * @param publishPermissions List of PublishPermissionEnum value for publishPermissions. * @return Builder */ public Builder publishPermissions(List publishPermissions) { @@ -268,7 +321,7 @@ public Builder publishPermissions(List publishPermissions /** * Setter for sessions. - * @param sessions List of String value for sessions. + * @param sessions List of String value for sessions. * @return Builder */ public Builder sessions(List sessions) { @@ -278,7 +331,7 @@ public Builder sessions(List sessions) { /** * Setter for subscriptions. - * @param subscriptions Subscriptions value for subscriptions. + * @param subscriptions Subscriptions value for subscriptions. * @return Builder */ public Builder subscriptions(Subscriptions subscriptions) { @@ -288,7 +341,7 @@ public Builder subscriptions(Subscriptions subscriptions) { /** * Setter for tag. - * @param tag String value for tag. + * @param tag String value for tag. * @return Builder */ public Builder tag(String tag) { @@ -298,7 +351,7 @@ public Builder tag(String tag) { /** * Setter for deviceApiVersion. - * @param deviceApiVersion DeviceApiVersionEnum value for deviceApiVersion. + * @param deviceApiVersion DeviceApiVersionEnum value for deviceApiVersion. * @return Builder */ public Builder deviceApiVersion(DeviceApiVersionEnum deviceApiVersion) { diff --git a/src/main/java/com/bandwidth/webrtc/models/ParticipantSubscription.java b/src/main/java/com/bandwidth/webrtc/models/ParticipantSubscription.java index b6a055b9..92beb637 100644 --- a/src/main/java/com/bandwidth/webrtc/models/ParticipantSubscription.java +++ b/src/main/java/com/bandwidth/webrtc/models/ParticipantSubscription.java @@ -23,7 +23,7 @@ public ParticipantSubscription() { /** * Initialization constructor. - * @param participantId String value for participantId. + * @param participantId String value for participantId. */ public ParticipantSubscription( String participantId) { @@ -37,7 +37,7 @@ public ParticipantSubscription( */ @JsonGetter("participantId") public String getParticipantId() { - return this.participantId; + return participantId; } /** @@ -83,7 +83,7 @@ public Builder() { /** * Initialization constructor. - * @param participantId String value for participantId. + * @param participantId String value for participantId. */ public Builder(String participantId) { this.participantId = participantId; @@ -91,7 +91,7 @@ public Builder(String participantId) { /** * Setter for participantId. - * @param participantId String value for participantId. + * @param participantId String value for participantId. * @return Builder */ public Builder participantId(String participantId) { diff --git a/src/main/java/com/bandwidth/webrtc/models/Session.java b/src/main/java/com/bandwidth/webrtc/models/Session.java index b054b078..fd8d5c6d 100644 --- a/src/main/java/com/bandwidth/webrtc/models/Session.java +++ b/src/main/java/com/bandwidth/webrtc/models/Session.java @@ -7,13 +7,16 @@ package com.bandwidth.webrtc.models; import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; /** * This is a model class for Session type. */ public class Session { + @JsonInclude(JsonInclude.Include.NON_NULL) private String id; + @JsonInclude(JsonInclude.Include.NON_NULL) private String tag; /** @@ -24,8 +27,8 @@ public Session() { /** * Initialization constructor. - * @param id String value for id. - * @param tag String value for tag. + * @param id String value for id. + * @param tag String value for tag. */ public Session( String id, @@ -41,7 +44,7 @@ public Session( */ @JsonGetter("id") public String getId() { - return this.id; + return id; } /** @@ -61,7 +64,7 @@ public void setId(String id) { */ @JsonGetter("tag") public String getTag() { - return this.tag; + return tag; } /** @@ -106,7 +109,7 @@ public static class Builder { /** * Setter for id. - * @param id String value for id. + * @param id String value for id. * @return Builder */ public Builder id(String id) { @@ -116,7 +119,7 @@ public Builder id(String id) { /** * Setter for tag. - * @param tag String value for tag. + * @param tag String value for tag. * @return Builder */ public Builder tag(String tag) { diff --git a/src/main/java/com/bandwidth/webrtc/models/Subscriptions.java b/src/main/java/com/bandwidth/webrtc/models/Subscriptions.java index 420774fe..62493636 100644 --- a/src/main/java/com/bandwidth/webrtc/models/Subscriptions.java +++ b/src/main/java/com/bandwidth/webrtc/models/Subscriptions.java @@ -7,6 +7,7 @@ package com.bandwidth.webrtc.models; import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import java.util.List; @@ -15,6 +16,7 @@ */ public class Subscriptions { private String sessionId; + @JsonInclude(JsonInclude.Include.NON_NULL) private List participants; /** @@ -25,8 +27,8 @@ public Subscriptions() { /** * Initialization constructor. - * @param sessionId String value for sessionId. - * @param participants List of ParticipantSubscription value for participants. + * @param sessionId String value for sessionId. + * @param participants List of ParticipantSubscription value for participants. */ public Subscriptions( String sessionId, @@ -44,7 +46,7 @@ public Subscriptions( */ @JsonGetter("sessionId") public String getSessionId() { - return this.sessionId; + return sessionId; } /** @@ -66,7 +68,7 @@ public void setSessionId(String sessionId) { */ @JsonGetter("participants") public List getParticipants() { - return this.participants; + return participants; } /** @@ -115,7 +117,7 @@ public Builder() { /** * Initialization constructor. - * @param sessionId String value for sessionId. + * @param sessionId String value for sessionId. */ public Builder(String sessionId) { this.sessionId = sessionId; @@ -123,7 +125,7 @@ public Builder(String sessionId) { /** * Setter for sessionId. - * @param sessionId String value for sessionId. + * @param sessionId String value for sessionId. * @return Builder */ public Builder sessionId(String sessionId) { @@ -133,7 +135,7 @@ public Builder sessionId(String sessionId) { /** * Setter for participants. - * @param participants List of ParticipantSubscription value for participants. + * @param participants List of ParticipantSubscription value for participants. * @return Builder */ public Builder participants(List participants) { diff --git a/src/test/java/com/bandwidth/ApiTest.java b/src/test/java/com/bandwidth/ApiTest.java index fc31d679..3eb1a733 100644 --- a/src/test/java/com/bandwidth/ApiTest.java +++ b/src/test/java/com/bandwidth/ApiTest.java @@ -29,6 +29,8 @@ import com.bandwidth.exceptions.ApiException; import com.bandwidth.http.response.ApiResponse; import com.bandwidth.utilities.FileWrapper; +import com.bandwidth.phonenumberlookup.models.*; +import com.bandwidth.phonenumberlookup.controllers.*; /** * Integration tests for API interactions @@ -40,6 +42,7 @@ public class ApiTest { private com.bandwidth.voice.controllers.APIController voiceController; private com.bandwidth.twofactorauth.controllers.MFAController mfaController; private com.bandwidth.webrtc.controllers.APIController webrtcController; + private com.bandwidth.phonenumberlookup.controllers.APIController phoneNumberLookupController; @Before public void init() { @@ -48,11 +51,13 @@ public void init() { .voiceBasicAuthCredentials(System.getenv("BW_USERNAME"), System.getenv("BW_PASSWORD")) .twoFactorAuthBasicAuthCredentials(System.getenv("BW_USERNAME"), System.getenv("BW_PASSWORD")) .webRtcBasicAuthCredentials(System.getenv("BW_USERNAME"), System.getenv("BW_PASSWORD")) + .phoneNumberLookupBasicAuthCredentials(System.getenv("BW_USERNAME"), System.getenv("BW_PASSWORD")) .build(); this.messagingController = client.getMessagingClient().getAPIController(); this.voiceController = client.getVoiceClient().getAPIController(); this.mfaController = client.getTwoFactorAuthClient().getMFAController(); this.webrtcController = client.getWebRtcClient().getAPIController(); + this.phoneNumberLookupController = client.getPhoneNumberLookupClient().getAPIController(); } @Test @@ -309,6 +314,26 @@ public void testWebRtcParticipantSessionManagement() throws Exception { webrtcController.addParticipantToSession(accountId, sessionId, participantId, null); } + @Test + public void testPhoneNumberLookup() throws Exception { + String accountId = System.getenv("BW_ACCOUNT_ID"); + String checkNumber = System.getenv("PHONE_NUMBER_INBOUND"); + ArrayList checkNumbers = new ArrayList(); + checkNumbers.add(checkNumber); + + OrderRequest body = new OrderRequest(); + body.setTns(checkNumbers); + ApiResponse orderResponse = phoneNumberLookupController.createLookupRequest(accountId, body); + String requestId = orderResponse.getResult().getRequestId(); + + assertTrue("requestId not defined properly", requestId.length() > 0); + + ApiResponse orderStatusResponse = phoneNumberLookupController.getLookupRequestStatus(accountId, requestId); + String status = orderStatusResponse.getResult().getStatus(); + + assertTrue("status not defined properly", status.length() > 0); + } + /* * Taken from https://mkyong.com/java/how-to-convert-inputstream-to-string-in-java/ */