diff --git a/src/main/java/com/twilio/TwilioNoAuth.java b/src/main/java/com/twilio/TwilioNoAuth.java deleted file mode 100644 index e18e69fad5..0000000000 --- a/src/main/java/com/twilio/TwilioNoAuth.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.twilio; - -import com.twilio.annotations.Beta; -import com.twilio.http.noauth.NoAuthTwilioRestClient; -import lombok.Getter; - -import java.util.List; -import com.twilio.exception.AuthenticationException; - -@Beta -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/auth_strategy/NoAuthStrategy.java b/src/main/java/com/twilio/auth_strategy/NoAuthStrategy.java index e53014e556..99941fa0fc 100644 --- a/src/main/java/com/twilio/auth_strategy/NoAuthStrategy.java +++ b/src/main/java/com/twilio/auth_strategy/NoAuthStrategy.java @@ -2,9 +2,24 @@ import com.twilio.constant.EnumConstants; +// Does not have any state thus thread safe. public class NoAuthStrategy extends AuthStrategy { + private static volatile NoAuthStrategy INSTANCE; - public NoAuthStrategy(String token) { + private static volatile NoAuthStrategy instance; + + public static NoAuthStrategy getInstance() { + if (instance == null) { + synchronized (NoAuthStrategy.class) { + if (instance == null) { + instance = new NoAuthStrategy(); + } + } + } + return instance; + } + + private NoAuthStrategy() { super(EnumConstants.AuthType.NO_AUTH); } diff --git a/src/main/java/com/twilio/base/noauth/Creator.java b/src/main/java/com/twilio/base/noauth/Creator.java deleted file mode 100644 index f4860ca592..0000000000 --- a/src/main/java/com/twilio/base/noauth/Creator.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.twilio.base.noauth; - -import com.twilio.Twilio; -import com.twilio.TwilioNoAuth; -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/base/noauth/Deleter.java b/src/main/java/com/twilio/base/noauth/Deleter.java deleted file mode 100644 index 59e0f6ed04..0000000000 --- a/src/main/java/com/twilio/base/noauth/Deleter.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.twilio.base.noauth; - -import com.twilio.Twilio; -import com.twilio.TwilioNoAuth; -import com.twilio.http.noauth.NoAuthTwilioRestClient; - -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(TwilioNoAuth.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 NoAuthTwilioRestClient 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(TwilioNoAuth.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 NoAuthTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/base/noauth/Fetcher.java b/src/main/java/com/twilio/base/noauth/Fetcher.java deleted file mode 100644 index 27ef356c36..0000000000 --- a/src/main/java/com/twilio/base/noauth/Fetcher.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.twilio.base.noauth; - -import com.twilio.Twilio; - -import com.twilio.TwilioNoAuth; -import com.twilio.http.noauth.NoAuthTwilioRestClient; - -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(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 fetchAsync(final NoAuthTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> fetch(client), Twilio.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T fetch() { - return fetch(TwilioNoAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return Requested object - */ - public abstract T fetch(final NoAuthTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/base/noauth/Resource.java b/src/main/java/com/twilio/base/noauth/Resource.java deleted file mode 100644 index 88e316899f..0000000000 --- a/src/main/java/com/twilio/base/noauth/Resource.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.twilio.base.noauth; - -import java.io.Serializable; - -public abstract class Resource implements Serializable { - - private static final long serialVersionUID = -5898012691404059592L; - -} diff --git a/src/main/java/com/twilio/base/noauth/Updater.java b/src/main/java/com/twilio/base/noauth/Updater.java deleted file mode 100644 index f85536e002..0000000000 --- a/src/main/java/com/twilio/base/noauth/Updater.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.twilio.base.noauth; - -import com.twilio.Twilio; -import com.twilio.TwilioNoAuth; -import com.twilio.http.noauth.NoAuthTwilioRestClient; - -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(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 updateAsync(final NoAuthTwilioRestClient client) { - return CompletableFuture.supplyAsync(() -> update(client), Twilio.getExecutorService()); - } - - /** - * Execute a request using default client. - * - * @return Requested object - */ - public T update() { - return update(TwilioNoAuth.getRestClient()); - } - - /** - * Execute a request using specified client. - * - * @param client client used to make request - * @return Requested object - */ - public abstract T update(final NoAuthTwilioRestClient client); -} diff --git a/src/main/java/com/twilio/http/TwilioRestClient.java b/src/main/java/com/twilio/http/TwilioRestClient.java index c4b8ff2b41..92e1abca2f 100644 --- a/src/main/java/com/twilio/http/TwilioRestClient.java +++ b/src/main/java/com/twilio/http/TwilioRestClient.java @@ -89,10 +89,13 @@ protected TwilioRestClient(Builder b) { * @return Response object */ public Response request(final Request request) { - if (username != null && password != null) { - request.setAuth(username, password); - } else if (authStrategy != null) { - request.setAuth(authStrategy); + // If authStrategy is passed from NoAuth API, no need to set authStrategy (ex TokenCreator). + if (request.getAuthStrategy() == null) { + if (username != null && password != null) { + request.setAuth(username, password); + } else if (authStrategy != null) { + request.setAuth(authStrategy); + } } if (region != null) diff --git a/src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java b/src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java deleted file mode 100644 index 09a159bb74..0000000000 --- a/src/main/java/com/twilio/http/noauth/NoAuthHttpClient.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.twilio.http.noauth; - -import com.twilio.http.HttpClient; -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 NoAuthHttpClient { - 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 NoAuthRequest lastRequest; - - public Response reliableRequest(final NoAuthRequest request) { - return reliableRequest(request, HttpClient.RETRY_CODES, HttpClient.RETRIES, HttpClient.DELAY_MILLIS); - } - - public Response reliableRequest(final NoAuthRequest 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(NoAuthRequest request); -} diff --git a/src/main/java/com/twilio/http/noauth/NoAuthNetworkHttpClient.java b/src/main/java/com/twilio/http/noauth/NoAuthNetworkHttpClient.java deleted file mode 100644 index a1b84a5532..0000000000 --- a/src/main/java/com/twilio/http/noauth/NoAuthNetworkHttpClient.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.twilio.http.noauth; - -import static com.twilio.http.HttpClient.createHttpUriRequestBase; - -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.HttpDelete; -import org.apache.hc.client5.http.classic.methods.HttpGet; -import org.apache.hc.client5.http.classic.methods.HttpPatch; -import org.apache.hc.client5.http.classic.methods.HttpPost; -import org.apache.hc.client5.http.classic.methods.HttpPut; -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.HttpVersion; -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 org.apache.hc.core5.http.message.BasicNameValuePair; - -public class NoAuthNetworkHttpClient extends NoAuthHttpClient { - - protected final CloseableHttpClient client; - - public NoAuthNetworkHttpClient() { - this(DEFAULT_REQUEST_CONFIG); - } - - public NoAuthNetworkHttpClient(final RequestConfig requestConfig) { - this(requestConfig, DEFAULT_SOCKET_CONFIG); - } - - public NoAuthNetworkHttpClient(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(); - - 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(NoAuthRequest request) { - HttpMethod method = request.getMethod(); - HttpUriRequestBase httpUriRequestBase = createHttpUriRequestBase(request); - - httpUriRequestBase.setConfig(DEFAULT_REQUEST_CONFIG); - - httpUriRequestBase.setVersion(HttpVersion.HTTP_1_1); - - 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())); - - 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/noauth/NoAuthRequest.java b/src/main/java/com/twilio/http/noauth/NoAuthRequest.java deleted file mode 100644 index 1d216699eb..0000000000 --- a/src/main/java/com/twilio/http/noauth/NoAuthRequest.java +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index ff2e790380..0000000000 --- a/src/main/java/com/twilio/http/noauth/NoAuthTwilioRestClient.java +++ /dev/null @@ -1,147 +0,0 @@ -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; -import java.util.function.Predicate; - - -/* - * 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 NoAuthNetworkHttpClient httpClient; - @Getter - 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; - this.httpClient = b.httpClient; - this.objectMapper = b.objectMapper; - this.userAgentExtensions = b.userAgentExtensions; - } - - 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 NoAuthNetworkHttpClient httpClient; - private List userAgentExtensions; - private ObjectMapper objectMapper = DEFAULT_OBJECT_MAPPER; - - 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 NoAuthNetworkHttpClient 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.Builder objectMapper(final ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - return this; - } - - public NoAuthTwilioRestClient build() { - if (this.httpClient == null) { - this.httpClient = new NoAuthNetworkHttpClient(); - } - 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.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 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 --"); - } - } -} diff --git a/src/main/java/com/twilio/rest/iam/v1/Token.java b/src/main/java/com/twilio/rest/iam/v1/Token.java index c3d454f14a..e81303e1db 100644 --- a/src/main/java/com/twilio/rest/iam/v1/Token.java +++ b/src/main/java/com/twilio/rest/iam/v1/Token.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.noauth.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/iam/v1/TokenCreator.java b/src/main/java/com/twilio/rest/iam/v1/TokenCreator.java index eed268b64f..66b5f2e181 100644 --- a/src/main/java/com/twilio/rest/iam/v1/TokenCreator.java +++ b/src/main/java/com/twilio/rest/iam/v1/TokenCreator.java @@ -14,15 +14,16 @@ package com.twilio.rest.iam.v1; -import com.twilio.base.noauth.Creator; +import com.twilio.auth_strategy.NoAuthStrategy; +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.noauth.NoAuthRequest; -import com.twilio.http.noauth.NoAuthTwilioRestClient; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class TokenCreator extends Creator { @@ -82,19 +83,20 @@ public TokenCreator setScope(final String scope) { } @Override - public Token create(final NoAuthTwilioRestClient client) { + 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()); - NoAuthRequest request = new NoAuthRequest( + Request request = new Request( HttpMethod.POST, Domains.IAM.toString(), path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + request.setAuth(NoAuthStrategy.getInstance()); addPostParams(request); Response response = client.request(request); if (response == null) { @@ -102,7 +104,7 @@ public Token create(final NoAuthTwilioRestClient client) { "Token creation failed: Unable to connect to server" ); } else if ( - !NoAuthTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -120,7 +122,7 @@ public Token create(final NoAuthTwilioRestClient client) { return Token.fromJson(response.getStream(), client.getObjectMapper()); } - private void addPostParams(final NoAuthRequest request) { + private void addPostParams(final Request request) { if (grantType != null) { request.addPostParam("grant_type", grantType); } diff --git a/src/main/java/com/twilio/rest/oauth/v1/Authorize.java b/src/main/java/com/twilio/rest/oauth/v1/Authorize.java index 9b0025da6a..4a1c0e6a06 100644 --- a/src/main/java/com/twilio/rest/oauth/v1/Authorize.java +++ b/src/main/java/com/twilio/rest/oauth/v1/Authorize.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.noauth.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/oauth/v1/AuthorizeFetcher.java b/src/main/java/com/twilio/rest/oauth/v1/AuthorizeFetcher.java index c6c1afd09f..6b66ab822a 100644 --- a/src/main/java/com/twilio/rest/oauth/v1/AuthorizeFetcher.java +++ b/src/main/java/com/twilio/rest/oauth/v1/AuthorizeFetcher.java @@ -14,15 +14,16 @@ package com.twilio.rest.oauth.v1; -import com.twilio.base.noauth.Fetcher; +import com.twilio.auth_strategy.NoAuthStrategy; +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.noauth.NoAuthRequest; -import com.twilio.http.noauth.NoAuthTwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; public class AuthorizeFetcher extends Fetcher { @@ -61,16 +62,17 @@ public AuthorizeFetcher setState(final String state) { } @Override - public Authorize fetch(final NoAuthTwilioRestClient client) { + public Authorize fetch(final TwilioRestClient client) { String path = "/v1/authorize"; - NoAuthRequest request = new NoAuthRequest( + Request request = new Request( HttpMethod.GET, Domains.OAUTH.toString(), path ); addQueryParams(request); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + request.setAuth(NoAuthStrategy.getInstance()); Response response = client.request(request); if (response == null) { @@ -78,7 +80,7 @@ public Authorize fetch(final NoAuthTwilioRestClient client) { "Authorize fetch failed: Unable to connect to server" ); } else if ( - !NoAuthTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -99,7 +101,7 @@ public Authorize fetch(final NoAuthTwilioRestClient client) { ); } - private void addQueryParams(final NoAuthRequest request) { + private void addQueryParams(final Request request) { if (responseType != null) { request.addQueryParam("ResponseType", responseType); } diff --git a/src/main/java/com/twilio/rest/oauth/v1/Token.java b/src/main/java/com/twilio/rest/oauth/v1/Token.java index ece191a8d8..0914298465 100644 --- a/src/main/java/com/twilio/rest/oauth/v1/Token.java +++ b/src/main/java/com/twilio/rest/oauth/v1/Token.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.noauth.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/oauth/v1/TokenCreator.java b/src/main/java/com/twilio/rest/oauth/v1/TokenCreator.java index b6321d16e3..edc3882649 100644 --- a/src/main/java/com/twilio/rest/oauth/v1/TokenCreator.java +++ b/src/main/java/com/twilio/rest/oauth/v1/TokenCreator.java @@ -14,15 +14,16 @@ package com.twilio.rest.oauth.v1; -import com.twilio.base.noauth.Creator; +import com.twilio.auth_strategy.NoAuthStrategy; +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.noauth.NoAuthRequest; -import com.twilio.http.noauth.NoAuthTwilioRestClient; +import com.twilio.http.TwilioRestClient; +import com.twilio.http.Request; import com.twilio.rest.Domains; public class TokenCreator extends Creator { @@ -82,18 +83,19 @@ public TokenCreator setScope(final String scope) { } @Override - public Token create(final NoAuthTwilioRestClient client) { + public Token create(final TwilioRestClient client) { String path = "/v1/token"; path = path.replace("{" + "GrantType" + "}", this.grantType.toString()); path = path.replace("{" + "ClientId" + "}", this.clientId.toString()); - NoAuthRequest request = new NoAuthRequest( + Request request = new Request( HttpMethod.POST, Domains.OAUTH.toString(), path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + request.setAuth(NoAuthStrategy.getInstance()); addPostParams(request); Response response = client.request(request); if (response == null) { @@ -101,7 +103,7 @@ public Token create(final NoAuthTwilioRestClient client) { "Token creation failed: Unable to connect to server" ); } else if ( - !NoAuthTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -119,7 +121,7 @@ public Token create(final NoAuthTwilioRestClient client) { return Token.fromJson(response.getStream(), client.getObjectMapper()); } - private void addPostParams(final NoAuthRequest request) { + private void addPostParams(final Request request) { if (grantType != null) { request.addPostParam("GrantType", grantType); } diff --git a/src/main/java/com/twilio/rest/previewiam/v1/Authorize.java b/src/main/java/com/twilio/rest/previewiam/v1/Authorize.java index 3ac5cada23..7c41e281bc 100644 --- a/src/main/java/com/twilio/rest/previewiam/v1/Authorize.java +++ b/src/main/java/com/twilio/rest/previewiam/v1/Authorize.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.noauth.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/v1/AuthorizeFetcher.java b/src/main/java/com/twilio/rest/previewiam/v1/AuthorizeFetcher.java index 66d1fe0e88..ff85651635 100644 --- a/src/main/java/com/twilio/rest/previewiam/v1/AuthorizeFetcher.java +++ b/src/main/java/com/twilio/rest/previewiam/v1/AuthorizeFetcher.java @@ -14,15 +14,16 @@ package com.twilio.rest.previewiam.v1; -import com.twilio.base.noauth.Fetcher; +import com.twilio.auth_strategy.NoAuthStrategy; +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.noauth.NoAuthRequest; -import com.twilio.http.noauth.NoAuthTwilioRestClient; +import com.twilio.http.TwilioRestClient; +import com.twilio.http.Request; import com.twilio.rest.Domains; public class AuthorizeFetcher extends Fetcher { @@ -61,16 +62,17 @@ public AuthorizeFetcher setState(final String state) { } @Override - public Authorize fetch(final NoAuthTwilioRestClient client) { + public Authorize fetch(final TwilioRestClient client) { String path = "/v1/authorize"; - NoAuthRequest request = new NoAuthRequest( + Request request = new Request( HttpMethod.GET, Domains.PREVIEWIAM.toString(), path ); addQueryParams(request); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + request.setAuth(NoAuthStrategy.getInstance()); Response response = client.request(request); if (response == null) { @@ -78,7 +80,7 @@ public Authorize fetch(final NoAuthTwilioRestClient client) { "Authorize fetch failed: Unable to connect to server" ); } else if ( - !NoAuthTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -99,7 +101,7 @@ public Authorize fetch(final NoAuthTwilioRestClient client) { ); } - private void addQueryParams(final NoAuthRequest request) { + private void addQueryParams(final Request request) { if (responseType != null) { request.addQueryParam("response_type", responseType); } diff --git a/src/main/java/com/twilio/rest/previewiam/v1/Token.java b/src/main/java/com/twilio/rest/previewiam/v1/Token.java index ca25985b40..99349efcdc 100644 --- a/src/main/java/com/twilio/rest/previewiam/v1/Token.java +++ b/src/main/java/com/twilio/rest/previewiam/v1/Token.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.noauth.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/v1/TokenCreator.java b/src/main/java/com/twilio/rest/previewiam/v1/TokenCreator.java index 68ff95c296..74e8715b2c 100644 --- a/src/main/java/com/twilio/rest/previewiam/v1/TokenCreator.java +++ b/src/main/java/com/twilio/rest/previewiam/v1/TokenCreator.java @@ -14,15 +14,18 @@ package com.twilio.rest.previewiam.v1; -import com.twilio.base.noauth.Creator; +import com.twilio.auth_strategy.NoAuthStrategy; +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.noauth.NoAuthRequest; -import com.twilio.http.noauth.NoAuthTwilioRestClient; +import com.twilio.http.TwilioRestClient; +import com.twilio.http.Request; +import com.twilio.http.TwilioRestClient; +import com.twilio.http.Request; import com.twilio.rest.Domains; public class TokenCreator extends Creator { @@ -82,19 +85,20 @@ public TokenCreator setScope(final String scope) { } @Override - public Token create(final NoAuthTwilioRestClient client) { + 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()); - NoAuthRequest request = new NoAuthRequest( + Request request = new Request( HttpMethod.POST, Domains.PREVIEWIAM.toString(), path ); request.setContentType(EnumConstants.ContentType.FORM_URLENCODED); + request.setAuth(NoAuthStrategy.getInstance()); addPostParams(request); Response response = client.request(request); if (response == null) { @@ -102,7 +106,7 @@ public Token create(final NoAuthTwilioRestClient client) { "Token creation failed: Unable to connect to server" ); } else if ( - !NoAuthTwilioRestClient.SUCCESS.test(response.getStatusCode()) + !TwilioRestClient.SUCCESS.test(response.getStatusCode()) ) { RestException restException = RestException.fromJson( response.getStream(), @@ -120,7 +124,7 @@ public Token create(final NoAuthTwilioRestClient client) { return Token.fromJson(response.getStream(), client.getObjectMapper()); } - private void addPostParams(final NoAuthRequest request) { + private void addPostParams(final Request request) { if (grantType != null) { request.addPostParam("grant_type", grantType); } diff --git a/src/test/java/com/twilio/http/TwilioRestClientTest.java b/src/test/java/com/twilio/http/TwilioRestClientTest.java index 05cbcd389b..16baf5faeb 100644 --- a/src/test/java/com/twilio/http/TwilioRestClientTest.java +++ b/src/test/java/com/twilio/http/TwilioRestClientTest.java @@ -8,6 +8,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.twilio.auth_strategy.BasicAuthStrategy; +import com.twilio.auth_strategy.NoAuthStrategy; import com.twilio.rest.Domains; import java.util.Arrays; import java.util.Collections; @@ -123,4 +125,40 @@ public void testRequestWithExtensionNull() { twilioRestClientExtension.request(request); assertNull(request.getUserAgentExtensions()); } + + @Test + public void testRequestWithNoAuthStrategy() { + Request request = new Request( + HttpMethod.GET, + Domains.API.toString(), + URI + ); + request.setAuth(NoAuthStrategy.getInstance()); + twilioRestClientExtension = new TwilioRestClient.Builder(USER_NAME, TOKEN) + .userAgentExtensions(Collections.emptyList()) + .httpClient(httpClient) + .build(); + twilioRestClientExtension.request(request); + assertNull(twilioRestClientExtension.getAuthStrategy()); + // AuthStrategy of Request not changing by TwilioRestClient + assertEquals(NoAuthStrategy.getInstance(), request.getAuthStrategy()); + } + + @Test + public void testRequestWithNoAuthStrategyWithAuthStrategy() { + Request request = new Request( + HttpMethod.GET, + Domains.API.toString(), + URI + ); + request.setAuth(NoAuthStrategy.getInstance()); + twilioRestClientExtension = new TwilioRestClient.Builder(new BasicAuthStrategy(USER_NAME, TOKEN)) + .userAgentExtensions(Collections.emptyList()) + .httpClient(httpClient) + .build(); + twilioRestClientExtension.request(request); + assertNotNull(twilioRestClientExtension.getAuthStrategy()); + // AuthStrategy of Request not changing by TwilioRestClient + assertEquals(NoAuthStrategy.getInstance(), request.getAuthStrategy()); + } } diff --git a/src/test/java/com/twilio/http/noauth/NoAuthNetworkHttpClientTest.java b/src/test/java/com/twilio/http/noauth/NoAuthNetworkHttpClientTest.java deleted file mode 100644 index 5007a8cb31..0000000000 --- a/src/test/java/com/twilio/http/noauth/NoAuthNetworkHttpClientTest.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.twilio.http.noauth; - -import com.twilio.constant.EnumConstants; -import com.twilio.exception.ApiException; -import com.twilio.http.HttpMethod; -import com.twilio.http.Response; -import org.apache.hc.client5.http.config.RequestConfig; -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.apache.hc.core5.http.io.SocketConfig; -import org.apache.hc.core5.util.Timeout; -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.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.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 NoAuthNetworkHttpClientTest { - - private NoAuthNetworkHttpClient client; - - @Mock - private NoAuthRequest 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 NoAuthNetworkHttpClient(); - } - - private void setup( - final int statusCode, - final String content, - final HttpMethod method - ) 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.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 testReliableRequest() { - NoAuthRequest request = mock(NoAuthRequest.class); - when(request.getMethod()).thenReturn(HttpMethod.GET); - - NoAuthNetworkHttpClient clientSpy = spy(client); - doReturn(new Response("", 204)).when(clientSpy).makeRequest(request); - - clientSpy.reliableRequest(request); - - assertNotNull(clientSpy.getLastRequest()); - assertNotNull(clientSpy.getLastResponse()); - } - - @Test - public void testShouldRetry() { - Response resp = new Response("error", 500); - boolean shouldRetry = client.shouldRetry(resp, new int[]{500}); - assertEquals(true, shouldRetry); - - resp = new Response("success", 200); - shouldRetry = client.shouldRetry(resp, new int[]{500}); - assertEquals(false, shouldRetry); - - shouldRetry = client.shouldRetry(null, new int[]{500}); - assertEquals(true, shouldRetry); - } - - @Test - public void testDefaultConstructor() throws IOException { - // Create client using default constructor - NoAuthNetworkHttpClient defaultClient = new NoAuthNetworkHttpClient(); - - // Setup mock NoAuthRequest - NoAuthRequest request = mock(NoAuthRequest.class); - when(request.getMethod()).thenReturn(HttpMethod.GET); - when(request.constructURL()).thenReturn(new URL("http://example.com")); - when(request.getHeaderParams()).thenReturn(new HashMap<>()); - - // This test verifies that the default constructor creates a functional client - // We can't directly test the internals, but we can verify the client was constructed - // without exceptions and has the expected type - assertNotNull(defaultClient); - assertEquals(NoAuthNetworkHttpClient.class, defaultClient.getClass()); - } - - @Test - public void testRequestConfigConstructor() { - // Create a custom RequestConfig - RequestConfig customConfig = RequestConfig.custom() - .setConnectTimeout(Timeout.ofMilliseconds(5000)) - .build(); - - // Create client with custom RequestConfig - NoAuthNetworkHttpClient configClient = new NoAuthNetworkHttpClient(customConfig); - - // Verify client was created successfully - assertNotNull(configClient); - assertEquals(NoAuthNetworkHttpClient.class, configClient.getClass()); - } - - @Test - public void testRequestAndSocketConfigConstructor() { - // Create custom configs - RequestConfig customRequestConfig = RequestConfig.custom() - .setConnectTimeout(Timeout.ofMilliseconds(5000)) - .build(); - - SocketConfig customSocketConfig = SocketConfig.custom() - .setSoTimeout(Timeout.ofMilliseconds(5000)) - .build(); - - // Create client with both custom configs - NoAuthNetworkHttpClient fullConfigClient = new NoAuthNetworkHttpClient(customRequestConfig, customSocketConfig); - - // Verify client was created successfully - assertNotNull(fullConfigClient); - assertEquals(NoAuthNetworkHttpClient.class, fullConfigClient.getClass()); - } -}