diff --git a/README.md b/README.md index c63cb6461a..c715b3a2fb 100644 --- a/README.md +++ b/README.md @@ -221,8 +221,8 @@ public class Example { We are introducing Client Credentials Flow-based OAuth 2.0 authentication. This feature is currently in `beta` and its implementation is subject to change. -- API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/FetchMessageUsingOAuth.md) -- Organisation API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/BearerTokenAuthentication.md) +- API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/PublicOAuthExample.md) +- Organisation API examples [here](https://github.com/twilio/twilio-java/blob/main/examples/OrgsAPIExample.md) ### Iterate through records diff --git a/examples/BearerTokenAuthentication.md b/examples/BearerTokenAuthentication.md deleted file mode 100644 index 2618436b32..0000000000 --- a/examples/BearerTokenAuthentication.md +++ /dev/null @@ -1,26 +0,0 @@ - class BearerTokenAuthenticationExamples { - public static void main { - - private static final String GRANT_TYPE = "grant_type_to_be_used"; - private static final String CLIENT_SID = - "client_id_of_the_organization"; - private static final String CLIENT_SECRET = "client_secret_of_organization"; - private static final String ORGANISATION_ID = "id_of_the_organization"; - - //Getting access token - Method #1 - TwilioOrgsTokenAuth.init(GRANT_TYPE, CLIENT_ID, CLIENT_SECRET); - - //Getting access token - Method #2 - //To provide custom token manager implementation - //Need not call init method if customer token manager is passed - //TwilioOrgsTokenAuth.setTokenManager(new CustomTokenManagerImpl(GRANT_TYPE, CLIENT_ID, CLIENT_SECRET)); - - fetchAccountDetails(); - } - - private static void fetchAccountDetails() { - ResourceSet accountSet = Account.reader(ORGANISATION_ID).read(); - String accountSid = accountSet.iterator().next().getAccountSid(); - System.out.println(accountSid); - } - } \ No newline at end of file diff --git a/examples/FetchMessageUsingOAuth.md b/examples/FetchMessageUsingOAuth.md deleted file mode 100644 index ec667f1ab0..0000000000 --- a/examples/FetchMessageUsingOAuth.md +++ /dev/null @@ -1,21 +0,0 @@ -``` -import com.twilio.Twilio; -import com.twilio.credential.ClientCredentialProvider; -import com.twilio.rest.api.v2010.account.Message; - -public class FetchMessageUsingOAuth { - public static void main(String[] args) { - String clientId = "YOUR_CLIENT_ID"; - String clientSecret = "YOUR_CLIENT_SECRET"; - String accountSid = "YOUR_ACCOUNT_SID"; - Twilio.init(new ClientCredentialProvider(clientId, clientSecret), accountSid); - /* - Or use the following if accountSid is not required as a path parameter for an API or when setting accountSid in the API. - Twilio.init(new ClientCredentialProvider(clientId, clientSecret)); - */ - String messageSid = "YOUR_MESSAGE_SID"; - Message message = Message.fetcher(messageSid).fetch(); - } -} -``` - diff --git a/examples/OrgsAPIExample.md b/examples/OrgsAPIExample.md new file mode 100644 index 0000000000..b4511f88bc --- /dev/null +++ b/examples/OrgsAPIExample.md @@ -0,0 +1,34 @@ + class OrgsAPIExample { + public static void main { + + private static final String GRANT_TYPE = "grant_type_to_be_used"; + private static final String CLIENT_SID = + "client_id_of_the_organization"; + private static final String CLIENT_SECRET = "client_secret_of_organization"; + private static final String ORGANISATION_ID = "id_of_the_organization"; + + //Getting access token - Method #1 + Twilio.init(new OrgsClientCredentialProvider(CLIENT_SID, CLIENT_SECRET)); + fetchAccountDetails(); + + + //Scenario: 2 If in case one doesn't want to change the existing stored credential + // Pass Custom TwilioRestClient + // TokenManager tokenManager = new OrgsTokenManager(GRANT_TYPE, CLIENT_SID, CLIENT_SECRET); + // TokenAuthStrategy tokenAuthStrategy = new TokenAuthStrategy(tokenManager); + // TwilioRestClient client = new TwilioRestClient.Builder(tokenAuthStrategy).build(); + // fetchAccountDetailsWithClient(client); + } + + private static void fetchAccountDetails() { + ResourceSet accountSet = Account.reader(ORGANISATION_ID).read(); + String accountSid = accountSet.iterator().next().getAccountSid(); + System.out.println(accountSid); + } + + private static void fetchAccountDetailsWithClient(TwilioRestClient client) { + ResourceSet accountSet = Account.reader(ORGANISATION_ID).read(client); + String accountSid = accountSet.iterator().next().getAccountSid(); + System.out.println(accountSid); + } + } \ No newline at end of file diff --git a/examples/PublicOAuthExample.md b/examples/PublicOAuthExample.md new file mode 100644 index 0000000000..dce5027e9a --- /dev/null +++ b/examples/PublicOAuthExample.md @@ -0,0 +1,35 @@ +``` +class PublicOAuthExample { + public static void main { + + private static final String GRANT_TYPE = "grant_type_to_be_used"; + private static final String OAUTH_CLIENT_SID = "client_id"; + private static final String OAUTH_CLIENT_SECRET = "client_secret"; + private static final String ACCOUNT_SID = "account_sid"; + private static final String MESSAGE_SID = "message_sid"; + + //Getting access token - Method #1 + Twilio.init(new ClientCredentialProvider(OAUTH_CLIENT_SID, OAUTH_CLIENT_SECRET), ACCOUNT_SID); + fetchMessage(MESSAGE_SID); + + + //Scenario: 2 If in case one doesn't want to change the existing stored credential + // Pass Custom TwilioRestClient + // TokenManager tokenManager = new ApiTokenManager(GRANT_TYPE, OAUTH_CLIENT_SID, OAUTH_CLIENT_SECRET); + // TokenAuthStrategy tokenAuthStrategy = new TokenAuthStrategy(tokenManager); + // TwilioRestClient client = new TwilioRestClient.Builder(tokenAuthStrategy).accountSid(ACCOUNT_SID).build(); + // fetchMessageWithClient(MESSAGE_SID, client); + } + + public static void fetchMessage(String sid) { + Message message = Message.fetcher(sid).fetch(); + System.out.println("Fetched Message SID: " + message.getSid()); + } + + public static void fetchMessageWithClient(String sid, TwilioRestClient client) { + Message message = Message.fetcher(sid).fetch(client); + System.out.println("Fetched Message SID: " + message.getSid()); + } +} +``` + diff --git a/src/main/java/com/twilio/TwilioOrgsTokenAuth.java b/src/main/java/com/twilio/TwilioOrgsTokenAuth.java deleted file mode 100644 index 9b28d0b06f..0000000000 --- a/src/main/java/com/twilio/TwilioOrgsTokenAuth.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.twilio; - -import com.twilio.annotations.Beta; -import com.twilio.exception.AuthenticationException; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; -import lombok.Getter; -import lombok.Setter; - -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import com.twilio.http.bearertoken.TokenManager; -import com.twilio.http.bearertoken.OrgsTokenManager; - -@Beta -public class TwilioOrgsTokenAuth { - 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; - @Getter @Setter - private static TokenManager tokenManager; - - private static volatile ExecutorService executorService; - - private TwilioOrgsTokenAuth() { - } - - public static synchronized void init(String grantType, String clientId, String clientSecret) { - validateAuthCredentials(grantType, clientId, clientSecret); - tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret); - } - public static synchronized void init(String grantType, String clientId, String clientSecret, String code, String redirectUri, String audience, String refreshToken, String scope) { - validateAuthCredentials(grantType, clientId, clientSecret); - tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret, code, redirectUri, audience, refreshToken, scope); - } - - private static void validateAuthCredentials(String grantType, String clientId, String clientSecret){ - if (grantType == null) { - throw new AuthenticationException("Grant Type cannot be null"); - } - if (clientId == null) { - throw new AuthenticationException("Client Id cannot be null"); - } - if (clientSecret == null) { - throw new AuthenticationException("Client Secret cannot be null"); - } - return; - } - - public static BearerTokenTwilioRestClient getRestClient() { - if (TwilioOrgsTokenAuth.restClient == null) { - synchronized (TwilioOrgsTokenAuth.class) { - if (TwilioOrgsTokenAuth.restClient == null) { - TwilioOrgsTokenAuth.restClient = buildOAuthRestClient(); - } - } - } - return TwilioOrgsTokenAuth.restClient; - } - /** - * Returns the Twilio executor service. - * - * @return the Twilio executor service - */ - public static ExecutorService getExecutorService() { - if (TwilioOrgsTokenAuth.executorService == null) { - synchronized (TwilioOrgsTokenAuth.class) { - if (TwilioOrgsTokenAuth.executorService == null) { - TwilioOrgsTokenAuth.executorService = Executors.newCachedThreadPool(); - } - } - } - return TwilioOrgsTokenAuth.executorService; - } - - private static BearerTokenTwilioRestClient buildOAuthRestClient() { - - BearerTokenTwilioRestClient.Builder builder = new BearerTokenTwilioRestClient.Builder(); - - if (userAgentExtensions != null) { - builder.userAgentExtensions(TwilioOrgsTokenAuth.userAgentExtensions); - } - - builder.region(TwilioOrgsTokenAuth.region); - builder.edge(TwilioOrgsTokenAuth.edge); - if(TwilioOrgsTokenAuth.tokenManager == null){ - throw new AuthenticationException("Either initialize the authentications class or pass a custom token manager"); - } - builder.tokenManager(TwilioOrgsTokenAuth.tokenManager); - - return builder.build(); - } - - /** - * Invalidates the volatile state held in the Twilio singleton. - */ - private static void invalidate() { - TwilioOrgsTokenAuth.restClient = null; - TwilioOrgsTokenAuth.tokenManager = null; - } - - -} \ No newline at end of file diff --git a/src/main/java/com/twilio/base/Page.java b/src/main/java/com/twilio/base/Page.java index b03440007e..259e86e480 100644 --- a/src/main/java/com/twilio/base/Page.java +++ b/src/main/java/com/twilio/base/Page.java @@ -169,8 +169,9 @@ 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()); @@ -192,6 +193,7 @@ private static Page buildNextGenPage(JsonNode root, List results) { } else { builder.pageSize(results.size()); } + } return builder.records(results).build(); } diff --git a/src/main/java/com/twilio/base/bearertoken/Creator.java b/src/main/java/com/twilio/base/bearertoken/Creator.java deleted file mode 100644 index 8cb676cef6..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Creator.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.TwilioOrgsTokenAuth; -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(TwilioOrgsTokenAuth.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), TwilioOrgsTokenAuth.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T create() { - return create(TwilioOrgsTokenAuth.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 deleted file mode 100644 index 3b49cfd0ba..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Deleter.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.Twilio; -import com.twilio.TwilioOrgsTokenAuth; -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(TwilioOrgsTokenAuth.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(TwilioOrgsTokenAuth.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 deleted file mode 100644 index 5654895a3f..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Fetcher.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.TwilioOrgsTokenAuth; -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(TwilioOrgsTokenAuth.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), TwilioOrgsTokenAuth.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T fetch() { - return fetch(TwilioOrgsTokenAuth.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 deleted file mode 100644 index 204c2e98a2..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Page.java +++ /dev/null @@ -1,270 +0,0 @@ -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<>(); - 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 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 deleted file mode 100644 index 15e221a3f9..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Reader.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.TwilioOrgsTokenAuth; -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(TwilioOrgsTokenAuth.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(TwilioOrgsTokenAuth.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), TwilioOrgsTokenAuth.getExecutorService()); - } - - /** - * Fetch the first page of resources. - * - * @return Page containing the first pageSize of resources - */ - public Page firstPage() { - return firstPage(TwilioOrgsTokenAuth.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, TwilioOrgsTokenAuth.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, TwilioOrgsTokenAuth.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, TwilioOrgsTokenAuth.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 deleted file mode 100644 index 08dc228556..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Resource.java +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 4cc09d8c2d..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/ResourceSet.java +++ /dev/null @@ -1,138 +0,0 @@ -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 final Page firstPage; // Store reference to first page to enable multiple iterations - - 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.firstPage = page; // Save first page to allow resetting iterator state - 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() { - // Reset state to allow multiple iterations - this.processed = 0; - this.pages = 1; - this.page = this.firstPage; // Reset to first page for new iteration - this.iterator = this.firstPage.getRecords().iterator(); // Reset iterator to start of first page - - 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 deleted file mode 100644 index 690e3604c5..0000000000 --- a/src/main/java/com/twilio/base/bearertoken/Updater.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.twilio.base.bearertoken; - -import com.twilio.TwilioOrgsTokenAuth; -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(TwilioOrgsTokenAuth.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), TwilioOrgsTokenAuth.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T update() { - return update(TwilioOrgsTokenAuth.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/credential/orgs/OrgsClientCredentialProvider.java b/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java index 9d5687a64a..5d93404bc6 100644 --- a/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java +++ b/src/main/java/com/twilio/credential/orgs/OrgsClientCredentialProvider.java @@ -1,4 +1,64 @@ package com.twilio.credential.orgs; -public class OrgsClientCredentialProvider { +import com.twilio.auth_strategy.AuthStrategy; +import com.twilio.auth_strategy.TokenAuthStrategy; +import com.twilio.constant.EnumConstants; +import com.twilio.credential.CredentialProvider; +import com.twilio.exception.AuthenticationException; +import com.twilio.http.bearertoken.OrgsTokenManager; +import com.twilio.http.bearertoken.TokenManager; + +import java.util.Objects; + +public class OrgsClientCredentialProvider extends CredentialProvider { + private String grantType; + private String clientId; + private String clientSecret; + private TokenManager tokenManager; + + public OrgsClientCredentialProvider(String clientId, String clientSecret) { + super(EnumConstants.AuthType.CLIENT_CREDENTIALS); + if (clientId == null || clientSecret == null) { + throw new AuthenticationException("ClientId or ClientSecret can not be null"); + } + this.grantType = "client_credentials"; + this.clientId = clientId; + this.clientSecret = clientSecret; + this.tokenManager = null; + } + + public OrgsClientCredentialProvider(String clientId, String clientSecret, TokenManager tokenManager) { + super(EnumConstants.AuthType.CLIENT_CREDENTIALS); + if (clientId == null || clientSecret == null || tokenManager == null) { + throw new AuthenticationException("ClientId or ClientSecret or TokenManager can not be null"); + } + this.grantType = "client_credentials"; + this.clientId = clientId; + this.clientSecret = clientSecret; + this.tokenManager = tokenManager; + } + + @Override + public AuthStrategy toAuthStrategy() { + if (tokenManager == null) { + tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret); + } + return new TokenAuthStrategy(tokenManager); + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + + if (o == null || getClass() != o.getClass()) { + return false; + } + + OrgsClientCredentialProvider other = (OrgsClientCredentialProvider) o; + return Objects.equals(clientId, other.clientId) && + Objects.equals(clientSecret, other.clientSecret) && + Objects.equals(tokenManager, other.tokenManager); + } } diff --git a/src/main/java/com/twilio/http/NetworkHttpClient.java b/src/main/java/com/twilio/http/NetworkHttpClient.java index 8c1b0dad85..0d40e4cb8c 100644 --- a/src/main/java/com/twilio/http/NetworkHttpClient.java +++ b/src/main/java/com/twilio/http/NetworkHttpClient.java @@ -72,7 +72,7 @@ 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"), + // The Accept header is intentionally omitted to support both SCIM and JSON content types. new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") ); diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java deleted file mode 100644 index 0c405769bf..0000000000 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenHttpClient.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.twilio.http.bearertoken; - -import com.twilio.http.HttpClient; -import com.twilio.http.Request; -import com.twilio.http.Response; -import lombok.Getter; -import lombok.Setter; -import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.impl.DefaultRedirectStrategy; -import org.apache.hc.client5.http.protocol.RedirectStrategy; -import org.apache.hc.core5.http.io.SocketConfig; - -public abstract class BearerTokenHttpClient { - // Use constants from HttpClient - public static final RequestConfig DEFAULT_REQUEST_CONFIG = RequestConfig - .custom() - .setConnectTimeout(HttpClient.CONNECTION_TIMEOUT) - .build(); - public static final SocketConfig DEFAULT_SOCKET_CONFIG = SocketConfig - .custom() - .setSoTimeout(HttpClient.SOCKET_TIMEOUT) - .build(); - @Getter - @Setter - private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - - @Getter - private Response lastResponse; - @Getter - private BearerTokenRequest lastRequest; - - public Response reliableRequest(final BearerTokenRequest request) { - return reliableRequest(request, HttpClient.RETRY_CODES, HttpClient.RETRIES, HttpClient.DELAY_MILLIS); - } - - public Response reliableRequest(final BearerTokenRequest request, final int[] retryCodes, int retries, - final long delayMillis) { - lastRequest = request; - Response response = null; - while (retries > 0) { - response = makeRequest(request); - - if (!shouldRetry(response, retryCodes)) { - break; - } - - try { - Thread.sleep(delayMillis); - } catch (final InterruptedException e) { - // Delay failed, continue - } - - // Decrement retries - retries--; - } - - lastResponse = response; - - return response; - } - - protected boolean shouldRetry(final Response response, final int[] retryCodes) { - if (response == null) { - return true; - } - - int statusCode = response.getStatusCode(); - int category = (int) Math.floor(statusCode / 100.0); - - for (final int retryCode : retryCodes) { - switch (retryCode) { - case HttpClient.ANY_100: - if (category == 1) { - return true; - } - break; - case HttpClient.ANY_200: - if (category == 2) { - return true; - } - break; - case HttpClient.ANY_300: - if (category == 3) { - return true; - } - break; - case HttpClient.ANY_400: - if (category == 4) { - return true; - } - break; - case HttpClient.ANY_500: - if (category == 5) { - return true; - } - break; - default: - if (statusCode == retryCode) { - return true; - } - break; - } - } - return false; - } - - public abstract Response makeRequest(final BearerTokenRequest request); -} diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java deleted file mode 100644 index 9d80666640..0000000000 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenNetworkHttpClient.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.twilio.http.bearertoken; - -import com.twilio.Twilio; -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiException; -import com.twilio.http.HttpMethod; -import com.twilio.http.HttpUtility; -import com.twilio.http.Response; -import java.util.ArrayList; -import java.util.Map.Entry; -import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; -import org.apache.hc.client5.http.config.RequestConfig; -import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; -import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; -import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; -import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; -import org.apache.hc.core5.http.ContentType; -import org.apache.hc.core5.http.HttpEntity; -import org.apache.hc.core5.http.HttpHeaders; -import org.apache.hc.core5.http.NameValuePair; -import org.apache.hc.core5.http.io.SocketConfig; -import org.apache.hc.core5.http.io.entity.BufferedHttpEntity; -import org.apache.hc.core5.http.io.entity.StringEntity; -import org.apache.hc.core5.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; -import org.apache.hc.core5.http.message.BasicNameValuePair; -import static com.twilio.http.HttpClient.createHttpUriRequestBase; - -public class BearerTokenNetworkHttpClient extends BearerTokenHttpClient { - - protected final CloseableHttpClient client; - - private boolean isCustomClient; - - /** - * Create a new HTTP Client. - */ - public BearerTokenNetworkHttpClient() { - this(DEFAULT_REQUEST_CONFIG); - } - - /** - * Create a new HTTP Client with a custom request config. - * - * @param requestConfig a RequestConfig. - */ - public BearerTokenNetworkHttpClient(final RequestConfig requestConfig) { - this(requestConfig, DEFAULT_SOCKET_CONFIG); - } - - /** - * Create a new HTTP Client with a custom request and socket config. - * - * @param requestConfig a RequestConfig. - * @param socketConfig a SocketConfig. - */ - public BearerTokenNetworkHttpClient(final RequestConfig requestConfig, final SocketConfig socketConfig) { - Collection headers = Arrays.asList( - new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), - //new BasicHeader(HttpHeaders.ACCEPT, "application/json"), Orgs API has scim or json support. - new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") - ); - - String googleAppEngineVersion = System.getProperty("com.google.appengine.runtime.version"); - boolean isGoogleAppEngine = googleAppEngineVersion != null && !googleAppEngineVersion.isEmpty(); - - 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(); - } - - /** - * Create a new HTTP Client using custom configuration. - * @param clientBuilder an HttpClientBuilder. - */ - public BearerTokenNetworkHttpClient(HttpClientBuilder clientBuilder) { - Collection headers = Arrays.asList( - new BasicHeader("X-Twilio-Client", "java-" + Twilio.VERSION), - //new BasicHeader(HttpHeaders.ACCEPT, "application/json"), Orgs API has scim or json support. - new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "utf-8") - ); - isCustomClient = true; - - client = clientBuilder - .setDefaultRequestConfig(DEFAULT_REQUEST_CONFIG) - .setDefaultHeaders(headers) - .setRedirectStrategy(this.getRedirectStrategy()) - .build(); - } - - /** - * Make a request. - * - * @param request request to make - * @return Response of the HTTP request - */ - public Response makeRequest(final BearerTokenRequest request) { - - HttpMethod method = request.getMethod(); - HttpUriRequestBase httpUriRequestBase = createHttpUriRequestBase(request); - - - if (request.requiresAuthentication()) { - httpUriRequestBase.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString()); - } - - for (Map.Entry> entry : request.getHeaderParams().entrySet()) { - for (String value : entry.getValue()) { - httpUriRequestBase.addHeader(entry.getKey(), value); - } - } - - if (method != HttpMethod.GET) { - // 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); - httpUriRequestBase.setEntity(entity); - httpUriRequestBase.addHeader( - HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.JSON.getValue()); - } else { - httpUriRequestBase.addHeader( - HttpHeaders.CONTENT_TYPE, EnumConstants.ContentType.FORM_URLENCODED.getValue()); - // Create your form parameters - List formParams = new ArrayList<>(); - for ( Entry> entry : request.getPostParams().entrySet()) { - for (String value : entry.getValue()) { - formParams.add(new BasicNameValuePair(entry.getKey(), value)); - } - } - - // Build the entity with URL form encoded parameters - UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8); - // Set the entity on the request - httpUriRequestBase.setEntity(formEntity); - } - - } - httpUriRequestBase.addHeader(HttpHeaders.USER_AGENT, HttpUtility.getUserAgentString(request.getUserAgentExtensions(), isCustomClient)); - - try { - CloseableHttpResponse response = client.execute(httpUriRequestBase); - HttpEntity entity = response.getEntity(); - return new Response( - // Consume the entire HTTP response before returning the stream - entity == null ? null : new BufferedHttpEntity(entity).getContent(), - response.getCode(), - response.getHeaders() - ); - } catch (IOException e) { - throw new ApiException(e.getMessage(), e); - } - } -} diff --git a/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java b/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java deleted file mode 100644 index 83976c2e45..0000000000 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenRequest.java +++ /dev/null @@ -1,38 +0,0 @@ -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 deleted file mode 100644 index c7da1ff2b0..0000000000 --- a/src/main/java/com/twilio/http/bearertoken/BearerTokenTwilioRestClient.java +++ /dev/null @@ -1,186 +0,0 @@ -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.http.Response; -import lombok.Getter; -import lombok.Setter; -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 String accessToken; - @Getter - private final String region; - @Getter - private final String edge; - @Getter - private final BearerTokenHttpClient httpClient; - @Getter - private final List userAgentExtensions; - @Setter - private final TokenManager tokenManager; - private static final Logger logger = LoggerFactory.getLogger(BearerTokenTwilioRestClient.class); - - private BearerTokenTwilioRestClient(BearerTokenTwilioRestClient.Builder b) { - this.region = b.region; - this.edge = b.edge; - this.httpClient = b.httpClient; - this.objectMapper = b.objectMapper; - this.userAgentExtensions = b.userAgentExtensions; - this.tokenManager = b.tokenManager; - } - - public static class Builder { - // 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+ - private static final ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapper() - .registerModule(new JavaTimeModule()); - - private String region; - private String edge; - private BearerTokenHttpClient httpClient; - private List userAgentExtensions; - private TokenManager tokenManager; - private ObjectMapper objectMapper = DEFAULT_OBJECT_MAPPER; - - public Builder() { - 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 tokenManager(final TokenManager tokenManager) { - this.tokenManager = tokenManager; - return this; - } - - public BearerTokenTwilioRestClient.Builder httpClient(final BearerTokenHttpClient 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.Builder objectMapper(final ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - return this; - } - - public BearerTokenTwilioRestClient build() { - if (this.httpClient == null) { - this.httpClient = new BearerTokenNetworkHttpClient(); - } - return new BearerTokenTwilioRestClient(this); - } - } - public Response request(BearerTokenRequest request) { - - if (accessToken == null || accessToken.isEmpty() || isTokenExpired(this.accessToken)) { - synchronized (BearerTokenTwilioRestClient.class){ - if (accessToken == null || accessToken.isEmpty() || isTokenExpired(this.accessToken)) { - this.accessToken = tokenManager.fetchAccessToken(); - } - } - } - - 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(response != null) { - int statusCode = response.getStatusCode(); - if (statusCode == 401) { - this.accessToken = tokenManager.fetchAccessToken(); - request.setAuth(accessToken); - response = httpClient.reliableRequest(request); - } - - if (logger.isDebugEnabled()) { - logger.debug("status code: {}", statusCode); - org.apache.hc.core5.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 isTokenExpired(String token) { - DecodedJWT jwt = JWT.decode(token); - 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/rest/previewiam/organizations/Account.java b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java index 388b31fa34..bffd937287 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/Account.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/Account.java @@ -20,7 +20,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Resource; +import com.twilio.base.Resource; import com.twilio.converter.DateConverter; import com.twilio.converter.Promoter; import com.twilio.exception.ApiConnectionException; diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java b/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java index 57dc7b088e..1949891f1d 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/AccountFetcher.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Fetcher; +import com.twilio.base.Fetcher; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; 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.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class AccountFetcher extends Fetcher { @@ -39,7 +39,7 @@ public AccountFetcher( } @Override - public Account fetch(final BearerTokenTwilioRestClient client) { + public Account fetch(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/Accounts/{AccountSid}"; path = @@ -53,7 +53,7 @@ public Account fetch(final BearerTokenTwilioRestClient client) { this.pathAccountSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -66,7 +66,7 @@ public Account fetch(final BearerTokenTwilioRestClient client) { "Account fetch failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java index 5ad736ac13..7c2a384f3f 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/AccountReader.java @@ -14,17 +14,17 @@ 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.base.Page; +import com.twilio.base.Reader; +import com.twilio.base.ResourceSet; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; 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.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class AccountReader extends Reader { @@ -42,11 +42,11 @@ public AccountReader setPageSize(final Integer pageSize) { } @Override - public ResourceSet read(final BearerTokenTwilioRestClient client) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage(final BearerTokenTwilioRestClient client) { + public Page firstPage(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/Accounts"; path = path.replace( @@ -54,7 +54,7 @@ public Page firstPage(final BearerTokenTwilioRestClient client) { this.pathOrganizationSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -66,8 +66,8 @@ public Page firstPage(final BearerTokenTwilioRestClient client) { } private Page pageForRequest( - final BearerTokenTwilioRestClient client, - final BearerTokenRequest request + final TwilioRestClient client, + final Request request ) { Response response = client.request(request); @@ -76,7 +76,7 @@ private Page pageForRequest( "Account read failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -102,9 +102,9 @@ private Page pageForRequest( @Override public Page previousPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -114,9 +114,9 @@ public Page previousPage( @Override public Page nextPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getNextPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -126,9 +126,9 @@ public Page nextPage( @Override public Page getPage( final String targetUrl, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, targetUrl ); @@ -136,7 +136,7 @@ public Page getPage( return pageForRequest(client, request); } - private void addQueryParams(final BearerTokenRequest request) { + private void addQueryParams(final Request request) { if (pageSize != null) { request.addQueryParam("PageSize", pageSize.toString()); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java index 875068a004..882781fe09 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignment.java @@ -22,7 +22,7 @@ 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.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java index e95e19a4b1..1a22c181ed 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentCreator.java @@ -15,15 +15,15 @@ package com.twilio.rest.previewiam.organizations; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Creator; +import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; 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.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentCreator extends Creator { @@ -49,7 +49,7 @@ public RoleAssignmentCreator setPublicApiCreateRoleAssignmentRequest( } @Override - public RoleAssignment create(final BearerTokenTwilioRestClient client) { + public RoleAssignment create(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/RoleAssignments"; path = @@ -63,7 +63,7 @@ public RoleAssignment create(final BearerTokenTwilioRestClient client) { this.publicApiCreateRoleAssignmentRequest.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.POST, Domains.PREVIEWIAM.toString(), path @@ -76,7 +76,7 @@ public RoleAssignment create(final BearerTokenTwilioRestClient client) { "RoleAssignment creation failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -98,8 +98,8 @@ public RoleAssignment create(final BearerTokenTwilioRestClient client) { } private void addPostParams( - final BearerTokenRequest request, - BearerTokenTwilioRestClient client + final Request request, + TwilioRestClient client ) { ObjectMapper objectMapper = client.getObjectMapper(); if (publicApiCreateRoleAssignmentRequest != null) { diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java index 43cc107708..514bacadf6 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentDeleter.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Deleter; +import com.twilio.base.Deleter; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentDeleter extends Deleter { @@ -39,7 +39,7 @@ public RoleAssignmentDeleter( } @Override - public boolean delete(final BearerTokenTwilioRestClient client) { + public boolean delete(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/RoleAssignments/{RoleAssignmentSid}"; @@ -54,7 +54,7 @@ public boolean delete(final BearerTokenTwilioRestClient client) { this.pathRoleAssignmentSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.DELETE, Domains.PREVIEWIAM.toString(), path @@ -67,7 +67,7 @@ public boolean delete(final BearerTokenTwilioRestClient client) { "RoleAssignment delete failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java index 05bb8e8b81..e10fca0991 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/RoleAssignmentReader.java @@ -14,17 +14,17 @@ 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.base.Page; +import com.twilio.base.Reader; +import com.twilio.base.ResourceSet; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class RoleAssignmentReader extends Reader { @@ -55,13 +55,13 @@ public RoleAssignmentReader setScope(final String scope) { @Override public ResourceSet read( - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { return new ResourceSet<>(this, client, firstPage(client)); } public Page firstPage( - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { String path = "/Organizations/{OrganizationSid}/RoleAssignments"; path = @@ -70,7 +70,7 @@ public Page firstPage( this.pathOrganizationSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -82,8 +82,8 @@ public Page firstPage( } private Page pageForRequest( - final BearerTokenTwilioRestClient client, - final BearerTokenRequest request + final TwilioRestClient client, + final Request request ) { Response response = client.request(request); @@ -92,7 +92,7 @@ private Page pageForRequest( "RoleAssignment read failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -118,9 +118,9 @@ private Page pageForRequest( @Override public Page previousPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -130,9 +130,9 @@ public Page previousPage( @Override public Page nextPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getNextPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -142,9 +142,9 @@ public Page nextPage( @Override public Page getPage( final String targetUrl, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, targetUrl ); @@ -152,7 +152,7 @@ public Page getPage( return pageForRequest(client, request); } - private void addQueryParams(final BearerTokenRequest request) { + private void addQueryParams(final Request request) { if (pageSize != null) { request.addQueryParam("PageSize", pageSize.toString()); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/User.java b/src/main/java/com/twilio/rest/previewiam/organizations/User.java index 2e3a501701..94359dbbbf 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/User.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/User.java @@ -22,7 +22,7 @@ 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.base.Resource; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import java.io.IOException; diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java index 92d390ed29..e768088a50 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserCreator.java @@ -15,15 +15,15 @@ package com.twilio.rest.previewiam.organizations; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Creator; +import com.twilio.base.Creator; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.TwilioRestClient; +import com.twilio.http.Request; import com.twilio.rest.Domains; public class UserCreator extends Creator { @@ -45,7 +45,7 @@ public UserCreator setScimUser(final User.ScimUser scimUser) { } @Override - public User create(final BearerTokenTwilioRestClient client) { + public User create(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users"; path = @@ -55,7 +55,7 @@ public User create(final BearerTokenTwilioRestClient client) { ); path = path.replace("{" + "ScimUser" + "}", this.scimUser.toString()); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.POST, Domains.PREVIEWIAM.toString(), path @@ -68,7 +68,7 @@ public User create(final BearerTokenTwilioRestClient client) { "User creation failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -87,8 +87,8 @@ public User create(final BearerTokenTwilioRestClient client) { } private void addPostParams( - final BearerTokenRequest request, - BearerTokenTwilioRestClient client + final Request request, + TwilioRestClient client ) { ObjectMapper objectMapper = client.getObjectMapper(); if (scimUser != null) { diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java index 6f44db1c69..dcb8c56787 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserDeleter.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Deleter; +import com.twilio.base.Deleter; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserDeleter extends Deleter { @@ -39,7 +39,7 @@ public UserDeleter( } @Override - public boolean delete(final BearerTokenTwilioRestClient client) { + public boolean delete(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; path = @@ -49,7 +49,7 @@ public boolean delete(final BearerTokenTwilioRestClient client) { ); path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.DELETE, Domains.PREVIEWIAM.toString(), path @@ -62,7 +62,7 @@ public boolean delete(final BearerTokenTwilioRestClient client) { "User delete failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java index 3abc3e86eb..0270ac88dc 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserFetcher.java @@ -14,15 +14,15 @@ package com.twilio.rest.previewiam.organizations; -import com.twilio.base.bearertoken.Fetcher; +import com.twilio.base.Fetcher; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserFetcher extends Fetcher { @@ -39,7 +39,7 @@ public UserFetcher( } @Override - public User fetch(final BearerTokenTwilioRestClient client) { + public User fetch(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; path = @@ -49,7 +49,7 @@ public User fetch(final BearerTokenTwilioRestClient client) { ); path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -62,7 +62,7 @@ public User fetch(final BearerTokenTwilioRestClient client) { "User fetch failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java index 2ebdb45da6..c6bb6a57eb 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserReader.java @@ -14,17 +14,17 @@ 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.base.Page; +import com.twilio.base.Reader; +import com.twilio.base.ResourceSet; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserReader extends Reader { @@ -42,11 +42,11 @@ public UserReader setFilter(final String filter) { } @Override - public ResourceSet read(final BearerTokenTwilioRestClient client) { + public ResourceSet read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); } - public Page firstPage(final BearerTokenTwilioRestClient client) { + public Page firstPage(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users"; path = path.replace( @@ -54,7 +54,7 @@ public Page firstPage(final BearerTokenTwilioRestClient client) { this.pathOrganizationSid.toString() ); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path @@ -66,8 +66,8 @@ public Page firstPage(final BearerTokenTwilioRestClient client) { } private Page pageForRequest( - final BearerTokenTwilioRestClient client, - final BearerTokenRequest request + final TwilioRestClient client, + final Request request ) { Response response = client.request(request); @@ -76,7 +76,7 @@ private Page pageForRequest( "User read failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -102,9 +102,9 @@ private Page pageForRequest( @Override public Page previousPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getPreviousPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -114,9 +114,9 @@ public Page previousPage( @Override public Page nextPage( final Page page, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, page.getNextPageUrl(Domains.PREVIEWIAM.toString()) ); @@ -126,9 +126,9 @@ public Page nextPage( @Override public Page getPage( final String targetUrl, - final BearerTokenTwilioRestClient client + final TwilioRestClient client ) { - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.GET, targetUrl ); @@ -136,7 +136,7 @@ public Page getPage( return pageForRequest(client, request); } - private void addQueryParams(final BearerTokenRequest request) { + private void addQueryParams(final Request request) { if (filter != null) { request.addQueryParam("filter", filter); } diff --git a/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java b/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java index b68b8557f0..9b3c2a0d4b 100644 --- a/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java +++ b/src/main/java/com/twilio/rest/previewiam/organizations/UserUpdater.java @@ -15,15 +15,15 @@ package com.twilio.rest.previewiam.organizations; import com.fasterxml.jackson.databind.ObjectMapper; -import com.twilio.base.bearertoken.Updater; +import com.twilio.base.Updater; import com.twilio.constant.EnumConstants; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenRequest; -import com.twilio.http.bearertoken.BearerTokenTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class UserUpdater extends Updater { @@ -54,7 +54,7 @@ public UserUpdater setIfMatch(final String ifMatch) { } @Override - public User update(final BearerTokenTwilioRestClient client) { + public User update(final TwilioRestClient client) { String path = "/Organizations/{OrganizationSid}/scim/Users/{UserSid}"; path = @@ -65,7 +65,7 @@ public User update(final BearerTokenTwilioRestClient client) { path = path.replace("{" + "UserSid" + "}", this.pathUserSid.toString()); path = path.replace("{" + "ScimUser" + "}", this.scimUser.toString()); - BearerTokenRequest request = new BearerTokenRequest( + Request request = new Request( HttpMethod.PUT, Domains.PREVIEWIAM.toString(), path @@ -79,7 +79,7 @@ public User update(final BearerTokenTwilioRestClient client) { "User update failed: Unable to connect to server" ); } else if ( - !BearerTokenTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -98,8 +98,8 @@ public User update(final BearerTokenTwilioRestClient client) { } private void addPostParams( - final BearerTokenRequest request, - BearerTokenTwilioRestClient client + final Request request, + TwilioRestClient client ) { ObjectMapper objectMapper = client.getObjectMapper(); if (scimUser != null) { @@ -107,7 +107,7 @@ private void addPostParams( } } - private void addHeaderParams(final BearerTokenRequest request) { + private void addHeaderParams(final Request 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 50062a5486..e21df98c3a 100644 --- a/src/test/java/com/twilio/ClusterTest.java +++ b/src/test/java/com/twilio/ClusterTest.java @@ -1,10 +1,12 @@ package com.twilio; +import com.twilio.auth_strategy.TokenAuthStrategy; import com.twilio.base.Page; -import com.twilio.base.bearertoken.ResourceSet; -import com.twilio.credential.ClientCredentialProvider; +import com.twilio.base.ResourceSet; import com.twilio.http.CustomHttpClient; import com.twilio.http.TwilioRestClient; +import com.twilio.http.bearertoken.OrgsTokenManager; +import com.twilio.http.bearertoken.TokenManager; import com.twilio.rest.api.v2010.account.IncomingPhoneNumber; import com.twilio.rest.api.v2010.account.IncomingPhoneNumberReader; import com.twilio.rest.api.v2010.account.Message; @@ -57,8 +59,7 @@ public void setUp() { orgsClientId = System.getenv("TWILIO_ORGS_CLIENT_ID"); orgsClientSecret = System.getenv("TWILIO_ORGS_CLIENT_SECRET"); organisationSid = System.getenv("TWILIO_ORG_SID"); - TwilioOrgsTokenAuth.init(grantType, orgsClientId, orgsClientSecret); - + clientId = System.getenv("TWILIO_CLIENT_ID"); clientSecret = System.getenv("TWILIO_CLIENT_SECRET"); messageSid = System.getenv("TWILIO_MESSAGE_SID"); @@ -140,19 +141,25 @@ public void testListParams() { @Test public void testOrgsApi(){ + //Twilio.init(new OrgsClientCredentialProvider(orgsClientId, orgsClientSecret)); + + TokenManager tokenManager = new OrgsTokenManager("client_credentials", orgsClientId, orgsClientSecret); + TokenAuthStrategy tokenAuthStrategy = new TokenAuthStrategy(tokenManager); + TwilioRestClient client = new TwilioRestClient.Builder(tokenAuthStrategy) + .build(); //Fetching the account information - ResourceSet accountSet = Account.reader(organisationSid).read(); + ResourceSet accountSet = Account.reader(organisationSid).read(client); String accountSid = accountSet.iterator().next().getAccountSid(); assertNotNull(accountSid); //Fetching specific account - Account account = Account.fetcher(organisationSid, accountSid).fetch(); + Account account = Account.fetcher(organisationSid, accountSid).fetch(client); assertNotNull(account.getAccountSid()); //Fetching users of this organisation ResourceSet - userSet = com.twilio.rest.previewiam.organizations.User.reader(organisationSid).read(); + userSet = com.twilio.rest.previewiam.organizations.User.reader(organisationSid).read(client); assertNotNull(userSet); String userId = userSet.iterator().next().getId().toString(); assertNotNull(userId); diff --git a/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java b/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java deleted file mode 100644 index 41094c2ff6..0000000000 --- a/src/test/java/com/twilio/http/bearerToken/BearerTokenNetworkHttpClientTest.java +++ /dev/null @@ -1,213 +0,0 @@ -package com.twilio.http.bearerToken; - -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Response; -import com.twilio.http.bearertoken.BearerTokenNetworkHttpClient; -import com.twilio.http.bearertoken.BearerTokenRequest; -import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; -import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; -import org.apache.hc.core5.http.HttpEntity; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class BearerTokenNetworkHttpClientTest { - - private BearerTokenNetworkHttpClient client; - - @Mock - private BearerTokenRequest mockRequest; - - @Spy - private HttpClientBuilder mockBuilder; - - @Mock - private CloseableHttpClient mockClient; - - @Mock - private CloseableHttpResponse mockResponse; - - @Mock - private HttpEntity mockEntity; - - @Before - public void setUp() { - MockitoAnnotations.openMocks(this); - doReturn(mockClient).when(mockBuilder).build(); - client = new BearerTokenNetworkHttpClient(mockBuilder); - } - - private void setup( - final int statusCode, - final String content, - final HttpMethod method, - final Boolean requiresAuthentication - ) throws IOException { - final InputStream stream = new ByteArrayInputStream(content.getBytes("UTF-8")); - - when(mockRequest.getMethod()).thenReturn(method); - when(mockRequest.constructURL()).thenReturn(new URL("http://foo.com/hello")); - when(mockRequest.requiresAuthentication()).thenReturn(requiresAuthentication); - when(mockRequest.getAuthString()).thenReturn("Bearer token123"); - when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.FORM_URLENCODED); - when(mockClient.execute(any())).thenReturn(mockResponse); - when(mockEntity.isRepeatable()).thenReturn(true); - when(mockEntity.getContentLength()).thenReturn(1L); - when(mockEntity.getContent()).thenReturn(stream); - when(mockResponse.getEntity()).thenReturn(mockEntity); - when(mockResponse.getCode()).thenReturn(statusCode); - } - - @Test - public void testGet() throws IOException { - setup(200, "success", HttpMethod.GET, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("success", resp.getContent()); - } - - @Test - public void testGetWithAuthentication() throws IOException { - setup(200, "authenticated", HttpMethod.GET, true); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("authenticated", resp.getContent()); - } - - @Test - public void testPost() throws IOException { - setup(201, "created", HttpMethod.POST, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(201, resp.getStatusCode()); - assertEquals("created", resp.getContent()); - } - - @Test - public void testJsonPost() throws IOException { - setup(201, "created", HttpMethod.POST, false); - when(mockRequest.getContentType()).thenReturn(EnumConstants.ContentType.JSON); - String body = "{\"name\":\"value\"}"; - when(mockRequest.getBody()).thenReturn(body); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(201, resp.getStatusCode()); - assertEquals("created", resp.getContent()); - } - - @Test - public void testFormUrlEncodedPost() throws IOException { - setup(201, "form-urlencoded", HttpMethod.POST, false); - - // Set up post parameters - Map> postParams = new HashMap<>(); - postParams.put("name", Arrays.asList("John Doe")); - postParams.put("tags", Arrays.asList("customer", "premium")); - when(mockRequest.getPostParams()).thenReturn(postParams); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(201, resp.getStatusCode()); - assertEquals("form-urlencoded", resp.getContent()); - } - - @Test - public void testPut() throws IOException { - setup(200, "updated", HttpMethod.PUT, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("updated", resp.getContent()); - } - - @Test - public void testPatch() throws IOException { - setup(200, "patched", HttpMethod.PATCH, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("patched", resp.getContent()); - } - - @Test - public void testDelete() throws IOException { - setup(204, "", HttpMethod.DELETE, false); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(204, resp.getStatusCode()); - assertEquals("", resp.getContent()); - } - - @Test - public void testWithCustomHeaders() throws IOException { - setup(200, "headers", HttpMethod.GET, false); - - Map> headers = new HashMap<>(); - headers.put("X-Custom-Header", Arrays.asList("CustomValue")); - headers.put("Accept-Language", Arrays.asList("en-US")); - when(mockRequest.getHeaderParams()).thenReturn(headers); - - Response resp = client.makeRequest(mockRequest); - - assertEquals(200, resp.getStatusCode()); - assertEquals("headers", resp.getContent()); - } - - @Test(expected = ApiException.class) - public void testIOException() throws IOException { - when(mockRequest.getMethod()).thenReturn(HttpMethod.GET); - when(mockRequest.constructURL()).thenReturn(new URL("http://foo.com/hello")); - when(mockRequest.requiresAuthentication()).thenReturn(false); - when(mockClient.execute(any())).thenThrow(new IOException("Connection error")); - - client.makeRequest(mockRequest); - } - - @Test - public void testReliableRequest() { - BearerTokenRequest request = mock(BearerTokenRequest.class); - when(request.getMethod()).thenReturn(HttpMethod.GET); - - BearerTokenNetworkHttpClient clientSpy = spy(client); - doReturn(new Response("", 204)).when(clientSpy).makeRequest(request); - - clientSpy.reliableRequest(request); - - assertNotNull(clientSpy.getLastRequest()); - assertNotNull(clientSpy.getLastResponse()); - } -}