From dcba61325c6814254b5407864745b95b620cec49 Mon Sep 17 00:00:00 2001 From: sbansla Date: Fri, 12 Apr 2024 15:57:14 +0530 Subject: [PATCH 1/3] noauth and bearertoken rest client --- pom.xml | 11 + src/main/java/com/twilio/Domains.java | 1 + .../com/twilio/TwilioBearerTokenAuth.java | 84 ++++ src/main/java/com/twilio/TwilioNoAuth.java | 48 +++ .../java/com/twilio/annotations/Beta.java | 9 + .../java/com/twilio/annotations/Preview.java | 12 + .../com/twilio/base/bearertoken/Creator.java | 50 +++ .../com/twilio/base/bearertoken/Deleter.java | 51 +++ .../com/twilio/base/bearertoken/Fetcher.java | 50 +++ .../com/twilio/base/bearertoken/Page.java | 265 +++++++++++++ .../com/twilio/base/bearertoken/Reader.java | 156 ++++++++ .../com/twilio/base/bearertoken/Resource.java | 9 + .../twilio/base/bearertoken/ResourceSet.java | 130 +++++++ .../com/twilio/base/bearertoken/Updater.java | 50 +++ .../java/com/twilio/base/noauth/Creator.java | 52 +++ src/main/java/com/twilio/http/HttpClient.java | 9 +- .../java/com/twilio/http/HttpUtility.java | 2 +- src/main/java/com/twilio/http/IRequest.java | 360 ++++++++++++++++++ .../com/twilio/http/NetworkHttpClient.java | 35 +- src/main/java/com/twilio/http/Request.java | 311 +-------------- .../com/twilio/http/ValidationClient.java | 8 +- .../twilio/http/ValidationInterceptor.java | 3 +- .../http/bearertoken/BearerTokenRequest.java | 38 ++ .../BearerTokenTwilioRestClient.java | 168 ++++++++ .../twilio/http/noauth/NoAuthHttpClient.java | 134 +++++++ .../com/twilio/http/noauth/NoAuthRequest.java | 19 + .../http/noauth/NoAuthTwilioRestClient.java | 137 +++++++ 27 files changed, 1873 insertions(+), 329 deletions(-) create mode 100644 src/main/java/com/twilio/TwilioBearerTokenAuth.java create mode 100644 src/main/java/com/twilio/TwilioNoAuth.java create mode 100644 src/main/java/com/twilio/annotations/Beta.java create mode 100644 src/main/java/com/twilio/annotations/Preview.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Creator.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Deleter.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Fetcher.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Page.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Reader.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Resource.java create mode 100644 src/main/java/com/twilio/base/bearertoken/ResourceSet.java create mode 100644 src/main/java/com/twilio/base/bearertoken/Updater.java create mode 100644 src/main/java/com/twilio/base/noauth/Creator.java create mode 100644 src/main/java/com/twilio/http/IRequest.java create mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java create mode 100644 src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java create mode 100644 src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java create mode 100644 src/main/java/com/twilio/http/noauth/NoAuthRequest.java create mode 100644 src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java diff --git a/pom.xml b/pom.xml index 7aac5b4175..5305e62eb6 100644 --- a/pom.xml +++ b/pom.xml @@ -315,6 +315,17 @@ 1.10.19 test + + com.auth0 + java-jwt + 4.4.0 + + + com.fasterxml.jackson.core + jackson-databind + + + diff --git a/src/main/java/com/twilio/Domains.java b/src/main/java/com/twilio/Domains.java index 4e36890f53..ec729352ce 100644 --- a/src/main/java/com/twilio/Domains.java +++ b/src/main/java/com/twilio/Domains.java @@ -32,6 +32,7 @@ public enum Domains { NUMBERS("numbers"), OAUTH("oauth"), PREVIEW("preview"), + PREVIEWIAM("preview-iam"), PRICING("pricing"), PROXY("proxy"), ROUTES("routes"), diff --git a/src/main/java/com/twilio/TwilioBearerTokenAuth.java b/src/main/java/com/twilio/TwilioBearerTokenAuth.java new file mode 100644 index 0000000000..90b7588cc6 --- /dev/null +++ b/src/main/java/com/twilio/TwilioBearerTokenAuth.java @@ -0,0 +1,84 @@ +package com.twilio; + +import com.twilio.annotations.Preview; +import com.twilio.exception.AuthenticationException; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import lombok.Getter; + +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +@Preview +public class TwilioBearerTokenAuth { + private static String accessToken; + @Getter + private static List userAgentExtensions; + private static String region = System.getenv("TWILIO_REGION"); + private static String edge = System.getenv("TWILIO_EDGE"); + private static volatile BearerTokenTwilioRestClient restClient; + + private static volatile ExecutorService executorService; + + private TwilioBearerTokenAuth() { + } + + public static synchronized void init(final String accessToken) { + if (accessToken == null || accessToken.isEmpty()) { + throw new AuthenticationException("Access Token can not be null or Empty"); + } + if (!accessToken.equals(TwilioBearerTokenAuth.accessToken)) { + TwilioBearerTokenAuth.invalidate(); + } + TwilioBearerTokenAuth.accessToken = accessToken; + } + + public static BearerTokenTwilioRestClient getRestClient() { + if (TwilioBearerTokenAuth.restClient == null) { + synchronized (TwilioBearerTokenAuth.class) { + if (TwilioBearerTokenAuth.restClient == null) { + TwilioBearerTokenAuth.restClient = buildOAuthRestClient(); + } + } + } + return TwilioBearerTokenAuth.restClient; + } + /** + * Returns the Twilio executor service. + * + * @return the Twilio executor service + */ + public static ExecutorService getExecutorService() { + if (TwilioBearerTokenAuth.executorService == null) { + synchronized (TwilioBearerTokenAuth.class) { + if (TwilioBearerTokenAuth.executorService == null) { + TwilioBearerTokenAuth.executorService = Executors.newCachedThreadPool(); + } + } + } + return TwilioBearerTokenAuth.executorService; + } + + private static BearerTokenTwilioRestClient buildOAuthRestClient() { + + BearerTokenTwilioRestClient.Builder builder = new BearerTokenTwilioRestClient.Builder(accessToken); + + if (userAgentExtensions != null) { + builder.userAgentExtensions(TwilioBearerTokenAuth.userAgentExtensions); + } + + builder.region(TwilioBearerTokenAuth.region); + builder.edge(TwilioBearerTokenAuth.edge); + + return builder.build(); + } + + /** + * Invalidates the volatile state held in the Twilio singleton. + */ + private static void invalidate() { + TwilioBearerTokenAuth.restClient = null; + } + + +} \ No newline at end of file diff --git a/src/main/java/com/twilio/TwilioNoAuth.java b/src/main/java/com/twilio/TwilioNoAuth.java new file mode 100644 index 0000000000..b4a646c8c8 --- /dev/null +++ b/src/main/java/com/twilio/TwilioNoAuth.java @@ -0,0 +1,48 @@ +package com.twilio; + +import com.twilio.annotations.Preview; +import com.twilio.http.noauth.NoAuthTwilioRestClient; +import lombok.Getter; + +import java.util.List; +import com.twilio.exception.AuthenticationException; + +@Preview +public class TwilioNoAuth { + @Getter + private static List userAgentExtensions; + private static String region = System.getenv("TWILIO_REGION"); + private static String edge = System.getenv("TWILIO_EDGE"); + + private static volatile NoAuthTwilioRestClient noAuthTwilioRestClient; + + private TwilioNoAuth() { + } + + public static NoAuthTwilioRestClient getRestClient() { + if (TwilioNoAuth.noAuthTwilioRestClient == null) { + synchronized (TwilioNoAuth.class) { + if (TwilioNoAuth.noAuthTwilioRestClient == null) { + TwilioNoAuth.noAuthTwilioRestClient = buildOAuthRestClient(); + } + } + } + return TwilioNoAuth.noAuthTwilioRestClient; + } + + private static NoAuthTwilioRestClient buildOAuthRestClient() { + + NoAuthTwilioRestClient.Builder builder = new NoAuthTwilioRestClient.Builder(); + + if (userAgentExtensions != null) { + builder.userAgentExtensions(TwilioNoAuth.userAgentExtensions); + } + + builder.region(TwilioNoAuth.region); + builder.edge(TwilioNoAuth.edge); + + return builder.build(); + } + + +} diff --git a/src/main/java/com/twilio/annotations/Beta.java b/src/main/java/com/twilio/annotations/Beta.java new file mode 100644 index 0000000000..f80596f57c --- /dev/null +++ b/src/main/java/com/twilio/annotations/Beta.java @@ -0,0 +1,9 @@ +package com.twilio.annotations; + +import java.lang.annotation.*; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface Beta { + String value() default "This class/method is under beta and is subjected to change. Use with caution."; +} \ No newline at end of file diff --git a/src/main/java/com/twilio/annotations/Preview.java b/src/main/java/com/twilio/annotations/Preview.java new file mode 100644 index 0000000000..67d0e512a6 --- /dev/null +++ b/src/main/java/com/twilio/annotations/Preview.java @@ -0,0 +1,12 @@ +package com.twilio.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface Preview { + String value() default "This class/method is under preview and is subjected to change. Use with caution."; +} \ No newline at end of file diff --git a/src/main/java/com/twilio/base/bearertoken/Creator.java b/src/main/java/com/twilio/base/bearertoken/Creator.java new file mode 100644 index 0000000000..b221459edd --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Creator.java @@ -0,0 +1,50 @@ +package com.twilio.base.bearertoken; + +import com.twilio.TwilioBearerTokenAuth; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; + +import java.util.concurrent.CompletableFuture; + +/** + * Executor for creation of a resource. + * + * @param type of the resource + */ +public abstract class Creator { + + /** + * Execute an async request using default client. + * + * @return future that resolves to requested object + */ + public CompletableFuture createAsync() { + return createAsync(TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Execute an async request using specified client. + * + * @param client client used to make request + * @return future that resolves to requested object + */ + public CompletableFuture createAsync(final BearerTokenTwilioRestClient client) { + return CompletableFuture.supplyAsync(() -> create(client), TwilioBearerTokenAuth.getExecutorService()); + } + + /** + * Execute a request using default client. + * + * @return Requested object + */ + public T create() { + return create(TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Execute a request using specified client. + * + * @param client client used to make request + * @return Requested object + */ + public abstract T create(final BearerTokenTwilioRestClient client); +} diff --git a/src/main/java/com/twilio/base/bearertoken/Deleter.java b/src/main/java/com/twilio/base/bearertoken/Deleter.java new file mode 100644 index 0000000000..44d738159f --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Deleter.java @@ -0,0 +1,51 @@ +package com.twilio.base.bearertoken; + +import com.twilio.Twilio; +import com.twilio.TwilioBearerTokenAuth; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; + +import java.util.concurrent.CompletableFuture; + +/** + * Executor for deletes of a resource. + * + * @param type of the resource + */ +public abstract class Deleter { + + /** + * Execute an async request using default client. + * + * @return future that resolves to true if the object was deleted + */ + public CompletableFuture deleteAsync() { + return deleteAsync(TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Execute an async request using specified client. + * + * @param client client used to make request + * @return future that resolves to true if the object was deleted + */ + public CompletableFuture deleteAsync(final BearerTokenTwilioRestClient client) { + return CompletableFuture.supplyAsync(() -> delete(client), Twilio.getExecutorService()); + } + + /** + * Execute a request using default client. + * + * @return true if the object was deleted + */ + public boolean delete() { + return delete(TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Execute a request using specified client. + * + * @param client client used to make request + * @return true if the object was deleted + */ + public abstract boolean delete(final BearerTokenTwilioRestClient client); +} diff --git a/src/main/java/com/twilio/base/bearertoken/Fetcher.java b/src/main/java/com/twilio/base/bearertoken/Fetcher.java new file mode 100644 index 0000000000..f5e00dbcc6 --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Fetcher.java @@ -0,0 +1,50 @@ +package com.twilio.base.bearertoken; + +import com.twilio.TwilioBearerTokenAuth; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; + +import java.util.concurrent.CompletableFuture; + +/** + * Executor for fetches of a resource. + * + * @param type of the resource + */ +public abstract class Fetcher { + + /** + * Execute an async request using default client. + * + * @return future that resolves to requested object + */ + public CompletableFuture fetchAsync() { + return fetchAsync(TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Execute an async request using specified client. + * + * @param client client used to make request + * @return future that resolves to requested object + */ + public CompletableFuture fetchAsync(final BearerTokenTwilioRestClient client) { + return CompletableFuture.supplyAsync(() -> fetch(client), TwilioBearerTokenAuth.getExecutorService()); + } + + /** + * Execute a request using default client. + * + * @return Requested object + */ + public T fetch() { + return fetch(TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Execute a request using specified client. + * + * @param client client used to make request + * @return Requested object + */ + public abstract T fetch(final BearerTokenTwilioRestClient client); +} diff --git a/src/main/java/com/twilio/base/bearertoken/Page.java b/src/main/java/com/twilio/base/bearertoken/Page.java new file mode 100644 index 0000000000..9c31231ef1 --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Page.java @@ -0,0 +1,265 @@ +package com.twilio.base.bearertoken; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.exception.ApiConnectionException; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class Page { + private final List records; + private final String firstPageUrl; + private final String firstPageUri; + private final String nextPageUrl; + private final String nextPageUri; + private final String previousPageUrl; + private final String previousPageUri; + private final String url; + private final String uri; + private final int pageSize; + + private Page(Builder b) { + this.records = b.records; + this.firstPageUri = b.firstPageUri; + this.firstPageUrl = b.firstPageUrl; + this.nextPageUri = b.nextPageUri; + this.nextPageUrl = b.nextPageUrl; + this.previousPageUri = b.previousPageUri; + this.previousPageUrl = b.previousPageUrl; + this.uri = b.uri; + this.url = b.url; + this.pageSize = b.pageSize; + } + + private String urlFromUri(String domain, String uri) { + return "https://" + domain + ".twilio.com" + uri; + } + + public List getRecords() { + return records; + } + + /** + * Generate first page url for a list result. + * + * @param domain domain to use + * @return the first page url + */ + public String getFirstPageUrl(String domain) { + if (firstPageUrl != null) { + return firstPageUrl; + } + + return urlFromUri(domain, firstPageUri); + } + + /** + * Generate next page url for a list result. + * + * @param domain domain to use + * @return the next page url + */ + public String getNextPageUrl(String domain) { + if (nextPageUrl != null) { + return nextPageUrl; + } + + return urlFromUri(domain, nextPageUri); + } + + /** + * Generate previous page url for a list result. + * + * @param domain domain to use + * @return the previous page url + */ + public String getPreviousPageUrl(String domain) { + if (previousPageUrl != null) { + return previousPageUrl; + } + + return urlFromUri(domain, previousPageUri); + } + + public int getPageSize() { + return pageSize; + } + + /** + * Generate page url for a list result. + * + * @param domain domain to use + * @return the page url + */ + public String getUrl(String domain) { + if (url != null) { + return url; + } + + return urlFromUri(domain, uri); + } + + public boolean hasNextPage() { + return (nextPageUri != null && !nextPageUri.isEmpty()) || (nextPageUrl != null && !nextPageUrl.isEmpty()); + } + + /** + * Create a new page of data from a json blob. + * + * @param recordKey key which holds the records + * @param json json blob + * @param recordType resource type + * @param mapper json parser + * @param record class type + * @return a page of records of type T + */ + public static Page fromJson(String recordKey, String json, Class recordType, ObjectMapper mapper) { + try { + List results = new ArrayList<>(); + JsonNode root = mapper.readTree(json); + JsonNode records = root.get(recordKey); + for (final JsonNode record : records) { + results.add(mapper.readValue(record.toString(), recordType)); + } + + JsonNode uriNode = root.get("uri"); + if (uriNode != null) { + return buildPage(root, results); + } else { + return buildNextGenPage(root, results); + } + + } catch (final IOException e) { + throw new ApiConnectionException( + "Unable to deserialize response: " + e.getMessage() + "\nJSON: " + json, e + ); + } + } + + private static Page buildPage(JsonNode root, List results) { + Builder builder = new Builder() + .uri(root.get("uri").asText()); + + JsonNode nextPageNode = root.get("next_page_uri"); + if (nextPageNode != null && !nextPageNode.isNull()) { + builder.nextPageUri(nextPageNode.asText()); + } + + JsonNode previousPageNode = root.get("previous_page_uri"); + if (previousPageNode != null && !previousPageNode.isNull()) { + builder.previousPageUri(previousPageNode.asText()); + } + + JsonNode firstPageNode = root.get("first_page_uri"); + if (firstPageNode != null && !firstPageNode.isNull()) { + builder.firstPageUri(firstPageNode.asText()); + } + + JsonNode pageSizeNode = root.get("page_size"); + if (pageSizeNode != null && !pageSizeNode.isNull()) { + builder.pageSize(pageSizeNode.asInt()); + } else { + builder.pageSize(results.size()); + } + + return builder.records(results).build(); + } + + private static Page buildNextGenPage(JsonNode root, List results) { + JsonNode meta = root.get("meta"); + Builder builder = new Builder().url(meta.get("url").asText()); + + JsonNode nextPageNode = meta.get("next_page_url"); + if (!nextPageNode.isNull()) { + builder.nextPageUrl(nextPageNode.asText()); + } + + JsonNode previousPageNode = meta.get("previous_page_url"); + if (!previousPageNode.isNull()) { + builder.previousPageUrl(previousPageNode.asText()); + } + + JsonNode firstPageNode = meta.get("first_page_url"); + if (!firstPageNode.isNull()) { + builder.firstPageUrl(firstPageNode.asText()); + } + + JsonNode pageSizeNode = meta.get("page_size"); + if (!pageSizeNode.isNull()) { + builder.pageSize(pageSizeNode.asInt()); + } else { + builder.pageSize(results.size()); + } + + return builder.records(results).build(); + } + + private static class Builder { + private List records; + private String firstPageUrl; + private String firstPageUri; + private String nextPageUrl; + private String nextPageUri; + private String previousPageUrl; + private String previousPageUri; + private String uri; + private String url; + private int pageSize; + + public Builder records(List records) { + this.records = records; + return this; + } + + public Builder firstPageUri(String firstPageUri) { + this.firstPageUri = firstPageUri; + return this; + } + + public Builder firstPageUrl(String firstPageUrl) { + this.firstPageUrl = firstPageUrl; + return this; + } + + public Builder nextPageUri(String nextPageUri) { + this.nextPageUri = nextPageUri; + return this; + } + + public Builder nextPageUrl(String nextPageUrl) { + this.nextPageUrl = nextPageUrl; + return this; + } + + public Builder previousPageUri(String previousPageUri) { + this.previousPageUri = previousPageUri; + return this; + } + + public Builder previousPageUrl(String previousPageUrl) { + this.previousPageUrl = previousPageUrl; + return this; + } + + public Builder uri(String uri) { + this.uri = uri; + return this; + } + + public Builder url(String url) { + this.url = url; + return this; + } + + public Builder pageSize(int pageSize) { + this.pageSize = pageSize; + return this; + } + + public Page build() { + return new Page<>(this); + } + } +} diff --git a/src/main/java/com/twilio/base/bearertoken/Reader.java b/src/main/java/com/twilio/base/bearertoken/Reader.java new file mode 100644 index 0000000000..db73736616 --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Reader.java @@ -0,0 +1,156 @@ +package com.twilio.base.bearertoken; + +import com.twilio.TwilioBearerTokenAuth; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; + +import java.util.concurrent.CompletableFuture; + +/** + * Executor for listing of a resource. + * + * @param type of the resource + */ +public abstract class Reader { + + private Integer pageSize; + private Long limit; + + /** + * Execute a request using default client. + * + * @return ResourceSet of objects + */ + public ResourceSet read() { + return read(TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Execute a request using specified client. + * + * @param client client used to make request + * @return ResourceSet of objects + */ + public abstract ResourceSet read(final BearerTokenTwilioRestClient client); + + /** + * Execute an async request using default client. + * + * @return future that resolves to the ResourceSet of objects + */ + public CompletableFuture> readAsync() { + return readAsync(TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Execute an async request using specified client. + * + * @param client client used to make request + * @return future that resolves to the ResourceSet of objects + */ + public CompletableFuture> readAsync(final BearerTokenTwilioRestClient client) { + return CompletableFuture.supplyAsync(() -> read(client), TwilioBearerTokenAuth.getExecutorService()); + } + + /** + * Fetch the first page of resources. + * + * @return Page containing the first pageSize of resources + */ + public Page firstPage() { + return firstPage(TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Fetch the first page of resources using specified client. + * + * @param client client used to fetch + * @return Page containing the first pageSize of resources + */ + public abstract Page firstPage(final BearerTokenTwilioRestClient client); + + /** + * Retrieve the target page of resources. + * + * @param targetUrl API-generated URL for the requested results page + * @return Page containing the target pageSize of resources + */ + public Page getPage(final String targetUrl) { + return getPage(targetUrl, TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Retrieve the target page of resources. + * + * @param targetUrl API-generated URL for the requested results page + * @param client client used to fetch + * @return Page containing the target pageSize of resources + */ + public abstract Page getPage(final String targetUrl, final BearerTokenTwilioRestClient client); + + /** + * Fetch the following page of resources. + * + * @param page current page of resources + * @return Page containing the next pageSize of resources + */ + public Page nextPage(final Page page) { + return nextPage(page, TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Fetch the following page of resources using specified client. + * + * @param page current page of resources + * @param client client used to fetch + * @return Page containing the next pageSize of resources + */ + public abstract Page nextPage(final Page page, final BearerTokenTwilioRestClient client); + + /** + * Fetch the prior page of resources. + * + * @param page current page of resources + * @return Page containing the previous pageSize of resources + */ + public Page previousPage(final Page page) { + return previousPage(page, TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Fetch the prior page of resources using specified client. + * + * @param page current page of resources + * @param client client used to fetch + * @return Page containing the previous pageSize of resources + */ + public abstract Page previousPage(final Page page, final BearerTokenTwilioRestClient client); + + public Integer getPageSize() { + return pageSize; + } + + public Reader pageSize(final int pageSize) { + this.pageSize = pageSize; + return this; + } + + public Long getLimit() { + return limit; + } + + /** + * Sets the max number of records to read. + * + * @param limit max number of records to read + * @return this reader + */ + public Reader limit(final long limit) { + this.limit = limit; + + if (this.pageSize == null) { + this.pageSize = this.limit.intValue(); + } + + return this; + } +} diff --git a/src/main/java/com/twilio/base/bearertoken/Resource.java b/src/main/java/com/twilio/base/bearertoken/Resource.java new file mode 100644 index 0000000000..08dc228556 --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Resource.java @@ -0,0 +1,9 @@ +package com.twilio.base.bearertoken; + +import java.io.Serializable; + +public abstract class Resource implements Serializable { + + private static final long serialVersionUID = -5898012691404059591L; + +} diff --git a/src/main/java/com/twilio/base/bearertoken/ResourceSet.java b/src/main/java/com/twilio/base/bearertoken/ResourceSet.java new file mode 100644 index 0000000000..16bc369084 --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/ResourceSet.java @@ -0,0 +1,130 @@ +package com.twilio.base.bearertoken; + +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * A collection of resources. + * + * @param type of the resource + */ +public class ResourceSet implements Iterable { + + private final Reader reader; + private final BearerTokenTwilioRestClient client; + + private boolean autoPaging; + private long pages = 1; + private long pageLimit = Long.MAX_VALUE; + private long processed = 0; + private Page page; + private Iterator iterator; + + /** + * Initialize the resource set. + * + * @param reader reader used to fetch next page + * @param client client used to make requests + * @param page page of data + */ + public ResourceSet(final Reader reader, final BearerTokenTwilioRestClient client, final Page page) { + this.reader = reader; + this.client = client; + this.page = page; + this.iterator = page.getRecords().iterator(); + this.autoPaging = true; + + if (reader.getLimit() != null) { + this.pageLimit = (long)(Math.ceil((double)reader.getLimit() / (double)page.getPageSize())); + } + } + + public boolean isAutoPaging() { + return autoPaging; + } + + public ResourceSet setAutoPaging(final boolean autoPaging) { + this.autoPaging = autoPaging; + return this; + } + + public Integer getPageSize() { + return page.getPageSize(); + } + + public ResourceSet setPageSize(final int pageSize) { + reader.pageSize(pageSize); + return this; + } + + public Long getLimit() { + return reader.getLimit(); + } + + public ResourceSet setLimit(final long limit) { + reader.limit(limit); + return this; + } + + public long getPageLimit() { + return pageLimit; + } + + @Override + public Iterator iterator() { + return new ResourceSetIterator<>(this); + } + + private void fetchNextPage() { + if (!page.hasNextPage() || pages >= pageLimit) { + return; + } + + pages++; + page = reader.nextPage(page, client); + iterator = page.getRecords().iterator(); + } + + private class ResourceSetIterator implements Iterator { + private final ResourceSet resourceSet; + + public ResourceSetIterator(final ResourceSet resourceSet) { + this.resourceSet = resourceSet; + } + + @Override + public boolean hasNext() { + if (resourceSet.getLimit() != null && resourceSet.processed >= resourceSet.getLimit()) { + return false; + } + + return resourceSet.iterator.hasNext(); + } + + @Override + public E next() { + if (resourceSet == null || resourceSet.iterator == null) { + throw new NoSuchElementException(); + } + + E element = resourceSet.iterator.next(); + if (resourceSet.isAutoPaging() && !resourceSet.iterator.hasNext()) { + resourceSet.fetchNextPage(); + } + + resourceSet.processed++; + return element; + } + + @Override + public void remove() { + if (resourceSet.iterator != null) { + resourceSet.processed++; + resourceSet.iterator.remove(); + } + } + + } +} diff --git a/src/main/java/com/twilio/base/bearertoken/Updater.java b/src/main/java/com/twilio/base/bearertoken/Updater.java new file mode 100644 index 0000000000..f41ae300ad --- /dev/null +++ b/src/main/java/com/twilio/base/bearertoken/Updater.java @@ -0,0 +1,50 @@ +package com.twilio.base.bearertoken; + +import com.twilio.TwilioBearerTokenAuth; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; + +import java.util.concurrent.CompletableFuture; + +/** + * Executor for updates of a resource. + * + * @param type of the resource + */ +public abstract class Updater { + + /** + * Execute an async request using default client. + * + * @return future that resolves to requested object + */ + public CompletableFuture updateAsync() { + return updateAsync(TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Execute an async request using specified client. + * + * @param client client used to make request + * @return future that resolves to requested object + */ + public CompletableFuture updateAsync(final BearerTokenTwilioRestClient client) { + return CompletableFuture.supplyAsync(() -> update(client), TwilioBearerTokenAuth.getExecutorService()); + } + + /** + * Execute a request using default client. + * + * @return Requested object + */ + public T update() { + return update(TwilioBearerTokenAuth.getRestClient()); + } + + /** + * Execute a request using specified client. + * + * @param client client used to make request + * @return Requested object + */ + public abstract T update(final BearerTokenTwilioRestClient client); +} diff --git a/src/main/java/com/twilio/base/noauth/Creator.java b/src/main/java/com/twilio/base/noauth/Creator.java new file mode 100644 index 0000000000..6f74c8371c --- /dev/null +++ b/src/main/java/com/twilio/base/noauth/Creator.java @@ -0,0 +1,52 @@ +package com.twilio.base.noauth; + +import com.twilio.Twilio; +import com.twilio.TwilioNoAuth; +import com.twilio.base.Resource; +import com.twilio.http.noauth.NoAuthTwilioRestClient; + +import java.util.concurrent.CompletableFuture; + +/** + * Executor for creation of a resource. + * + * @param type of the resource + */ +public abstract class Creator { + + /** + * Execute an async request using default client. + * + * @return future that resolves to requested object + */ + public CompletableFuture createAsync() { + return createAsync(TwilioNoAuth.getRestClient()); + } + + /** + * Execute an async request using specified client. + * + * @param client client used to make request + * @return future that resolves to requested object + */ + public CompletableFuture createAsync(final NoAuthTwilioRestClient client) { + return CompletableFuture.supplyAsync(() -> create(client), Twilio.getExecutorService()); + } + + /** + * Execute a request using default client. + * + * @return Requested object + */ + public T create() { + return create(TwilioNoAuth.getRestClient()); + } + + /** + * Execute a request using specified client. + * + * @param client client used to make request + * @return Requested object + */ + public abstract T create(final NoAuthTwilioRestClient client); +} diff --git a/src/main/java/com/twilio/http/HttpClient.java b/src/main/java/com/twilio/http/HttpClient.java index 71e595ff34..46938dfad2 100644 --- a/src/main/java/com/twilio/http/HttpClient.java +++ b/src/main/java/com/twilio/http/HttpClient.java @@ -39,7 +39,7 @@ public abstract class HttpClient { @Getter private Response lastResponse; @Getter - private Request lastRequest; + private IRequest lastRequest; /** * Make a request. @@ -47,7 +47,7 @@ public abstract class HttpClient { * @param request request to make * @return Response of the HTTP request */ - public Response reliableRequest(final Request request) { + public Response reliableRequest(final IRequest request) { return reliableRequest(request, RETRY_CODES, RETRIES, DELAY_MILLIS); } @@ -60,7 +60,7 @@ public Response reliableRequest(final Request request) { * @param delayMillis delays between retries * @return Response of the HTTP request */ - public Response reliableRequest(final Request request, final int[] retryCodes, int retries, + public Response reliableRequest(final IRequest request, final int[] retryCodes, int retries, final long delayMillis) { lastRequest = request; Response response = null; @@ -131,5 +131,6 @@ protected boolean shouldRetry(final Response response, final int[] retryCodes) { return false; } - public abstract Response makeRequest(final Request request); + public abstract Response makeRequest(final T request); + } diff --git a/src/main/java/com/twilio/http/HttpUtility.java b/src/main/java/com/twilio/http/HttpUtility.java index d31117c24b..4e54bc55b0 100644 --- a/src/main/java/com/twilio/http/HttpUtility.java +++ b/src/main/java/com/twilio/http/HttpUtility.java @@ -6,7 +6,7 @@ import java.util.List; @UtilityClass -class HttpUtility { +public class HttpUtility { public String getUserAgentString(final List userAgentExtensions) { StringBuilder userAgentString = new StringBuilder(); userAgentString.append("twilio-java/") diff --git a/src/main/java/com/twilio/http/IRequest.java b/src/main/java/com/twilio/http/IRequest.java new file mode 100644 index 0000000000..584951f34b --- /dev/null +++ b/src/main/java/com/twilio/http/IRequest.java @@ -0,0 +1,360 @@ +package com.twilio.http; + +import com.twilio.constant.EnumConstants; +import com.twilio.exception.ApiException; +import com.twilio.exception.InvalidRequestException; + +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLEncoder; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +public class IRequest { + private static final String DEFAULT_REGION = "us1"; + + public static final String QUERY_STRING_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; + public static final String QUERY_STRING_DATE_FORMAT = "yyyy-MM-dd"; + + protected final HttpMethod method; + protected final String url; + protected final Map> queryParams; + protected final Map> postParams; + protected final Map> headerParams; + + protected String region; + protected String edge; + + private List userAgentExtensions; + + private EnumConstants.ContentType contentType; + + private String body; + + /** + * Create a new API request. + * + * @param method HTTP method + * @param url url of request + */ + public IRequest(final HttpMethod method, final String url) { + this.method = method; + this.url = url; + this.queryParams = new HashMap<>(); + this.postParams = new HashMap<>(); + this.headerParams = new HashMap<>(); + } + + /** + * Create a new API request. + * + * @param method HTTP method + * @param domain Twilio domain + * @param uri uri of request + */ + public IRequest(final HttpMethod method, final String domain, final String uri) { + this(method, domain, uri, null); + } + + /** + * Create a new API request. + * + * @param method HTTP Method + * @param domain Twilio domain + * @param uri uri of request + * @param region region to make request + */ + public IRequest(final HttpMethod method, final String domain, final String uri, final String region + ) { + this.method = method; + this.url = "https://" + domain + ".twilio.com" + uri; + this.region = region; + this.queryParams = new HashMap<>(); + this.postParams = new HashMap<>(); + this.headerParams = new HashMap<>(); + } + + public HttpMethod getMethod() { + return method; + } + + public String getUrl() { + return url; + } + + public void setRegion(final String region) { + this.region = region; + } + + public void setEdge(final String edge) { + this.edge = edge; + } + + public void setUserAgentExtensions(List userAgentExtensions) { + this.userAgentExtensions = userAgentExtensions; + } + + public List getUserAgentExtensions() { + return this.userAgentExtensions; + } + + public EnumConstants.ContentType getContentType() { + return contentType; + } + + public void setContentType(EnumConstants.ContentType contentType) { + this.contentType = contentType; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + /** + * Build the URL for the request. + * + * @return URL for the request + */ + public URL constructURL() { + String params = encodeQueryParams(); + String stringUri = buildURL(); + + if (params.length() > 0) { + stringUri += "?" + params; + } + + try { + URI uri = new URI(stringUri); + return uri.toURL(); + } catch (final URISyntaxException e) { + throw new ApiException("Bad URI: " + e.getMessage()); + } catch (final MalformedURLException e) { + throw new ApiException("Bad URL: " + e.getMessage()); + } + } + + protected String buildURL() { + try { + final URL parsedUrl = new URL(url); + String host = parsedUrl.getHost(); + final String[] pieces = host.split("\\."); + + if (pieces.length > 1) { + final String product = pieces[0]; + final String domain = joinIgnoreNull(".", pieces[pieces.length - 2], pieces[pieces.length - 1]); + + String targetRegion = region; + String targetEdge = edge; + + if (pieces.length == 4) { // product.region.twilio.com + targetRegion = targetRegion != null ? targetRegion : pieces[1]; + } else if (pieces.length == 5) { // product.edge.region.twilio.com + targetEdge = targetEdge != null ? targetEdge : pieces[1]; + targetRegion = targetRegion != null ? targetRegion : pieces[2]; + } + + if (targetEdge != null && targetRegion == null) + targetRegion = DEFAULT_REGION; + + host = joinIgnoreNull(".", product, targetEdge, targetRegion, domain); + } + + String urlPort = parsedUrl.getPort() != -1 ? ":" + parsedUrl.getPort() : null; + String protocol = parsedUrl.getProtocol() + "://"; + String[] pathPieces = parsedUrl.getPath().split("/"); + for (int i = 0; i < pathPieces.length; i++) { + pathPieces[i] = URLEncoder.encode(pathPieces[i], "UTF-8"); + } + String encodedPath = String.join("/", pathPieces); + String query = parsedUrl.getQuery() != null ? "?" + parsedUrl.getQuery() : null; + String ref = parsedUrl.getRef() != null ? "#" + parsedUrl.getRef() : null; + String credentials = parsedUrl.getUserInfo() != null ? parsedUrl.getUserInfo() + "@" : null; + return joinIgnoreNull("", protocol, credentials, host, urlPort, encodedPath, query, ref); + } catch (final MalformedURLException | UnsupportedEncodingException e) { + throw new ApiException("Bad URL: " + e.getMessage()); + } + } + + /** + * Add query parameters for date ranges. + * + * @param name name of query parameter + * @param lowerBound lower bound of LocalDate range + * @param upperBound upper bound of LocalDate range + */ + public void addQueryDateRange(final String name, LocalDate lowerBound, LocalDate upperBound) { + if (lowerBound != null) { + String value = lowerBound.toString(); + addQueryParam(name + ">", value); + } + + if (upperBound != null) { + String value = upperBound.toString(); + addQueryParam(name + "<", value); + } + } + + /** + * Add query parameters for date ranges. + * + * @param name name of query parameter + * @param lowerBound lower bound of ZonedDateTime range + * @param upperBound upper bound of ZonedDateTime range + */ + public void addQueryDateTimeRange(final String name, ZonedDateTime lowerBound, ZonedDateTime upperBound) { + if (lowerBound != null) { + String value = lowerBound.withZoneSameInstant(ZoneId.of("UTC")).format(DateTimeFormatter.ofPattern(QUERY_STRING_DATE_TIME_FORMAT)); + addQueryParam(name + ">", value); + } + + if (upperBound != null) { + String value = upperBound.withZoneSameInstant(ZoneId.of("UTC")).format(DateTimeFormatter.ofPattern(QUERY_STRING_DATE_TIME_FORMAT)); + addQueryParam(name + "<", value); + } + } + + /** + * Add a query parameter. + * + * @param name name of parameter + * @param value value of parameter + */ + public void addQueryParam(final String name, final String value) { + addParam(queryParams, name, value); + } + + /** + * Add a form parameter. + * + * @param name name of parameter + * @param value value of parameter + */ + public void addPostParam(final String name, final String value) { + addParam(postParams, name, value); + } + + /** + * Add a header parameter. + * + * @param name name of parameter + * @param value value of parameter + */ + public void addHeaderParam(final String name, final String value) { + addParam(headerParams, name, value); + } + + private void addParam(final Map> params, final String name, final String value) { + if (value == null || value.equals("null")) + return; + + if (!params.containsKey(name)) { + params.put(name, new ArrayList()); + } + + params.get(name).add(value); + } + + /** + * Encode the form body. + * + * @return url encoded form body + */ + public String encodeFormBody() { + return encodeParameters(postParams); + } + + /** + * Encode the query parameters. + * + * @return url encoded query parameters + */ + public String encodeQueryParams() { + return encodeParameters(queryParams); + } + + private static String encodeParameters(final Map> params) { + List parameters = new ArrayList<>(); + + for (final Map.Entry> entry : params.entrySet()) { + try { + String encodedName = URLEncoder.encode(entry.getKey(), "UTF-8"); + for (final String value : entry.getValue()) { + if (value == null) { + continue; + } + + String encodedValue = URLEncoder.encode(value, "UTF-8"); + parameters.add(encodedName + "=" + encodedValue); + } + } catch (final UnsupportedEncodingException e) { + throw new InvalidRequestException("Couldn't encode params", entry.getKey(), e); + } + } + return joinIgnoreNull("&", parameters); + } + + private static String joinIgnoreNull(final String separator, final String... items) { + return joinIgnoreNull(separator, Arrays.asList(items)); + } + + private static String joinIgnoreNull(final String separator, final List items) { + final StringBuilder builder = new StringBuilder(); + + for (final String item : items) { + if (item != null) { + if (builder.length() > 0) { + builder.append(separator); + } + + builder.append(item); + } + } + + return builder.toString(); + } + + public Map> getQueryParams() { + return queryParams; + } + + public Map> getPostParams() { + return postParams; + } + + public Map> getHeaderParams() { + return headerParams; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + Request other = (Request) o; + return Objects.equals(this.method, other.method) && + Objects.equals(this.buildURL(), other.buildURL()) && + Objects.equals(this.queryParams, other.queryParams) && + Objects.equals(this.postParams, other.postParams) && + Objects.equals(this.headerParams, other.headerParams); + } +} diff --git a/src/main/java/com/twilio/http/NetworkHttpClient.java b/src/main/java/com/twilio/http/NetworkHttpClient.java index efa058cb4c..36fb5420d1 100644 --- a/src/main/java/com/twilio/http/NetworkHttpClient.java +++ b/src/main/java/com/twilio/http/NetworkHttpClient.java @@ -3,14 +3,7 @@ import com.twilio.Twilio; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiException; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; - +import com.twilio.http.bearertoken.BearerTokenRequest; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; @@ -26,6 +19,13 @@ import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicHeader; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; + public class NetworkHttpClient extends HttpClient { protected final org.apache.http.client.HttpClient client; @@ -57,7 +57,8 @@ public NetworkHttpClient(final RequestConfig requestConfig) { public NetworkHttpClient(final RequestConfig requestConfig, final SocketConfig socketConfig) { Collection headers = Arrays.asList( new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), - new BasicHeader(HttpHeaders.ACCEPT, "application/json"), + // new BasicHeader(HttpHeaders.ACCEPT, "application/json"), + //new BasicHeader(HttpHeaders.ACCEPT, "application/scim+json"), new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") ); @@ -113,16 +114,24 @@ public NetworkHttpClient(HttpClientBuilder clientBuilder) { * @param request request to make * @return Response of the HTTP request */ - public Response makeRequest(final Request request) { + public Response makeRequest(final T request) { HttpMethod method = request.getMethod(); RequestBuilder builder = RequestBuilder.create(method.toString()) .setUri(request.constructURL().toString()) .setVersion(HttpVersion.HTTP_1_1) .setCharset(StandardCharsets.UTF_8); - - if (request.requiresAuthentication()) { - builder.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString()); + if (request instanceof Request) { + Request basicRequest = (Request) request; + // builder.setHeader(HttpHeaders.AUTHORIZATION, basicRequest.getAuthString(accessToken)); + if (basicRequest.requiresAuthentication()) { + builder.addHeader(HttpHeaders.AUTHORIZATION, basicRequest.getAuthString()); + } + } else if (request instanceof BearerTokenRequest) { + BearerTokenRequest bearerTokenRequest = (BearerTokenRequest) request; + if (bearerTokenRequest.requiresAuthentication()) { + builder.addHeader(HttpHeaders.AUTHORIZATION, bearerTokenRequest.getAuthString()); + } } for (Map.Entry> entry : request.getHeaderParams().entrySet()) { diff --git a/src/main/java/com/twilio/http/Request.java b/src/main/java/com/twilio/http/Request.java index 36aa7a5e03..7c24765ee1 100644 --- a/src/main/java/com/twilio/http/Request.java +++ b/src/main/java/com/twilio/http/Request.java @@ -1,47 +1,17 @@ package com.twilio.http; -import com.twilio.constant.EnumConstants; - -import com.twilio.exception.ApiException; -import com.twilio.exception.InvalidRequestException; - -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLEncoder; import java.nio.charset.StandardCharsets; -import java.time.LocalDate; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; - -public class Request { +import java.util.Base64; +import java.util.Objects; +public class Request extends IRequest { private static final String DEFAULT_REGION = "us1"; public static final String QUERY_STRING_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; public static final String QUERY_STRING_DATE_FORMAT = "yyyy-MM-dd"; - - private final HttpMethod method; - private final String url; - private final Map> queryParams; - private final Map> postParams; - private final Map> headerParams; - - private String region; - private String edge; private String username; private String password; - private List userAgentExtensions; - - private EnumConstants.ContentType contentType; - - private String body; - /** * Create a new API request. * @@ -49,11 +19,7 @@ public class Request { * @param url url of request */ public Request(final HttpMethod method, final String url) { - this.method = method; - this.url = url; - this.queryParams = new HashMap<>(); - this.postParams = new HashMap<>(); - this.headerParams = new HashMap<>(); + super(method, url); } /** @@ -75,26 +41,8 @@ public Request(final HttpMethod method, final String domain, final String uri) { * @param uri uri of request * @param region region to make request */ - public Request( - final HttpMethod method, - final String domain, - final String uri, - final String region - ) { - this.method = method; - this.url = "https://" + domain + ".twilio.com" + uri; - this.region = region; - this.queryParams = new HashMap<>(); - this.postParams = new HashMap<>(); - this.headerParams = new HashMap<>(); - } - - public HttpMethod getMethod() { - return method; - } - - public String getUrl() { - return url; + public Request(final HttpMethod method, final String domain, final String uri, final String region) { + super(method, domain, uri, region); } public void setAuth(final String username, final String password) { @@ -102,38 +50,6 @@ public void setAuth(final String username, final String password) { this.password = password; } - public void setRegion(final String region) { - this.region = region; - } - - public void setEdge(final String edge) { - this.edge = edge; - } - - public void setUserAgentExtensions(List userAgentExtensions) { - this.userAgentExtensions = userAgentExtensions; - } - - public List getUserAgentExtensions() { - return this.userAgentExtensions; - } - - public EnumConstants.ContentType getContentType() { - return contentType; - } - - public void setContentType(EnumConstants.ContentType contentType) { - this.contentType = contentType; - } - - public String getBody() { - return body; - } - - public void setBody(String body) { - this.body = body; - } - /** * Create auth string from username and password. * @@ -157,219 +73,6 @@ public boolean requiresAuthentication() { return username != null || password != null; } - /** - * Build the URL for the request. - * - * @return URL for the request - */ - public URL constructURL() { - String params = encodeQueryParams(); - String stringUri = buildURL(); - - if (params.length() > 0) { - stringUri += "?" + params; - } - - try { - URI uri = new URI(stringUri); - return uri.toURL(); - } catch (final URISyntaxException e) { - throw new ApiException("Bad URI: " + e.getMessage()); - } catch (final MalformedURLException e) { - throw new ApiException("Bad URL: " + e.getMessage()); - } - } - - private String buildURL() { - try { - final URL parsedUrl = new URL(url); - String host = parsedUrl.getHost(); - final String[] pieces = host.split("\\."); - - if (pieces.length > 1) { - final String product = pieces[0]; - final String domain = joinIgnoreNull(".", pieces[pieces.length - 2], pieces[pieces.length - 1]); - - String targetRegion = region; - String targetEdge = edge; - - if (pieces.length == 4) { // product.region.twilio.com - targetRegion = targetRegion != null ? targetRegion : pieces[1]; - } else if (pieces.length == 5) { // product.edge.region.twilio.com - targetEdge = targetEdge != null ? targetEdge : pieces[1]; - targetRegion = targetRegion != null ? targetRegion : pieces[2]; - } - - if (targetEdge != null && targetRegion == null) - targetRegion = DEFAULT_REGION; - - host = joinIgnoreNull(".", product, targetEdge, targetRegion, domain); - } - - String urlPort = parsedUrl.getPort() != -1 ? ":" + parsedUrl.getPort() : null; - String protocol = parsedUrl.getProtocol() + "://"; - String[] pathPieces = parsedUrl.getPath().split("/"); - for (int i = 0; i < pathPieces.length; i++) { - pathPieces[i] = URLEncoder.encode(pathPieces[i], "UTF-8"); - } - String encodedPath = String.join("/", pathPieces); - String query = parsedUrl.getQuery() != null ? "?" + parsedUrl.getQuery() : null; - String ref = parsedUrl.getRef() != null ? "#" + parsedUrl.getRef() : null; - String credentials = parsedUrl.getUserInfo() != null ? parsedUrl.getUserInfo() + "@" : null; - return joinIgnoreNull("", protocol, credentials, host, urlPort, encodedPath, query, ref); - } catch (final MalformedURLException | UnsupportedEncodingException e) { - throw new ApiException("Bad URL: "+ e.getMessage()); - } - } - - /** - * Add query parameters for date ranges. - * - * @param name name of query parameter - * @param lowerBound lower bound of LocalDate range - * @param upperBound upper bound of LocalDate range - */ - public void addQueryDateRange(final String name, LocalDate lowerBound, LocalDate upperBound) { - if (lowerBound != null) { - String value = lowerBound.toString(); - addQueryParam(name + ">", value); - } - - if (upperBound != null) { - String value = upperBound.toString(); - addQueryParam(name + "<", value); - } - } - - /** - * Add query parameters for date ranges. - * - * @param name name of query parameter - * @param lowerBound lower bound of ZonedDateTime range - * @param upperBound upper bound of ZonedDateTime range - */ - public void addQueryDateTimeRange(final String name, ZonedDateTime lowerBound, ZonedDateTime upperBound) { - if (lowerBound != null) { - String value = lowerBound.withZoneSameInstant(ZoneId.of("UTC")).format(DateTimeFormatter.ofPattern(QUERY_STRING_DATE_TIME_FORMAT)); - addQueryParam(name + ">", value); - } - - if (upperBound != null) { - String value = upperBound.withZoneSameInstant(ZoneId.of("UTC")).format(DateTimeFormatter.ofPattern(QUERY_STRING_DATE_TIME_FORMAT)); - addQueryParam(name + "<", value); - } - } - - /** - * Add a query parameter. - * - * @param name name of parameter - * @param value value of parameter - */ - public void addQueryParam(final String name, final String value) { - addParam(queryParams, name, value); - } - - /** - * Add a form parameter. - * - * @param name name of parameter - * @param value value of parameter - */ - public void addPostParam(final String name, final String value) { - addParam(postParams, name, value); - } - - /** - * Add a header parameter. - * - * @param name name of parameter - * @param value value of parameter - */ - public void addHeaderParam(final String name, final String value) { - addParam(headerParams, name, value); - } - - private void addParam(final Map> params, final String name, final String value) { - if (value == null || value.equals("null")) - return; - - if (!params.containsKey(name)) { - params.put(name, new ArrayList()); - } - - params.get(name).add(value); - } - - /** - * Encode the form body. - * - * @return url encoded form body - */ - public String encodeFormBody() { - return encodeParameters(postParams); - } - - /** - * Encode the query parameters. - * - * @return url encoded query parameters - */ - public String encodeQueryParams() { - return encodeParameters(queryParams); - } - - private static String encodeParameters(final Map> params) { - List parameters = new ArrayList<>(); - - for (final Map.Entry> entry : params.entrySet()) { - try { - String encodedName = URLEncoder.encode(entry.getKey(), "UTF-8"); - for (final String value : entry.getValue()) { - if (value == null) { - continue; - } - - String encodedValue = URLEncoder.encode(value, "UTF-8"); - parameters.add(encodedName + "=" + encodedValue); - } - } catch (final UnsupportedEncodingException e) { - throw new InvalidRequestException("Couldn't encode params", entry.getKey(), e); - } - } - return joinIgnoreNull("&", parameters); - } - - private static String joinIgnoreNull(final String separator, final String... items) { - return joinIgnoreNull(separator, Arrays.asList(items)); - } - - private static String joinIgnoreNull(final String separator, final List items) { - final StringBuilder builder = new StringBuilder(); - - for (final String item : items) { - if (item != null) { - if (builder.length() > 0) { - builder.append(separator); - } - - builder.append(item); - } - } - - return builder.toString(); - } - - public Map> getQueryParams() { - return queryParams; - } - - public Map> getPostParams() { - return postParams; - } - - public Map> getHeaderParams() { return headerParams; } - @Override public boolean equals(Object o) { if (this == o) { @@ -382,7 +85,7 @@ public boolean equals(Object o) { Request other = (Request) o; return Objects.equals(this.method, other.method) && - Objects.equals(this.buildURL(), other.buildURL()) && + Objects.equals(this.buildURL(), this.buildURL()) && Objects.equals(this.username, other.username) && Objects.equals(this.password, other.password) && Objects.equals(this.queryParams, other.queryParams) && diff --git a/src/main/java/com/twilio/http/ValidationClient.java b/src/main/java/com/twilio/http/ValidationClient.java index 32dd43ab6a..9c55af6833 100644 --- a/src/main/java/com/twilio/http/ValidationClient.java +++ b/src/main/java/com/twilio/http/ValidationClient.java @@ -3,6 +3,7 @@ import com.twilio.Twilio; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiException; +import io.jsonwebtoken.SignatureAlgorithm; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; @@ -23,11 +24,7 @@ import java.util.Collection; import java.util.List; import java.util.Map; -import java.util.Set; - -import io.jsonwebtoken.SignatureAlgorithm; -import static io.jsonwebtoken.SignatureAlgorithm.PS256; import static io.jsonwebtoken.SignatureAlgorithm.RS256; public class ValidationClient extends HttpClient { @@ -167,7 +164,8 @@ public ValidationClient(final String accountSid, } @Override - public Response makeRequest(Request request) { + public Response makeRequest(IRequest iRequest) { + Request request = (Request)iRequest; RequestBuilder builder = RequestBuilder.create(request.getMethod().toString()) .setUri(request.constructURL().toString()) .setVersion(HttpVersion.HTTP_1_1) diff --git a/src/main/java/com/twilio/http/ValidationInterceptor.java b/src/main/java/com/twilio/http/ValidationInterceptor.java index c3c391e84c..8e3cfcd441 100644 --- a/src/main/java/com/twilio/http/ValidationInterceptor.java +++ b/src/main/java/com/twilio/http/ValidationInterceptor.java @@ -2,6 +2,7 @@ import com.twilio.jwt.Jwt; import com.twilio.jwt.validation.ValidationToken; +import io.jsonwebtoken.SignatureAlgorithm; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; @@ -12,8 +13,6 @@ import java.util.Arrays; import java.util.List; -import io.jsonwebtoken.SignatureAlgorithm; - public class ValidationInterceptor implements HttpRequestInterceptor { private static final List HEADERS = Arrays.asList("authorization", "host"); diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java new file mode 100644 index 0000000000..83976c2e45 --- /dev/null +++ b/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java @@ -0,0 +1,38 @@ +package com.twilio.http.bearertoken; + +import com.twilio.http.HttpMethod; +import com.twilio.http.IRequest; + +public class BearerTokenRequest extends IRequest { + + private String accessToken; + + public BearerTokenRequest(HttpMethod method, String url) { + super(method, url); + } + + public BearerTokenRequest(HttpMethod method, String domain, String uri) { + super(method, domain, uri); + } + + public BearerTokenRequest(HttpMethod method, String domain, String uri, String region) { + super(method, domain, uri, region); + } + + /** + * Create auth string from accessToken. + * + * @return basic authentication string + */ + public String getAuthString() { + return "Bearer " + accessToken; + } + + public boolean requiresAuthentication() { + return accessToken != null; + } + + public void setAuth(String accessToken) { + this.accessToken = accessToken; + } +} diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java new file mode 100644 index 0000000000..376bd58456 --- /dev/null +++ b/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java @@ -0,0 +1,168 @@ +package com.twilio.http.bearertoken; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.interfaces.DecodedJWT; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.twilio.exception.AuthenticationException; +import com.twilio.http.HttpClient; +import com.twilio.http.NetworkHttpClient; +import com.twilio.http.Response; +import lombok.Getter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; + + +/* + * Use this BearerToken Rest Client if no authentication is involved in an API. + */ +public class BearerTokenTwilioRestClient { + public static final int HTTP_STATUS_CODE_CREATED = 201; + public static final int HTTP_STATUS_CODE_NO_CONTENT = 204; + public static final int HTTP_STATUS_CODE_OK = 200; + public static final Predicate SUCCESS = i -> i != null && i >= 200 && i < 400; + @Getter + private final ObjectMapper objectMapper; + private final String accessToken; + @Getter + private final String region; + @Getter + private final String edge; + @Getter + private final HttpClient httpClient; + @Getter + private final List userAgentExtensions; + private static final Logger logger = LoggerFactory.getLogger(BearerTokenTwilioRestClient.class); + + private BearerTokenTwilioRestClient(BearerTokenTwilioRestClient.Builder b) { + this.accessToken = b.accessToken; + this.region = b.region; + this.edge = b.edge; + this.httpClient = b.httpClient; + this.objectMapper = new ObjectMapper(); + this.userAgentExtensions = b.userAgentExtensions; + + // This module configures the ObjectMapper to use + // public API methods for manipulating java.time.* + // classes. The alternative is to use reflection which + // generates warnings from the module system on Java 9+ + objectMapper.registerModule(new JavaTimeModule()); + } + + public static class Builder { + private final String accessToken; + private String region; + private String edge; + private HttpClient httpClient; + private List userAgentExtensions; + + public Builder(String accessToken) { + this.accessToken = accessToken; + this.region = System.getenv("TWILIO_REGION"); + this.edge = System.getenv("TWILIO_EDGE"); + userAgentExtensions = new ArrayList<>(); + } + + public BearerTokenTwilioRestClient.Builder region(final String region) { + this.region = region; + return this; + } + + public BearerTokenTwilioRestClient.Builder edge(final String edge) { + this.edge = edge; + return this; + } + + public BearerTokenTwilioRestClient.Builder httpClient(final HttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + public BearerTokenTwilioRestClient.Builder userAgentExtensions(final List userAgentExtensions) { + if (userAgentExtensions != null && !userAgentExtensions.isEmpty()) { + this.userAgentExtensions = new ArrayList<>(userAgentExtensions); + } + return this; + } + + public BearerTokenTwilioRestClient build() { + if (this.httpClient == null) { + this.httpClient = new NetworkHttpClient(); + } + return new BearerTokenTwilioRestClient(this); + } + } + public Response request(BearerTokenRequest request) { + + if (accessToken == null || accessToken.isEmpty()) { + throw new AuthenticationException("Access Token can not be Null or Empty."); + } + + if (isAccessTokenExpired()) { + throw new AuthenticationException("Access Token is expired."); + } + + request.setAuth(accessToken); + if (region != null) + request.setRegion(region); + if (edge != null) + request.setEdge(edge); + + if (userAgentExtensions != null && !userAgentExtensions.isEmpty()) { + request.setUserAgentExtensions(userAgentExtensions); + } + logRequest(request); + Response response = httpClient.reliableRequest(request); + + if (logger.isDebugEnabled()) { + logger.debug("status code: {}", response.getStatusCode()); + org.apache.http.Header[] responseHeaders = response.getHeaders(); + logger.debug("response headers:"); + for (int i = 0; i < responseHeaders.length; i++) { + logger.debug("responseHeader: {}", responseHeaders[i]); + } + } + + return response; + } + + public boolean isAccessTokenExpired() { + DecodedJWT jwt = JWT.decode(this.accessToken); + Date expiresAt = jwt.getExpiresAt(); + // Add a buffer of 30 seconds + long bufferMilliseconds = 30 * 1000; + Date bufferExpiresAt = new Date(expiresAt.getTime() - bufferMilliseconds); + return bufferExpiresAt.before(new Date()); + } + + public void logRequest(final BearerTokenRequest request) { + if (logger.isDebugEnabled()) { + logger.debug("-- BEGIN Twilio API BearerTokenRequest --"); + logger.debug("request method: " + request.getMethod()); + logger.debug("request URL: " + request.constructURL().toString()); + final Map> queryParams = request.getQueryParams(); + final Map> headerParams = request.getHeaderParams(); + + if (queryParams != null && !queryParams.isEmpty()) { + logger.debug("query parameters: " + queryParams); + } + + if (headerParams != null && !headerParams.isEmpty()) { + logger.debug("header parameters: "); + for (String key : headerParams.keySet()) { + if (!key.toLowerCase().contains("authorization")) { + logger.debug(key + ": " + headerParams.get(key)); + } + } + } + + logger.debug("-- END Twilio API BearerTokenRequest --"); + } + } +} diff --git a/src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java b/src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java new file mode 100644 index 0000000000..95ae3ad56a --- /dev/null +++ b/src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java @@ -0,0 +1,134 @@ +package com.twilio.http.noauth; + +import com.twilio.Twilio; +import com.twilio.constant.EnumConstants; +import com.twilio.exception.ApiException; +import com.twilio.http.HttpClient; +import com.twilio.http.HttpMethod; +import com.twilio.http.HttpUtility; +import com.twilio.http.IRequest; +import com.twilio.http.Response; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.RequestBuilder; +import org.apache.http.client.utils.HttpClientUtils; +import org.apache.http.config.SocketConfig; +import org.apache.http.entity.BufferedHttpEntity; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.message.BasicHeader; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public class NoAuthHttpClient extends HttpClient { + protected final org.apache.http.client.HttpClient client; + public NoAuthHttpClient() { + this(DEFAULT_REQUEST_CONFIG); + } + + public NoAuthHttpClient(final RequestConfig requestConfig) { + this(requestConfig, DEFAULT_SOCKET_CONFIG); + } + + public NoAuthHttpClient(final RequestConfig requestConfig, final SocketConfig socketConfig) { + Collection headers = Arrays.asList( + new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), + new BasicHeader(HttpHeaders.ACCEPT, "application/json"), + new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") + ); + + String googleAppEngineVersion = System.getProperty("com.google.appengine.runtime.version"); + boolean isGoogleAppEngine = googleAppEngineVersion != null && !googleAppEngineVersion.isEmpty(); + + org.apache.http.impl.client.HttpClientBuilder clientBuilder = HttpClientBuilder.create(); + + if (!isGoogleAppEngine) { + clientBuilder.useSystemProperties(); + } + + PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); + connectionManager.setDefaultSocketConfig(socketConfig); + /* + * Example: Lets say client has one server. + * There are 4 servers on edge handling client request. + * Each request takes on an average 500ms (2 request per second) + * Total number request can be server in a second from a route: 20 * 4 * 2 (DefaultMaxPerRoute * edge servers * request per second) + */ + connectionManager.setDefaultMaxPerRoute(20); + connectionManager.setMaxTotal(100); + + client = clientBuilder + .setConnectionManager(connectionManager) + .setDefaultRequestConfig(requestConfig) + .setDefaultHeaders(headers) + .setRedirectStrategy(this.getRedirectStrategy()) + .build(); + } + + @Override + public Response makeRequest(IRequest request) { + HttpMethod method = request.getMethod(); + RequestBuilder builder = RequestBuilder.create(method.toString()) + .setUri(request.constructURL().toString()) + .setVersion(HttpVersion.HTTP_1_1) + .setCharset(StandardCharsets.UTF_8); + + for (Map.Entry> entry : request.getHeaderParams().entrySet()) { + for (String value : entry.getValue()) { + builder.addHeader(entry.getKey(), value); + } + } + + if (method == HttpMethod.POST) { + // TODO: It will be removed after one RC Release. + if (request.getContentType() == null) request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + if (EnumConstants.ContentType.JSON.getValue().equals(request.getContentType().getValue())) { + HttpEntity entity = new StringEntity(request.getBody(), ContentType.APPLICATION_JSON); + builder.setEntity(entity); + builder.addHeader( + HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.JSON.getValue()); + } else { + builder.addHeader( + HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.FORM_URLENCODED.getValue()); + for (Map.Entry> entry : request.getPostParams().entrySet()) { + for (String value : entry.getValue()) { + builder.addParameter(entry.getKey(), value); + } + } + } + + } + builder.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions())); + + HttpResponse response = null; + + try { + response = client.execute(builder.build()); + HttpEntity entity = response.getEntity(); + return new Response( + // Consume the entire HTTP response before returning the stream + entity == null ? null : new BufferedHttpEntity(entity).getContent(), + response.getStatusLine().getStatusCode(), + response.getAllHeaders() + ); + } catch (IOException e) { + throw new ApiException(e.getMessage(), e); + } finally { + + // Ensure this response is properly closed + HttpClientUtils.closeQuietly(response); + + } + + } +} diff --git a/src/main/java/com/twilio/http/noauth/NoAuthRequest.java b/src/main/java/com/twilio/http/noauth/NoAuthRequest.java new file mode 100644 index 0000000000..00cc7bf140 --- /dev/null +++ b/src/main/java/com/twilio/http/noauth/NoAuthRequest.java @@ -0,0 +1,19 @@ +package com.twilio.http.noauth; + +import com.twilio.http.HttpMethod; +import com.twilio.http.IRequest; + +public class NoAuthRequest extends IRequest { + + public NoAuthRequest(HttpMethod method, String url) { + super(method, url); + } + + public NoAuthRequest(HttpMethod method, String domain, String uri) { + super(method, domain, uri, null); + } + + public NoAuthRequest(HttpMethod method, String domain, String uri, String region) { + super(method, domain, uri, region); + } +} diff --git a/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java b/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java new file mode 100644 index 0000000000..b24c35ca58 --- /dev/null +++ b/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java @@ -0,0 +1,137 @@ +package com.twilio.http.noauth; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.twilio.http.HttpClient; +import com.twilio.http.NetworkHttpClient; +import com.twilio.http.Response; +import lombok.Getter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + + +/* + * Use this NoAuth Rest Client if no authentication is involved in an API. + */ +public class NoAuthTwilioRestClient { + @Getter + private final ObjectMapper objectMapper; + + @Getter + private final String region; + @Getter + private final String edge; + @Getter + private final HttpClient httpClient; + @Getter + private final List userAgentExtensions; + private static final Logger logger = LoggerFactory.getLogger(NoAuthTwilioRestClient.class); + + private NoAuthTwilioRestClient(NoAuthTwilioRestClient.Builder b) { + this.region = b.region; + this.edge = b.edge; + this.httpClient = b.httpClient; + this.objectMapper = new ObjectMapper(); + this.userAgentExtensions = b.userAgentExtensions; + + // This module configures the ObjectMapper to use + // public API methods for manipulating java.time.* + // classes. The alternative is to use reflection which + // generates warnings from the module system on Java 9+ + objectMapper.registerModule(new JavaTimeModule()); + } + + public static class Builder { + private String region; + private String edge; + private HttpClient httpClient; + private List userAgentExtensions; + + public Builder() { + this.region = System.getenv("TWILIO_REGION"); + this.edge = System.getenv("TWILIO_EDGE"); + userAgentExtensions = new ArrayList<>(); + } + + public NoAuthTwilioRestClient.Builder region(final String region) { + this.region = region; + return this; + } + + public NoAuthTwilioRestClient.Builder edge(final String edge) { + this.edge = edge; + return this; + } + + public NoAuthTwilioRestClient.Builder httpClient(final HttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + public NoAuthTwilioRestClient.Builder userAgentExtensions(final List userAgentExtensions) { + if (userAgentExtensions != null && !userAgentExtensions.isEmpty()) { + this.userAgentExtensions = new ArrayList<>(userAgentExtensions); + } + return this; + } + + public NoAuthTwilioRestClient build() { + if (this.httpClient == null) { + this.httpClient = new NetworkHttpClient(); + } + return new NoAuthTwilioRestClient(this); + } + } + public Response request(NoAuthRequest request) { + if (region != null) + request.setRegion(region); + if (edge != null) + request.setEdge(edge); + + if (userAgentExtensions != null && !userAgentExtensions.isEmpty()) { + request.setUserAgentExtensions(userAgentExtensions); + } + logRequest(request); + Response response = httpClient.reliableRequest(request); + + if (logger.isDebugEnabled()) { + logger.debug("status code: {}", response.getStatusCode()); + org.apache.http.Header[] responseHeaders = response.getHeaders(); + logger.debug("response headers:"); + for (int i = 0; i < responseHeaders.length; i++) { + logger.debug("responseHeader: {}", responseHeaders[i]); + } + } + + return response; + } + + public void logRequest(final NoAuthRequest request) { + if (logger.isDebugEnabled()) { + logger.debug("-- BEGIN Twilio API NoAuthRequest --"); + logger.debug("request method: " + request.getMethod()); + logger.debug("request URL: " + request.constructURL().toString()); + final Map> queryParams = request.getQueryParams(); + final Map> headerParams = request.getHeaderParams(); + + if (queryParams != null && !queryParams.isEmpty()) { + logger.debug("query parameters: " + queryParams); + } + + if (headerParams != null && !headerParams.isEmpty()) { + logger.debug("header parameters: "); + for (String key : headerParams.keySet()) { + if (!key.toLowerCase().contains("authorization")) { + logger.debug(key + ": " + headerParams.get(key)); + } + } + } + + logger.debug("-- END Twilio API NoAuthRequest --"); + } + } +} From b97c2d1ef8de7c031897fdf15531f9f4b444f450 Mon Sep 17 00:00:00 2001 From: AsabuHere Date: Wed, 5 Jun 2024 10:12:26 -0600 Subject: [PATCH 2/3] bearertoken apis change --- .../com/twilio/base/bearertoken/Page.java | 41 +- .../com/twilio/constant/EnumConstants.java | 1 + .../com/twilio/http/NetworkHttpClient.java | 2 +- .../com/twilio/http/ValidationClient.java | 2 +- .../http/noauth/NoAuthTwilioRestClient.java | 3 + .../previewiam/organizations/Account.java | 218 ++++++++++ .../organizations/AccountFetcher.java | 83 ++++ .../organizations/AccountReader.java | 139 +++++++ .../previewiam/organizations/Authorize.java | 161 ++++++++ .../organizations/AuthorizeFetcher.java | 125 ++++++ .../organizations/ResourceType.java | 185 +++++++++ .../organizations/ResourceTypeReader.java | 123 ++++++ .../organizations/RoleAssignment.java | 227 +++++++++++ .../organizations/RoleAssignmentCreator.java | 102 +++++ .../organizations/RoleAssignmentDeleter.java | 81 ++++ .../organizations/RoleAssignmentReader.java | 157 +++++++ .../rest/previewiam/organizations/Token.java | 194 +++++++++ .../organizations/TokenCreator.java | 164 ++++++++ .../rest/previewiam/organizations/User.java | 382 ++++++++++++++++++ .../previewiam/organizations/UserCreator.java | 102 +++++ .../previewiam/organizations/UserDeleter.java | 81 ++++ .../previewiam/organizations/UserFetcher.java | 83 ++++ .../previewiam/organizations/UserReader.java | 139 +++++++ .../previewiam/organizations/UserUpdater.java | 102 +++++ src/test/java/com/twilio/ClusterTest.java | 93 +++++ 25 files changed, 2969 insertions(+), 21 deletions(-) create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/Account.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/Authorize.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/AuthorizeFetcher.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/ResourceType.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/ResourceTypeReader.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/Token.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/TokenCreator.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/User.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java create mode 100644 src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java diff --git a/src/main/java/com/twilio/base/bearertoken/Page.java b/src/main/java/com/twilio/base/bearertoken/Page.java index 9c31231ef1..757f18f267 100644 --- a/src/main/java/com/twilio/base/bearertoken/Page.java +++ b/src/main/java/com/twilio/base/bearertoken/Page.java @@ -169,30 +169,33 @@ private static Page buildPage(JsonNode root, List results) { private static Page buildNextGenPage(JsonNode root, List results) { JsonNode meta = root.get("meta"); - Builder builder = new Builder().url(meta.get("url").asText()); + Builder builder = new Builder<>(); + if(meta != null && meta.get("url") != null) { + builder = builder.url(meta.get("url").asText()); - JsonNode nextPageNode = meta.get("next_page_url"); - if (!nextPageNode.isNull()) { - builder.nextPageUrl(nextPageNode.asText()); - } + JsonNode nextPageNode = meta.get("next_page_url"); + if (!nextPageNode.isNull()) { + builder.nextPageUrl(nextPageNode.asText()); + } - JsonNode previousPageNode = meta.get("previous_page_url"); - if (!previousPageNode.isNull()) { - builder.previousPageUrl(previousPageNode.asText()); - } + JsonNode previousPageNode = meta.get("previous_page_url"); + if (!previousPageNode.isNull()) { + builder.previousPageUrl(previousPageNode.asText()); + } - JsonNode firstPageNode = meta.get("first_page_url"); - if (!firstPageNode.isNull()) { - builder.firstPageUrl(firstPageNode.asText()); - } + JsonNode firstPageNode = meta.get("first_page_url"); + if (!firstPageNode.isNull()) { + builder.firstPageUrl(firstPageNode.asText()); + } - JsonNode pageSizeNode = meta.get("page_size"); - if (!pageSizeNode.isNull()) { - builder.pageSize(pageSizeNode.asInt()); - } else { - builder.pageSize(results.size()); - } + JsonNode pageSizeNode = meta.get("page_size"); + if (!pageSizeNode.isNull()) { + builder.pageSize(pageSizeNode.asInt()); + } else { + builder.pageSize(results.size()); + } + } return builder.records(results).build(); } diff --git a/src/main/java/com/twilio/constant/EnumConstants.java b/src/main/java/com/twilio/constant/EnumConstants.java index 7d2f70b590..2765c1d56b 100644 --- a/src/main/java/com/twilio/constant/EnumConstants.java +++ b/src/main/java/com/twilio/constant/EnumConstants.java @@ -9,6 +9,7 @@ public class EnumConstants { @RequiredArgsConstructor public enum ContentType { JSON("application/json"), + SCIM("application/scim"), FORM_URLENCODED("application/x-www-form-urlencoded"); private final String value; diff --git a/src/main/java/com/twilio/http/NetworkHttpClient.java b/src/main/java/com/twilio/http/NetworkHttpClient.java index 36fb5420d1..ac170d32b6 100644 --- a/src/main/java/com/twilio/http/NetworkHttpClient.java +++ b/src/main/java/com/twilio/http/NetworkHttpClient.java @@ -140,7 +140,7 @@ public Response makeRequest(final T request) { } } - if (method == HttpMethod.POST) { + if (method == HttpMethod.POST || method == HttpMethod.PUT) { // TODO: It will be removed after one RC Release. if (request.getContentType() == null) request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); if (EnumConstants.ContentType.JSON.getValue().equals(request.getContentType().getValue())) { diff --git a/src/main/java/com/twilio/http/ValidationClient.java b/src/main/java/com/twilio/http/ValidationClient.java index 9c55af6833..d9010cabf9 100644 --- a/src/main/java/com/twilio/http/ValidationClient.java +++ b/src/main/java/com/twilio/http/ValidationClient.java @@ -176,7 +176,7 @@ public Response makeRequest(IRequest iRequest) { } HttpMethod method = request.getMethod(); - if (method == HttpMethod.POST) { + if (method == HttpMethod.POST || method == HttpMethod.PUT) { // TODO: It will be removed after one RC Release. if (request.getContentType() == null) request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); if (EnumConstants.ContentType.JSON.getValue().equals(request.getContentType().getValue())) { diff --git a/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java b/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java index b24c35ca58..89d1e28805 100644 --- a/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java +++ b/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.function.Predicate; /* @@ -31,6 +32,8 @@ public class NoAuthTwilioRestClient { private final List userAgentExtensions; private static final Logger logger = LoggerFactory.getLogger(NoAuthTwilioRestClient.class); + public static final Predicate SUCCESS = i -> i != null && i >= 200 && i < 400; + private NoAuthTwilioRestClient(NoAuthTwilioRestClient.Builder b) { this.region = b.region; this.edge = b.edge; diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java new file mode 100644 index 0000000000..bad11dc82f --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java @@ -0,0 +1,218 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.bearertoken.Resource; +import com.twilio.converter.Converter; +import java.util.Currency; +import com.twilio.converter.DateConverter; +import com.twilio.converter.Promoter; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.CurrencyDeserializer; +import com.twilio.exception.ApiConnectionException; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Request; +import com.twilio.http.Response; +import com.twilio.http.TwilioRestClient; +import com.twilio.rest.Domains; + +import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.time.ZonedDateTime; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.Map; +import java.time.LocalDate; +import java.math.BigDecimal; +import com.twilio.type.PhoneNumberCapabilities; +import com.twilio.type.FeedbackIssue; +import com.twilio.type.IceServer; +import com.twilio.type.InboundCallPrice; +import com.twilio.type.OutboundPrefixPriceWithOrigin; +import com.twilio.type.OutboundPrefixPrice; +import com.twilio.type.OutboundCallPriceWithOrigin; +import com.twilio.type.PhoneNumberPrice; +import com.twilio.type.InboundSmsPrice; +import com.twilio.type.OutboundSmsPrice; +import com.twilio.type.OutboundCallPrice; +import com.twilio.type.RecordingRule; +import com.twilio.type.SubscribeRule; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class Account extends Resource { + private static final long serialVersionUID = 74567986844628L; + + + + public static AccountFetcher fetcher(final String pathOrganizationSid, final String pathAccountSid){ + return new AccountFetcher(pathOrganizationSid, pathAccountSid); + } + + public static AccountReader reader(final String pathOrganizationSid){ + return new AccountReader(pathOrganizationSid); + } + + /** + * Converts a JSON String into a Account object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return Account object represented by the provided JSON + */ + public static Account fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Account.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a Account object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return Account object represented by the provided JSON + */ + public static Account fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Account.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + private final String accountSid; + private final String friendlyName; + private final Account.StatusEnum status; + private final String ownerSid; + private final ZonedDateTime dateCreated; + + @JsonCreator + private Account( + @JsonProperty("account_sid") + final String accountSid, + + @JsonProperty("friendly_name") + final String friendlyName, + + @JsonProperty("status") + final Account.StatusEnum status, + + @JsonProperty("owner_sid") + final String ownerSid, + + @JsonProperty("date_created") + final String dateCreated + ) { + this.accountSid = accountSid; + this.friendlyName = friendlyName; + this.status = status; + this.ownerSid = ownerSid; + this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); + } + + public final String getAccountSid() { + return this.accountSid; + } + public final String getFriendlyName() { + return this.friendlyName; + } + public final Account.StatusEnum getStatus() { + return this.status; + } + public final String getOwnerSid() { + return this.ownerSid; + } + public final ZonedDateTime getDateCreated() { + return this.dateCreated; + } + + @Override + public boolean equals(final Object o) { + if (this==o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + Account other = (Account) o; + + return Objects.equals(accountSid, other.accountSid) && Objects.equals(friendlyName, other.friendlyName) && Objects.equals(status, other.status) && Objects.equals(ownerSid, other.ownerSid) && Objects.equals(dateCreated, other.dateCreated) ; + } + + @Override + public int hashCode() { + return Objects.hash(accountSid, friendlyName, status, ownerSid, dateCreated); + } + + public enum StatusEnum { + ACTIVE("active"), + SUSPENDED("suspended"), + PENDING_CLOSURE("pending_closure"), + CLOSED("closed"); + + private final String value; + + private StatusEnum(final String value) { + this.value = value; + } + + public String toString() { + return value; + } + + @JsonCreator + public static StatusEnum forValue(final String value) { + return Promoter.enumFromString(value, StatusEnum.values()); + } + } + +} + diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java b/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java new file mode 100644 index 0000000000..b718a85f7e --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java @@ -0,0 +1,83 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.twilio.base.bearertoken.Fetcher; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.Converter; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.rest.Domains; + +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.time.ZonedDateTime; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import com.twilio.converter.DateConverter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.ToString; + +public class AccountFetcher extends Fetcher { + private String pathOrganizationSid; + private String pathAccountSid; + + public AccountFetcher(final String pathOrganizationSid, final String pathAccountSid){ + this.pathOrganizationSid = pathOrganizationSid; + this.pathAccountSid = pathAccountSid; + } + + + @Override + public Account fetch(final BearerTokenTwilioRestClient client) { + String path = "/Organizations/{organizationSid}/Accounts/{accountSid}"; + + path = path.replace("{"+"organizationSid"+"}", this.pathOrganizationSid.toString()); + path = path.replace("{"+"accountSid"+"}", this.pathAccountSid.toString()); + + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + Domains.PREVIEWIAM.toString(), + path + ); + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("Account fetch failed: Unable to connect to server"); + } else if (!BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return Account.fromJson(response.getStream(), client.getObjectMapper()); + } +} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java new file mode 100644 index 0000000000..b1effdfee9 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java @@ -0,0 +1,139 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.twilio.base.bearertoken.Page; +import com.twilio.base.bearertoken.Reader; +import com.twilio.base.bearertoken.ResourceSet; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.Converter; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.rest.Domains; +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.time.format.DateTimeFormatter; +import com.twilio.converter.DateConverter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.ToString; + +public class AccountReader extends Reader { + private String pathOrganizationSid; + private Integer pageSize; + + public AccountReader(final String pathOrganizationSid){ + this.pathOrganizationSid = pathOrganizationSid; + } + + public AccountReader setPageSize(final Integer pageSize){ + this.pageSize = pageSize; + return this; + } + + @Override + public ResourceSet read(final BearerTokenTwilioRestClient client) { + return new ResourceSet<>(this, client, firstPage(client)); + } + + public Page firstPage(final BearerTokenTwilioRestClient client) { + String path = "/Organizations/{organizationSid}/Accounts"; + path = path.replace("{"+"organizationSid"+"}", this.pathOrganizationSid.toString()); + + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + Domains.PREVIEWIAM.toString(), + path + ); + + addQueryParams(request); + return pageForRequest(client, request); + } + + private Page pageForRequest(final BearerTokenTwilioRestClient client, final BearerTokenRequest request) { + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("Account read failed: Unable to connect to server"); + } else if (!BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return Page.fromJson( + "content", + response.getContent(), + Account.class, + client.getObjectMapper() + ); + } + + @Override + public Page previousPage(final Page page, final BearerTokenTwilioRestClient client) { + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) + ); + return pageForRequest(client, request); + } + + + @Override + public Page nextPage(final Page page, final BearerTokenTwilioRestClient client) { + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + page.getNextPageUrl(Domains.PREVIEWIAM.toString()) + ); + return pageForRequest(client, request); + } + + @Override + public Page getPage(final String targetUrl, final BearerTokenTwilioRestClient client) { + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + targetUrl + ); + + return pageForRequest(client, request); + } + private void addQueryParams(final BearerTokenRequest request) { + if (pageSize != null) { + + request.addQueryParam("PageSize", pageSize.toString()); + } + + if(getPageSize() != null) { + request.addQueryParam("PageSize", Integer.toString(getPageSize())); + } + } +} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/Authorize.java b/src/main/java/com/twilio/rest/previewiam/organizations/Authorize.java new file mode 100644 index 0000000000..137f923396 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/Authorize.java @@ -0,0 +1,161 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.bearertoken.Resource; +import com.twilio.converter.Converter; +import java.util.Currency; +import com.twilio.converter.DateConverter; +import com.twilio.converter.Promoter; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.CurrencyDeserializer; +import com.twilio.exception.ApiConnectionException; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Request; +import com.twilio.http.Response; +import com.twilio.http.TwilioRestClient; +import com.twilio.rest.Domains; + +import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.time.ZonedDateTime; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.Map; +import java.time.LocalDate; +import java.math.BigDecimal; +import com.twilio.type.PhoneNumberCapabilities; +import com.twilio.type.FeedbackIssue; +import com.twilio.type.IceServer; +import com.twilio.type.InboundCallPrice; +import com.twilio.type.OutboundPrefixPriceWithOrigin; +import com.twilio.type.OutboundPrefixPrice; +import com.twilio.type.OutboundCallPriceWithOrigin; +import com.twilio.type.PhoneNumberPrice; +import com.twilio.type.InboundSmsPrice; +import com.twilio.type.OutboundSmsPrice; +import com.twilio.type.OutboundCallPrice; +import com.twilio.type.RecordingRule; +import com.twilio.type.SubscribeRule; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class Authorize extends Resource { + private static final long serialVersionUID = 245900587626041L; + + + + public static AuthorizeFetcher fetcher(){ + return new AuthorizeFetcher(); + } + + /** + * Converts a JSON String into a Authorize object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return Authorize object represented by the provided JSON + */ + public static Authorize fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Authorize.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a Authorize object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return Authorize object represented by the provided JSON + */ + public static Authorize fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Authorize.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + private final URI redirectTo; + + @JsonCreator + private Authorize( + @JsonProperty("redirect_to") + final URI redirectTo + ) { + this.redirectTo = redirectTo; + } + + public final URI getRedirectTo() { + return this.redirectTo; + } + + @Override + public boolean equals(final Object o) { + if (this==o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + Authorize other = (Authorize) o; + + return Objects.equals(redirectTo, other.redirectTo) ; + } + + @Override + public int hashCode() { + return Objects.hash(redirectTo); + } + + +} + diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/AuthorizeFetcher.java b/src/main/java/com/twilio/rest/previewiam/organizations/AuthorizeFetcher.java new file mode 100644 index 0000000000..5b5fd5edb2 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/AuthorizeFetcher.java @@ -0,0 +1,125 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.twilio.base.bearertoken.Fetcher; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.Converter; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.rest.Domains; + +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.time.ZonedDateTime; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import com.twilio.converter.DateConverter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.ToString; + +public class AuthorizeFetcher extends Fetcher { + private String responseType; + private String clientId; + private String redirectUri; + private String scope; + private String state; + + public AuthorizeFetcher(){ + } + + public AuthorizeFetcher setResponseType(final String responseType){ + this.responseType = responseType; + return this; + } + public AuthorizeFetcher setClientId(final String clientId){ + this.clientId = clientId; + return this; + } + public AuthorizeFetcher setRedirectUri(final String redirectUri){ + this.redirectUri = redirectUri; + return this; + } + public AuthorizeFetcher setScope(final String scope){ + this.scope = scope; + return this; + } + public AuthorizeFetcher setState(final String state){ + this.state = state; + return this; + } + + @Override + public Authorize fetch(final BearerTokenTwilioRestClient client) { + String path = "/v1/authorize"; + + + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + Domains.PREVIEWIAM.toString(), + path + ); + addQueryParams(request); + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("Authorize fetch failed: Unable to connect to server"); + } else if (!BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return Authorize.fromJson(response.getStream(), client.getObjectMapper()); + } + private void addQueryParams(final BearerTokenRequest request) { + if (responseType != null) { + + request.addQueryParam("response_type", responseType); + } + if (clientId != null) { + + request.addQueryParam("client_id", clientId); + } + if (redirectUri != null) { + + request.addQueryParam("redirect_uri", redirectUri); + } + if (scope != null) { + + request.addQueryParam("scope", scope); + } + if (state != null) { + + request.addQueryParam("state", state); + } + } +} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/ResourceType.java b/src/main/java/com/twilio/rest/previewiam/organizations/ResourceType.java new file mode 100644 index 0000000000..25c701390f --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/ResourceType.java @@ -0,0 +1,185 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.bearertoken.Resource; +import com.twilio.converter.Converter; +import java.util.Currency; +import com.twilio.converter.DateConverter; +import com.twilio.converter.Promoter; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.CurrencyDeserializer; +import com.twilio.exception.ApiConnectionException; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Request; +import com.twilio.http.Response; +import com.twilio.http.TwilioRestClient; +import com.twilio.rest.Domains; + +import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.time.ZonedDateTime; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.Map; +import java.time.LocalDate; +import java.math.BigDecimal; +import com.twilio.type.PhoneNumberCapabilities; +import com.twilio.type.FeedbackIssue; +import com.twilio.type.IceServer; +import com.twilio.type.InboundCallPrice; +import com.twilio.type.OutboundPrefixPriceWithOrigin; +import com.twilio.type.OutboundPrefixPrice; +import com.twilio.type.OutboundCallPriceWithOrigin; +import com.twilio.type.PhoneNumberPrice; +import com.twilio.type.InboundSmsPrice; +import com.twilio.type.OutboundSmsPrice; +import com.twilio.type.OutboundCallPrice; +import com.twilio.type.RecordingRule; +import com.twilio.type.SubscribeRule; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class ResourceType extends Resource { + private static final long serialVersionUID = 264859174513564L; + + + + public static ResourceTypeReader reader(final String pathOrganizationSid){ + return new ResourceTypeReader(pathOrganizationSid); + } + + /** + * Converts a JSON String into a ResourceType object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return ResourceType object represented by the provided JSON + */ + public static ResourceType fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, ResourceType.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a ResourceType object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return ResourceType object represented by the provided JSON + */ + public static ResourceType fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, ResourceType.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + private final String name; + private final String description; + private final String endpoint; + private final String schema; + + @JsonCreator + private ResourceType( + @JsonProperty("name") + final String name, + + @JsonProperty("description") + final String description, + + @JsonProperty("endpoint") + final String endpoint, + + @JsonProperty("schema") + final String schema + ) { + this.name = name; + this.description = description; + this.endpoint = endpoint; + this.schema = schema; + } + + public final String getName() { + return this.name; + } + public final String getDescription() { + return this.description; + } + public final String getEndpoint() { + return this.endpoint; + } + public final String getSchema() { + return this.schema; + } + + @Override + public boolean equals(final Object o) { + if (this==o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + ResourceType other = (ResourceType) o; + + return Objects.equals(name, other.name) && Objects.equals(description, other.description) && Objects.equals(endpoint, other.endpoint) && Objects.equals(schema, other.schema) ; + } + + @Override + public int hashCode() { + return Objects.hash(name, description, endpoint, schema); + } + + +} + diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/ResourceTypeReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/ResourceTypeReader.java new file mode 100644 index 0000000000..821a5f6b63 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/ResourceTypeReader.java @@ -0,0 +1,123 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.twilio.base.bearertoken.Page; +import com.twilio.base.bearertoken.Reader; +import com.twilio.base.bearertoken.ResourceSet; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.Converter; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.rest.Domains; +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.time.format.DateTimeFormatter; +import com.twilio.converter.DateConverter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.ToString; + +public class ResourceTypeReader extends Reader { + private String pathOrganizationSid; + + public ResourceTypeReader(final String pathOrganizationSid){ + this.pathOrganizationSid = pathOrganizationSid; + } + + + @Override + public ResourceSet read(final BearerTokenTwilioRestClient client) { + return new ResourceSet<>(this, client, firstPage(client)); + } + + public Page firstPage(final BearerTokenTwilioRestClient client) { + String path = "/Organizations/{organizationSid}/scim/ResourceTypes"; + path = path.replace("{"+"organizationSid"+"}", this.pathOrganizationSid.toString()); + + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + Domains.PREVIEWIAM.toString(), + path + ); + + return pageForRequest(client, request); + } + + private Page pageForRequest(final BearerTokenTwilioRestClient client, final BearerTokenRequest request) { + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("ResourceType read failed: Unable to connect to server"); + } else if (!BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return Page.fromJson( + "Resources", + response.getContent(), + ResourceType.class, + client.getObjectMapper() + ); + } + + @Override + public Page previousPage(final Page page, final BearerTokenTwilioRestClient client) { + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) + ); + return pageForRequest(client, request); + } + + + @Override + public Page nextPage(final Page page, final BearerTokenTwilioRestClient client) { + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + page.getNextPageUrl(Domains.PREVIEWIAM.toString()) + ); + return pageForRequest(client, request); + } + + @Override + public Page getPage(final String targetUrl, final BearerTokenTwilioRestClient client) { + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + targetUrl + ); + + return pageForRequest(client, request); + } +} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java new file mode 100644 index 0000000000..bec84dceb4 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java @@ -0,0 +1,227 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.bearertoken.Resource; +import com.twilio.converter.Converter; +import java.util.Currency; +import com.twilio.converter.DateConverter; +import com.twilio.converter.Promoter; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.CurrencyDeserializer; +import com.twilio.exception.ApiConnectionException; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Request; +import com.twilio.http.Response; +import com.twilio.http.TwilioRestClient; +import com.twilio.rest.Domains; + +import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.time.ZonedDateTime; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.Map; +import java.time.LocalDate; +import java.math.BigDecimal; +import com.twilio.type.PhoneNumberCapabilities; +import com.twilio.type.FeedbackIssue; +import com.twilio.type.IceServer; +import com.twilio.type.InboundCallPrice; +import com.twilio.type.OutboundPrefixPriceWithOrigin; +import com.twilio.type.OutboundPrefixPrice; +import com.twilio.type.OutboundCallPriceWithOrigin; +import com.twilio.type.PhoneNumberPrice; +import com.twilio.type.InboundSmsPrice; +import com.twilio.type.OutboundSmsPrice; +import com.twilio.type.OutboundCallPrice; +import com.twilio.type.RecordingRule; +import com.twilio.type.SubscribeRule; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class RoleAssignment extends Resource { + private static final long serialVersionUID = 175566213667704L; + + + @ToString + static public class PublicApiCreateRoleAssignmentRequest { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("role_sid") + @Getter @Setter private String roleSid; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("scope") + @Getter @Setter private String scope; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("identity") + @Getter @Setter private String identity; + + public PublicApiCreateRoleAssignmentRequest(final String roleSid, final String scope, final String identity ) { + this.roleSid = roleSid; + this.scope = scope; + this.identity = identity; + } + + public static PublicApiCreateRoleAssignmentRequest fromJson(String jsonString, ObjectMapper mapper) throws IOException { + return mapper.readValue(jsonString, PublicApiCreateRoleAssignmentRequest.class); + } + } + + public static RoleAssignmentCreator creator(final String pathOrganizationSid, final PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest){ + return new RoleAssignmentCreator(pathOrganizationSid, publicApiCreateRoleAssignmentRequest); + } + + public static RoleAssignmentDeleter deleter(final String pathOrganizationSid, final String pathRoleAssignmentSid){ + return new RoleAssignmentDeleter(pathOrganizationSid, pathRoleAssignmentSid); + } + + public static RoleAssignmentReader reader(final String pathOrganizationSid){ + return new RoleAssignmentReader(pathOrganizationSid); + } + + /** + * Converts a JSON String into a RoleAssignment object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return RoleAssignment object represented by the provided JSON + */ + public static RoleAssignment fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, RoleAssignment.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a RoleAssignment object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return RoleAssignment object represented by the provided JSON + */ + public static RoleAssignment fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, RoleAssignment.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + private final String sid; + private final String roleSid; + private final String scope; + private final String identity; + + @JsonCreator + private RoleAssignment( + @JsonProperty("sid") + final String sid, + + @JsonProperty("role_sid") + final String roleSid, + + @JsonProperty("scope") + final String scope, + + @JsonProperty("identity") + final String identity + ) { + this.sid = sid; + this.roleSid = roleSid; + this.scope = scope; + this.identity = identity; + } + + public final String getSid() { + return this.sid; + } + public final String getRoleSid() { + return this.roleSid; + } + public final String getScope() { + return this.scope; + } + public final String getIdentity() { + return this.identity; + } + + @Override + public boolean equals(final Object o) { + if (this==o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + RoleAssignment other = (RoleAssignment) o; + + return Objects.equals(sid, other.sid) && Objects.equals(roleSid, other.roleSid) && Objects.equals(scope, other.scope) && Objects.equals(identity, other.identity) ; + } + + @Override + public int hashCode() { + return Objects.hash(sid, roleSid, scope, identity); + } + + +} + diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java new file mode 100644 index 0000000000..de49feff58 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java @@ -0,0 +1,102 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.bearertoken.Creator; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.constant.EnumConstants; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.Converter; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.rest.Domains; +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; +import java.time.LocalDate; +import com.twilio.converter.Converter; +import java.time.ZonedDateTime; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.time.format.DateTimeFormatter; +import com.twilio.converter.DateConverter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +import lombok.ToString; + +import java.net.URI; + +public class RoleAssignmentCreator extends Creator{ + private String pathOrganizationSid; + private RoleAssignment.PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest; + + public RoleAssignmentCreator(final String pathOrganizationSid, final RoleAssignment.PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest) { + this.pathOrganizationSid = pathOrganizationSid; + this.publicApiCreateRoleAssignmentRequest = publicApiCreateRoleAssignmentRequest; + } + + public RoleAssignmentCreator setPublicApiCreateRoleAssignmentRequest(final RoleAssignment.PublicApiCreateRoleAssignmentRequest publicApiCreateRoleAssignmentRequest){ + this.publicApiCreateRoleAssignmentRequest = publicApiCreateRoleAssignmentRequest; + return this; + } + + @Override + public RoleAssignment create(final BearerTokenTwilioRestClient client){ + String path = "/Organizations/{organizationSid}/RoleAssignments"; + + path = path.replace("{"+"organizationSid"+"}", this.pathOrganizationSid.toString()); + path = path.replace("{"+"publicApiCreateRoleAssignmentRequest"+"}", this.publicApiCreateRoleAssignmentRequest.toString()); + + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.POST, + Domains.PREVIEWIAM.toString(), + path + ); + request.setContentType(EnumConstants.ContentType.JSON); + addPostParams(request, client); + Response response = client.request(request); + if (response == null) { + throw new ApiConnectionException("RoleAssignment creation failed: Unable to connect to server"); + } else if (!BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return RoleAssignment.fromJson(response.getStream(), client.getObjectMapper()); + } + private void addPostParams(final BearerTokenRequest request, BearerTokenTwilioRestClient client) { + ObjectMapper objectMapper = client.getObjectMapper(); + if (publicApiCreateRoleAssignmentRequest != null) { + request.setBody(RoleAssignment.toJson(publicApiCreateRoleAssignmentRequest, objectMapper)); + } + } +} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java new file mode 100644 index 0000000000..7f581fd312 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java @@ -0,0 +1,81 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.twilio.base.bearertoken.Deleter; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.exception.ApiException; +import com.twilio.converter.Converter; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.rest.Domains; +import java.time.LocalDate; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import com.twilio.converter.DateConverter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.ToString; + +public class RoleAssignmentDeleter extends Deleter { + private String pathOrganizationSid; + private String pathRoleAssignmentSid; + + public RoleAssignmentDeleter(final String pathOrganizationSid, final String pathRoleAssignmentSid){ + this.pathOrganizationSid = pathOrganizationSid; + this.pathRoleAssignmentSid = pathRoleAssignmentSid; + } + + + @Override + public boolean delete(final BearerTokenTwilioRestClient client) { + String path = "/Organizations/{organizationSid}/RoleAssignments/{roleAssignmentSid}"; + + path = path.replace("{"+"organizationSid"+"}", this.pathOrganizationSid.toString()); + path = path.replace("{"+"roleAssignmentSid"+"}", this.pathRoleAssignmentSid.toString()); + + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.DELETE, + Domains.PREVIEWIAM.toString(), + path + ); + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("RoleAssignment delete failed: Unable to connect to server"); + } else if (!BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + return response.getStatusCode() == 204; + } +} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java new file mode 100644 index 0000000000..8af502d723 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java @@ -0,0 +1,157 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.twilio.base.bearertoken.Page; +import com.twilio.base.bearertoken.Reader; +import com.twilio.base.bearertoken.ResourceSet; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.Converter; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.rest.Domains; +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.time.format.DateTimeFormatter; +import com.twilio.converter.DateConverter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.ToString; + +public class RoleAssignmentReader extends Reader { + private String pathOrganizationSid; + private Integer pageSize; + private String identity; + private String scope; + + public RoleAssignmentReader(final String pathOrganizationSid){ + this.pathOrganizationSid = pathOrganizationSid; + } + + public RoleAssignmentReader setPageSize(final Integer pageSize){ + this.pageSize = pageSize; + return this; + } + public RoleAssignmentReader setIdentity(final String identity){ + this.identity = identity; + return this; + } + public RoleAssignmentReader setScope(final String scope){ + this.scope = scope; + return this; + } + + @Override + public ResourceSet read(final BearerTokenTwilioRestClient client) { + return new ResourceSet<>(this, client, firstPage(client)); + } + + public Page firstPage(final BearerTokenTwilioRestClient client) { + String path = "/Organizations/{organizationSid}/RoleAssignments"; + path = path.replace("{"+"organizationSid"+"}", this.pathOrganizationSid.toString()); + + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + Domains.PREVIEWIAM.toString(), + path + ); + + addQueryParams(request); + return pageForRequest(client, request); + } + + private Page pageForRequest(final BearerTokenTwilioRestClient client, final BearerTokenRequest request) { + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("RoleAssignment read failed: Unable to connect to server"); + } else if (!BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return Page.fromJson( + "content", + response.getContent(), + RoleAssignment.class, + client.getObjectMapper() + ); + } + + @Override + public Page previousPage(final Page page, final BearerTokenTwilioRestClient client) { + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) + ); + return pageForRequest(client, request); + } + + + @Override + public Page nextPage(final Page page, final BearerTokenTwilioRestClient client) { + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + page.getNextPageUrl(Domains.PREVIEWIAM.toString()) + ); + return pageForRequest(client, request); + } + + @Override + public Page getPage(final String targetUrl, final BearerTokenTwilioRestClient client) { + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + targetUrl + ); + + return pageForRequest(client, request); + } + private void addQueryParams(final BearerTokenRequest request) { + if (pageSize != null) { + + request.addQueryParam("PageSize", pageSize.toString()); + } + if (identity != null) { + + request.addQueryParam("Identity", identity); + } + if (scope != null) { + + request.addQueryParam("Scope", scope); + } + + if(getPageSize() != null) { + request.addQueryParam("PageSize", Integer.toString(getPageSize())); + } + } +} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/Token.java b/src/main/java/com/twilio/rest/previewiam/organizations/Token.java new file mode 100644 index 0000000000..8f2ea5c879 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/Token.java @@ -0,0 +1,194 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.Resource; +import com.twilio.converter.Converter; +import com.twilio.converter.Converter; +import java.util.Currency; +import com.twilio.converter.DateConverter; +import com.twilio.converter.Promoter; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.CurrencyDeserializer; +import com.twilio.exception.ApiConnectionException; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Request; +import com.twilio.http.Response; +import com.twilio.http.TwilioRestClient; +import com.twilio.rest.Domains; + +import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.time.ZonedDateTime; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.Map; +import java.time.LocalDate; +import java.math.BigDecimal; +import com.twilio.type.PhoneNumberCapabilities; +import com.twilio.type.FeedbackIssue; +import com.twilio.type.IceServer; +import com.twilio.type.InboundCallPrice; +import com.twilio.type.OutboundPrefixPriceWithOrigin; +import com.twilio.type.OutboundPrefixPrice; +import com.twilio.type.OutboundCallPriceWithOrigin; +import com.twilio.type.PhoneNumberPrice; +import com.twilio.type.InboundSmsPrice; +import com.twilio.type.OutboundSmsPrice; +import com.twilio.type.OutboundCallPrice; +import com.twilio.type.RecordingRule; +import com.twilio.type.SubscribeRule; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class Token extends Resource { + private static final long serialVersionUID = 258139119277894L; + + + + public static TokenCreator creator(final String grantType, final String clientId){ + return new TokenCreator(grantType, clientId); + } + + /** + * Converts a JSON String into a Token object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return Token object represented by the provided JSON + */ + public static Token fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Token.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a Token object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return Token object represented by the provided JSON + */ + public static Token fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, Token.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + private final String accessToken; + private final String refreshToken; + private final String idToken; + private final String tokenType; + private final Long expiresIn; + + @JsonCreator + private Token( + @JsonProperty("access_token") + final String accessToken, + + @JsonProperty("refresh_token") + final String refreshToken, + + @JsonProperty("id_token") + final String idToken, + + @JsonProperty("token_type") + final String tokenType, + + @JsonProperty("expires_in") + final Long expiresIn + ) { + this.accessToken = accessToken; + this.refreshToken = refreshToken; + this.idToken = idToken; + this.tokenType = tokenType; + this.expiresIn = expiresIn; + } + + public final String getAccessToken() { + return this.accessToken; + } + public final String getRefreshToken() { + return this.refreshToken; + } + public final String getIdToken() { + return this.idToken; + } + public final String getTokenType() { + return this.tokenType; + } + public final Long getExpiresIn() { + return this.expiresIn; + } + + @Override + public boolean equals(final Object o) { + if (this==o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + Token other = (Token) o; + + return Objects.equals(accessToken, other.accessToken) && Objects.equals(refreshToken, other.refreshToken) && Objects.equals(idToken, other.idToken) && Objects.equals(tokenType, other.tokenType) && Objects.equals(expiresIn, other.expiresIn) ; + } + + @Override + public int hashCode() { + return Objects.hash(accessToken, refreshToken, idToken, tokenType, expiresIn); + } + + +} + diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/TokenCreator.java b/src/main/java/com/twilio/rest/previewiam/organizations/TokenCreator.java new file mode 100644 index 0000000000..710ae3db43 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/TokenCreator.java @@ -0,0 +1,164 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.Creator; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; +import com.twilio.constant.EnumConstants; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.Converter; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.rest.Domains; +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; +import java.time.LocalDate; +import com.twilio.converter.Converter; +import java.time.ZonedDateTime; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.time.format.DateTimeFormatter; +import com.twilio.converter.DateConverter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +import lombok.ToString; + +import java.net.URI; + +public class TokenCreator extends Creator{ + private String grantType; + private String clientId; + private String clientSecret; + private String code; + private String redirectUri; + private String audience; + private String refreshToken; + private String scope; + + public TokenCreator(final String grantType, final String clientId) { + this.grantType = grantType; + this.clientId = clientId; + } + + public TokenCreator setGrantType(final String grantType){ + this.grantType = grantType; + return this; + } + public TokenCreator setClientId(final String clientId){ + this.clientId = clientId; + return this; + } + public TokenCreator setClientSecret(final String clientSecret){ + this.clientSecret = clientSecret; + return this; + } + public TokenCreator setCode(final String code){ + this.code = code; + return this; + } + public TokenCreator setRedirectUri(final String redirectUri){ + this.redirectUri = redirectUri; + return this; + } + public TokenCreator setAudience(final String audience){ + this.audience = audience; + return this; + } + public TokenCreator setRefreshToken(final String refreshToken){ + this.refreshToken = refreshToken; + return this; + } + public TokenCreator setScope(final String scope){ + this.scope = scope; + return this; + } + + @Override + public Token create(final TwilioRestClient client){ + String path = "/v1/token"; + + path = path.replace("{"+"grant_type"+"}", this.grantType.toString()); + path = path.replace("{"+"client_id"+"}", this.clientId.toString()); + + Request request = new Request( + HttpMethod.POST, + Domains.PREVIEWIAM.toString(), + path + ); + request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + addPostParams(request); + Response response = client.request(request); + if (response == null) { + throw new ApiConnectionException("Token creation failed: Unable to connect to server"); + } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return Token.fromJson(response.getStream(), client.getObjectMapper()); + } + private void addPostParams(final Request request) { + if (grantType != null) { + request.addPostParam("grant_type", grantType); + + } + if (clientId != null) { + request.addPostParam("client_id", clientId); + + } + if (clientSecret != null) { + request.addPostParam("client_secret", clientSecret); + + } + if (code != null) { + request.addPostParam("code", code); + + } + if (redirectUri != null) { + request.addPostParam("redirect_uri", redirectUri); + + } + if (audience != null) { + request.addPostParam("audience", audience); + + } + if (refreshToken != null) { + request.addPostParam("refresh_token", refreshToken); + + } + if (scope != null) { + request.addPostParam("scope", scope); + + } + } +} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/User.java b/src/main/java/com/twilio/rest/previewiam/organizations/User.java new file mode 100644 index 0000000000..4598f6cae0 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/User.java @@ -0,0 +1,382 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.bearertoken.Resource; +import com.twilio.converter.Converter; +import java.util.Currency; +import com.twilio.converter.DateConverter; +import com.twilio.converter.Promoter; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.CurrencyDeserializer; +import com.twilio.exception.ApiConnectionException; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; + +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Request; +import com.twilio.http.Response; +import com.twilio.http.TwilioRestClient; +import com.twilio.rest.Domains; + +import lombok.ToString; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.time.ZonedDateTime; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.util.Map; +import java.time.LocalDate; +import java.math.BigDecimal; +import com.twilio.type.PhoneNumberCapabilities; +import com.twilio.type.FeedbackIssue; +import com.twilio.type.IceServer; +import com.twilio.type.InboundCallPrice; +import com.twilio.type.OutboundPrefixPriceWithOrigin; +import com.twilio.type.OutboundPrefixPrice; +import com.twilio.type.OutboundCallPriceWithOrigin; +import com.twilio.type.PhoneNumberPrice; +import com.twilio.type.InboundSmsPrice; +import com.twilio.type.OutboundSmsPrice; +import com.twilio.type.OutboundCallPrice; +import com.twilio.type.RecordingRule; +import com.twilio.type.SubscribeRule; + +@JsonIgnoreProperties(ignoreUnknown = true) +@ToString +public class User extends Resource { + private static final long serialVersionUID = 281207691925540L; + + + @ToString + static public class ScimName { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("givenName") + @Getter @Setter private String givenName; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("familyName") + @Getter @Setter private String familyName; + + + public static ScimName fromJson(String jsonString, ObjectMapper mapper) throws IOException { + return mapper.readValue(jsonString, ScimName.class); + } + } + @ToString + static public class ScimEmailAddress { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("primary") + @Getter @Setter private Boolean primary; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("value") + @Getter @Setter private String value; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("type") + @Getter @Setter private String type; + + + public static ScimEmailAddress fromJson(String jsonString, ObjectMapper mapper) throws IOException { + return mapper.readValue(jsonString, ScimEmailAddress.class); + } + } + @ToString + static public class ScimMeta { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("resourceType") + @Getter @Setter private String resourceType; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("created") + @Getter @Setter private ZonedDateTime created; + public String getCreated() { + return created.toInstant().toString(); + } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("lastModified") + @Getter @Setter private ZonedDateTime lastModified; + public String getLastModified() { + return lastModified.toInstant().toString(); + } + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("version") + @Getter @Setter private String version; + + + public static ScimMeta fromJson(String jsonString, ObjectMapper mapper) throws IOException { + return mapper.readValue(jsonString, ScimMeta.class); + } + } + @ToString + static public class ScimUser { + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("id") + @Getter @Setter private String id; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("externalId") + @Getter @Setter private String externalId; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("userName") + @Getter @Setter private String userName; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("displayName") + @Getter @Setter private String displayName; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("name") + @Getter @Setter private ScimName name; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("emails") + @Getter @Setter private List emails; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("active") + @Getter @Setter private Boolean active; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("locale") + @Getter @Setter private String locale; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("timezone") + @Getter @Setter private String timezone; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("schemas") + @Getter @Setter private List schemas; + + @JsonInclude(JsonInclude.Include.NON_EMPTY) + @JsonProperty("meta") + @Getter @Setter private ScimMeta meta; + + public ScimUser(final String userName ) { + this.userName = userName; + } + + public static ScimUser fromJson(String jsonString, ObjectMapper mapper) throws IOException { + return mapper.readValue(jsonString, ScimUser.class); + } + } + + public static UserCreator creator(final String pathOrganizationSid, final ScimUser scimUser){ + return new UserCreator(pathOrganizationSid, scimUser); + } + + public static UserDeleter deleter(final String pathOrganizationSid, final String pathUserSid){ + return new UserDeleter(pathOrganizationSid, pathUserSid); + } + + public static UserFetcher fetcher(final String pathOrganizationSid, final String pathUserSid){ + return new UserFetcher(pathOrganizationSid, pathUserSid); + } + + public static UserReader reader(final String pathOrganizationSid){ + return new UserReader(pathOrganizationSid); + } + + public static UserUpdater updater(final String pathOrganizationSid, final String pathUserSid, final ScimUser scimUser){ + return new UserUpdater(pathOrganizationSid, pathUserSid, scimUser); + } + + /** + * Converts a JSON String into a User object using the provided ObjectMapper. + * + * @param json Raw JSON String + * @param objectMapper Jackson ObjectMapper + * @return User object represented by the provided JSON + */ + public static User fromJson(final String json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, User.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + + /** + * Converts a JSON InputStream into a User object using the provided + * ObjectMapper. + * + * @param json Raw JSON InputStream + * @param objectMapper Jackson ObjectMapper + * @return User object represented by the provided JSON + */ + public static User fromJson(final InputStream json, final ObjectMapper objectMapper) { + // Convert all checked exceptions to Runtime + try { + return objectMapper.readValue(json, User.class); + } catch (final JsonMappingException | JsonParseException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + public static String toJson(Object object, ObjectMapper mapper) { + try { + return mapper.writeValueAsString(object); + } catch (final JsonMappingException e) { + throw new ApiException(e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ApiException(e.getMessage(), e); + } catch (final IOException e) { + throw new ApiConnectionException(e.getMessage(), e); + } + } + private final String id; + private final String externalId; + private final String userName; + private final String displayName; + private final ScimName name; + private final List emails; + private final Boolean active; + private final String locale; + private final String timezone; + private final List schemas; + private final ScimMeta meta; + + @JsonCreator + private User( + @JsonProperty("id") + final String id, + + @JsonProperty("external_id") + final String externalId, + + @JsonProperty("user_name") + final String userName, + + @JsonProperty("display_name") + final String displayName, + + @JsonProperty("name") + final ScimName name, + + @JsonProperty("emails") + final List emails, + + @JsonProperty("active") + final Boolean active, + + @JsonProperty("locale") + final String locale, + + @JsonProperty("timezone") + final String timezone, + + @JsonProperty("schemas") + final List schemas, + + @JsonProperty("meta") + final ScimMeta meta + ) { + this.id = id; + this.externalId = externalId; + this.userName = userName; + this.displayName = displayName; + this.name = name; + this.emails = emails; + this.active = active; + this.locale = locale; + this.timezone = timezone; + this.schemas = schemas; + this.meta = meta; + } + + public final String getId() { + return this.id; + } + public final String getExternalId() { + return this.externalId; + } + public final String getUserName() { + return this.userName; + } + public final String getDisplayName() { + return this.displayName; + } + public final ScimName getName() { + return this.name; + } + public final List getEmails() { + return this.emails; + } + public final Boolean getActive() { + return this.active; + } + public final String getLocale() { + return this.locale; + } + public final String getTimezone() { + return this.timezone; + } + public final List getSchemas() { + return this.schemas; + } + public final ScimMeta getMeta() { + return this.meta; + } + + @Override + public boolean equals(final Object o) { + if (this==o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + User other = (User) o; + + return Objects.equals(id, other.id) && Objects.equals(externalId, other.externalId) && Objects.equals(userName, other.userName) && Objects.equals(displayName, other.displayName) && Objects.equals(name, other.name) && Objects.equals(emails, other.emails) && Objects.equals(active, other.active) && Objects.equals(locale, other.locale) && Objects.equals(timezone, other.timezone) && Objects.equals(schemas, other.schemas) && Objects.equals(meta, other.meta) ; + } + + @Override + public int hashCode() { + return Objects.hash(id, externalId, userName, displayName, name, emails, active, locale, timezone, schemas, meta); + } + + +} + diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java new file mode 100644 index 0000000000..2db447b998 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java @@ -0,0 +1,102 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.twilio.base.bearertoken.Creator; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.constant.EnumConstants; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.Converter; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.rest.Domains; +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; +import java.time.LocalDate; +import com.twilio.converter.Converter; +import java.time.ZonedDateTime; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.time.format.DateTimeFormatter; +import com.twilio.converter.DateConverter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +import lombok.ToString; + +import java.net.URI; + +public class UserCreator extends Creator{ + private String pathOrganizationSid; + private User.ScimUser scimUser; + + public UserCreator(final String pathOrganizationSid, final User.ScimUser scimUser) { + this.pathOrganizationSid = pathOrganizationSid; + this.scimUser = scimUser; + } + + public UserCreator setScimUser(final User.ScimUser scimUser){ + this.scimUser = scimUser; + return this; + } + + @Override + public User create(final BearerTokenTwilioRestClient client){ + String path = "/Organizations/{organizationSid}/scim/Users"; + + path = path.replace("{"+"organizationSid"+"}", this.pathOrganizationSid.toString()); + path = path.replace("{"+"scimUser"+"}", this.scimUser.toString()); + + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.POST, + Domains.PREVIEWIAM.toString(), + path + ); + request.setContentType(EnumConstants.ContentType.JSON); + addPostParams(request, client); + Response response = client.request(request); + if (response == null) { + throw new ApiConnectionException("User creation failed: Unable to connect to server"); + } else if (!BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return User.fromJson(response.getStream(), client.getObjectMapper()); + } + private void addPostParams(final BearerTokenRequest request, BearerTokenTwilioRestClient client) { + ObjectMapper objectMapper = client.getObjectMapper(); + if (scimUser != null) { + request.setBody(User.toJson(scimUser, objectMapper)); + } + } +} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java new file mode 100644 index 0000000000..152195e5fa --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java @@ -0,0 +1,81 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.twilio.base.bearertoken.Deleter; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.exception.ApiException; +import com.twilio.converter.Converter; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.rest.Domains; +import java.time.LocalDate; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import com.twilio.converter.DateConverter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.ToString; + +public class UserDeleter extends Deleter { + private String pathOrganizationSid; + private String pathUserSid; + + public UserDeleter(final String pathOrganizationSid, final String pathUserSid){ + this.pathOrganizationSid = pathOrganizationSid; + this.pathUserSid = pathUserSid; + } + + + @Override + public boolean delete(final BearerTokenTwilioRestClient client) { + String path = "/Organizations/{organizationSid}/scim/Users/{userSid}"; + + path = path.replace("{"+"organizationSid"+"}", this.pathOrganizationSid.toString()); + path = path.replace("{"+"userSid"+"}", this.pathUserSid.toString()); + + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.DELETE, + Domains.PREVIEWIAM.toString(), + path + ); + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("User delete failed: Unable to connect to server"); + } else if (!BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + return response.getStatusCode() == 204; + } +} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java new file mode 100644 index 0000000000..3fb423c119 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java @@ -0,0 +1,83 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.twilio.base.bearertoken.Fetcher; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.Converter; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.rest.Domains; + +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.time.ZonedDateTime; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import com.twilio.converter.DateConverter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.ToString; + +public class UserFetcher extends Fetcher { + private String pathOrganizationSid; + private String pathUserSid; + + public UserFetcher(final String pathOrganizationSid, final String pathUserSid){ + this.pathOrganizationSid = pathOrganizationSid; + this.pathUserSid = pathUserSid; + } + + + @Override + public User fetch(final BearerTokenTwilioRestClient client) { + String path = "/Organizations/{organizationSid}/scim/Users/{userSid}"; + + path = path.replace("{"+"organizationSid"+"}", this.pathOrganizationSid.toString()); + path = path.replace("{"+"userSid"+"}", this.pathUserSid.toString()); + + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + Domains.PREVIEWIAM.toString(), + path + ); + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("User fetch failed: Unable to connect to server"); + } else if (!BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return User.fromJson(response.getStream(), client.getObjectMapper()); + } +} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java new file mode 100644 index 0000000000..3860024c17 --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java @@ -0,0 +1,139 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.twilio.base.bearertoken.Page; +import com.twilio.base.bearertoken.Reader; +import com.twilio.base.bearertoken.ResourceSet; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.Converter; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.rest.Domains; +import java.time.LocalDate; +import java.time.ZonedDateTime; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.time.format.DateTimeFormatter; +import com.twilio.converter.DateConverter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.ToString; + +public class UserReader extends Reader { + private String pathOrganizationSid; + private String filter; + + public UserReader(final String pathOrganizationSid){ + this.pathOrganizationSid = pathOrganizationSid; + } + + public UserReader setFilter(final String filter){ + this.filter = filter; + return this; + } + + @Override + public ResourceSet read(final BearerTokenTwilioRestClient client) { + return new ResourceSet<>(this, client, firstPage(client)); + } + + public Page firstPage(final BearerTokenTwilioRestClient client) { + String path = "/Organizations/{organizationSid}/scim/Users"; + path = path.replace("{"+"organizationSid"+"}", this.pathOrganizationSid.toString()); + + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + Domains.PREVIEWIAM.toString(), + path + ); + + addQueryParams(request); + return pageForRequest(client, request); + } + + private Page pageForRequest(final BearerTokenTwilioRestClient client, final BearerTokenRequest request) { + Response response = client.request(request); + + if (response == null) { + throw new ApiConnectionException("User read failed: Unable to connect to server"); + } else if (!BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return Page.fromJson( + "Resources", + response.getContent(), + User.class, + client.getObjectMapper() + ); + } + + @Override + public Page previousPage(final Page page, final BearerTokenTwilioRestClient client) { + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) + ); + return pageForRequest(client, request); + } + + + @Override + public Page nextPage(final Page page, final BearerTokenTwilioRestClient client) { + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + page.getNextPageUrl(Domains.PREVIEWIAM.toString()) + ); + return pageForRequest(client, request); + } + + @Override + public Page getPage(final String targetUrl, final BearerTokenTwilioRestClient client) { + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.GET, + targetUrl + ); + + return pageForRequest(client, request); + } + private void addQueryParams(final BearerTokenRequest request) { + if (filter != null) { + + request.addQueryParam("filter", filter); + } + + if(getPageSize() != null) { + request.addQueryParam("PageSize", Integer.toString(getPageSize())); + } + } +} diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java new file mode 100644 index 0000000000..87b4505dda --- /dev/null +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java @@ -0,0 +1,102 @@ +/* + * This code was generated by + * ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + * | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + * | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + * + * Organization Public API + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * NOTE: This class is auto generated by OpenAPI Generator. + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package com.twilio.rest.previewiam.organizations; + +import com.twilio.base.bearertoken.Updater; +import com.twilio.http.bearertoken.BearerTokenRequest; +import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.constant.EnumConstants; +import com.twilio.converter.Promoter; +import com.twilio.exception.ApiConnectionException; +import com.twilio.converter.PrefixedCollapsibleMap; +import com.twilio.converter.Converter; +import com.twilio.exception.ApiException; +import com.twilio.exception.RestException; +import com.twilio.http.HttpMethod; +import com.twilio.http.Response; +import com.twilio.rest.Domains; +import java.time.format.DateTimeFormatter; +import com.twilio.converter.DateConverter; + +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.net.URI; +import java.time.ZonedDateTime; +import java.time.LocalDate; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import lombok.ToString; + +public class UserUpdater extends Updater{ + private String pathOrganizationSid; + private String pathUserSid; + private User.ScimUser scimUser; + private String ifMatch; + + public UserUpdater(final String pathOrganizationSid, final String pathUserSid, final User.ScimUser scimUser){ + this.pathOrganizationSid = pathOrganizationSid; + this.pathUserSid = pathUserSid; + this.scimUser = scimUser; + } + + public UserUpdater setScimUser(final User.ScimUser scimUser){ + this.scimUser = scimUser; + return this; + } + public UserUpdater setIfMatch(final String ifMatch){ + this.ifMatch = ifMatch; + return this; + } + + @Override + public User update(final BearerTokenTwilioRestClient client){ + String path = "/Organizations/{organizationSid}/scim/Users/{userSid}"; + + path = path.replace("{"+"organizationSid"+"}", this.pathOrganizationSid.toString()); + path = path.replace("{"+"userSid"+"}", this.pathUserSid.toString()); + path = path.replace("{"+"scimUser"+"}", this.scimUser.toString()); + + BearerTokenRequest request = new BearerTokenRequest( + HttpMethod.POST, + Domains.PREVIEWIAM.toString(), + path + ); + addHeaderParams(request); + Response response = client.request(request); + if (response == null) { + throw new ApiConnectionException("User update failed: Unable to connect to server"); + } else if (!BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode())) { + RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); + if (restException == null) { + throw new ApiException("Server Error, no content", response.getStatusCode()); + } + throw new ApiException(restException); + } + + return User.fromJson(response.getStream(), client.getObjectMapper()); + } + private void addHeaderParams(final BearerTokenRequest request) { + if (ifMatch != null) { + request.addHeaderParam("If-Match", ifMatch); + + } + } +} diff --git a/src/test/java/com/twilio/ClusterTest.java b/src/test/java/com/twilio/ClusterTest.java index 93a92c4cad..8824d2b012 100644 --- a/src/test/java/com/twilio/ClusterTest.java +++ b/src/test/java/com/twilio/ClusterTest.java @@ -1,6 +1,7 @@ package com.twilio; import com.twilio.base.Page; +import com.twilio.base.bearertoken.ResourceSet; import com.twilio.rest.api.v2010.account.IncomingPhoneNumber; import com.twilio.rest.api.v2010.account.IncomingPhoneNumberReader; import com.twilio.rest.api.v2010.account.Message; @@ -8,21 +9,31 @@ import com.twilio.rest.chat.v2.service.User; import com.twilio.rest.events.v1.Sink; import com.twilio.rest.events.v1.Subscription; +import com.twilio.rest.previewiam.organizations.Account; +import com.twilio.rest.previewiam.organizations.RoleAssignment; +import com.twilio.rest.previewiam.organizations.RoleAssignmentReader; +import com.twilio.rest.previewiam.organizations.Token; import org.hamcrest.CoreMatchers; import org.junit.Assume; import org.junit.Before; import org.junit.Test; +import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; public class ClusterTest { String fromNumber; String toNumber; + String grantType; + String clientId; + String clientSecret; + String organisationSid; @Before public void setUp() { @@ -34,6 +45,12 @@ public void setUp() { String secret = System.getenv("TWILIO_API_SECRET"); String accountSid = System.getenv("TWILIO_ACCOUNT_SID"); Twilio.init(apiKey, secret, accountSid); + + //Secrets required for tests for token based auth flows + grantType = System.getenv("TWILIO_GRANT_TYPE"); + clientId = System.getenv("TWILIO_CLIENT_ID"); + clientSecret = System.getenv("TWILIO_CLIENT_SECRET"); + organisationSid = System.getenv("TWILIO_ORG_SID"); } @Test @@ -107,4 +124,80 @@ public void testListParams() { assertTrue(Sink.deleter(sink.getSid()).delete()); } + public void testOrgsApi() throws IOException { + + + //Getting access token + Token token = Token.creator(grantType, clientId).setClientSecret(clientSecret).create(); + assertNotNull(token); + + //Setting access token + TwilioBearerTokenAuth.init(token.getAccessToken()); + + //Fetching the account information + ResourceSet accountSet = Account.reader(organisationSid).read(); + String accountSid = accountSet.iterator().next().getAccountSid(); + System.out.println(accountSid); + + //Fetching specific account + Account account = Account.fetcher(organisationSid, accountSid).fetch(); + assertNotNull(account.getAccountSid()); + + //Fetching users of this organisation + ResourceSet + userSet = com.twilio.rest.previewiam.organizations.User.reader(organisationSid).read(); + assertNotNull(userSet); + String userId = userSet.iterator().next().getId().toString(); + assertNotNull(userId); + + //Fetch specific user + com.twilio.rest.previewiam.organizations.UserFetcher user = com.twilio.rest.previewiam.organizations.User.fetcher(organisationSid, userId); + com.twilio.rest.previewiam.organizations.User user1 = user.fetch(); + assertNotNull(user1); + + //Create a new user, userName and external id should be unique and new every time we execute this test case +// String userName = "asabuUser210@asabu1.test.twilio.com"; +// com.twilio.rest.previewiam.organizations.User.ScimUser scimUser = new com.twilio.rest.previewiam.organizations.User.ScimUser(userName); +// scimUser.setExternalId("43536374422"); +// com.twilio.rest.previewiam.organizations.User.ScimEmailAddress emailAddress = new com.twilio.rest.previewiam.organizations.User.ScimEmailAddress(); +// emailAddress.setPrimary(true); +// emailAddress.setValue(userName); +// +// +// List listemails; +// listemails = new ArrayList<>(); +// listemails.add(emailAddress); +// scimUser.setEmails(listemails); +// com.twilio.rest.previewiam.organizations.User userNew = com.twilio.rest.previewiam.organizations.User.creator(organisationSid, scimUser).create(); +// System.out.println(userNew.getUserName()); +// +// +// //Update users details +// System.out.println("Executing patches"); +// com.twilio.rest.previewiam.organizations.User.ScimUser uscimUser = new com.twilio.rest.previewiam.organizations.User.ScimUser(userName); +// com.twilio.rest.previewiam.organizations.User.ScimEmailAddress emailAddress1 = new com.twilio.rest.previewiam.organizations.User.ScimEmailAddress(); +// emailAddress1.setPrimary(true); +// emailAddress1.setValue(userName); +// +// +// List listemails1; +// listemails1 = new ArrayList<>(); +// listemails1.add(emailAddress1); +// uscimUser.setEmails(listemails1); +// uscimUser.setDisplayName("Auth1 user test"); +// +// com.twilio.rest.previewiam.organizations.User userUpdated = null; +// userUpdated = com.twilio.rest.previewiam.organizations.User.updater(organisationSid, userId, uscimUser).update(); +// System.out.println(userUpdated.getDisplayName()); +// +// //Delete an existing user +// boolean isDeleted = com.twilio.rest.previewiam.organizations.User.deleter(organisationSid,"US3bdcff893e4f3a91afa1afd742feb1ed").delete(); +// System.out.println("is deleted "+ isDeleted); +// + + + } + + + } From 6bfd0dd06b8c5bce6c62d4dc1d4305b8054515c5 Mon Sep 17 00:00:00 2001 From: AsabuHere Date: Wed, 5 Jun 2024 10:21:49 -0600 Subject: [PATCH 3/3] Handling token expired scenario with a new exception --- .../twilio/http/bearertoken/BearerTokenTwilioRestClient.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java index 376bd58456..65b264c903 100644 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java +++ b/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java @@ -1,6 +1,8 @@ package com.twilio.http.bearertoken; +import static java.time.Instant.now; import com.auth0.jwt.JWT; +import com.auth0.jwt.exceptions.TokenExpiredException; import com.auth0.jwt.interfaces.DecodedJWT; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; @@ -105,7 +107,7 @@ public Response request(BearerTokenRequest request) { } if (isAccessTokenExpired()) { - throw new AuthenticationException("Access Token is expired."); + throw new TokenExpiredException("Access Token is expired.", now()); } request.setAuth(accessToken);