diff --git a/client/resources/config-default.properties b/client/resources/config-default.properties index b0f6ff22..84260713 100644 --- a/client/resources/config-default.properties +++ b/client/resources/config-default.properties @@ -2,6 +2,8 @@ oauth-url=https://auth.sinch.com/oauth2/token numbers-server=https://numbers.api.sinch.com sms-region=us sms-server=https://zt.%s.sms.api.sinch.com +sms-server-service-plan=https://%s.sms.api.sinch.com + verification-server=https://verification.api.sinch.com voice-region=global diff --git a/client/src/main/com/sinch/sdk/SinchClient.java b/client/src/main/com/sinch/sdk/SinchClient.java index 5df9f5eb..d2631eae 100644 --- a/client/src/main/com/sinch/sdk/SinchClient.java +++ b/client/src/main/com/sinch/sdk/SinchClient.java @@ -7,12 +7,16 @@ import com.sinch.sdk.domains.voice.VoiceService; import com.sinch.sdk.http.HttpClientApache; import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.NumbersContext; import com.sinch.sdk.models.SMSRegion; +import com.sinch.sdk.models.SmsContext; +import com.sinch.sdk.models.VerificationContext; +import com.sinch.sdk.models.VoiceContext; import com.sinch.sdk.models.VoiceRegion; import java.io.IOException; import java.io.InputStream; -import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.Objects; import java.util.Properties; import java.util.logging.Logger; @@ -29,6 +33,7 @@ public class SinchClient { private static final String NUMBERS_SERVER_KEY = "numbers-server"; private static final String SMS_REGION_KEY = "sms-region"; private static final String SMS_SERVER_KEY = "sms-server"; + private static final String SMS_SERVER_SERVICE_PLAN_KEY = "sms-server-service-plan"; private static final String VOICE_REGION_KEY = "voice-region"; private static final String VOICE_APPLICATION_MANAGEMENT_SERVER_KEY = @@ -83,60 +88,104 @@ public SinchClient(Configuration configuration) { versionProperties = handlePropertiesFile(VERSION_PROPERTIES_FILE_NAME); LOGGER.fine( String.format( - "%s (%s) started with projectId '%s'", + "%s (%s) started", versionProperties.getProperty(PROJECT_NAME_KEY), - versionProperties.getProperty(PROJECT_VERSION_KEY), - configuration.getProjectId())); + versionProperties.getProperty(PROJECT_VERSION_KEY))); } private void handleDefaultNumbersSettings( Configuration configuration, Properties props, Configuration.Builder builder) { - if (null == configuration.getNumbersUrl() && props.containsKey(NUMBERS_SERVER_KEY)) { - builder.setNumbersUrl(props.getProperty(NUMBERS_SERVER_KEY)); + String url = configuration.getNumbersContext().map(NumbersContext::getNumbersUrl).orElse(null); + + if (null == url && props.containsKey(NUMBERS_SERVER_KEY)) { + builder.setNumbersContext( + NumbersContext.builder().setNumbersUrl(props.getProperty(NUMBERS_SERVER_KEY)).build()); } } private void handleDefaultSmsSettings( Configuration configuration, Properties props, Configuration.Builder builder) { - if (null == configuration.getSmsUrl() && props.containsKey(SMS_SERVER_KEY)) { - builder.setSmsUrl(props.getProperty(SMS_SERVER_KEY)); + String smsUrl = configuration.getSmsContext().map(SmsContext::getSmsUrl).orElse(null); + + SMSRegion smsRegion = configuration.getSmsContext().map(SmsContext::getSmsRegion).orElse(null); + + // service plan ID activated: use dedicated server + String serverKey = + configuration + .getSmsServicePlanCredentials() + .map(unused -> SMS_SERVER_SERVICE_PLAN_KEY) + .orElse(SMS_SERVER_KEY); + if (null == smsUrl && props.containsKey(serverKey)) { + smsUrl = props.getProperty(serverKey); } - if (null == configuration.getSmsRegion() && props.containsKey(SMS_REGION_KEY)) { - builder.setSmsRegion(SMSRegion.from(props.getProperty(SMS_REGION_KEY))); + + if (null == smsRegion && props.containsKey(SMS_REGION_KEY)) { + smsRegion = SMSRegion.from(props.getProperty(SMS_REGION_KEY)); + } + + if (null != smsUrl || null != smsRegion) { + builder.setSmsContext(SmsContext.builder().setSmsRegion(smsRegion).setSmsUrl(smsUrl).build()); } } private void handleDefaultVerificationSettings( Configuration configuration, Properties props, Configuration.Builder builder) { - if (null == configuration.getVerificationUrl() && props.containsKey(VERIFICATION_SERVER_KEY)) { - builder.setVerificationUrl(props.getProperty(VERIFICATION_SERVER_KEY)); + String url = + configuration + .getVerificationContext() + .map(VerificationContext::getVerificationUrl) + .orElse(null); + + if (null == url && props.containsKey(VERIFICATION_SERVER_KEY)) { + builder.setVerificationContext( + VerificationContext.builder() + .setVerificationUrl(props.getProperty(VERIFICATION_SERVER_KEY)) + .build()); } } private void handleDefaultVoiceSettings( Configuration configuration, Properties props, Configuration.Builder builder) { - if (null == configuration.getVoiceRegion() && props.containsKey(VOICE_REGION_KEY)) { - builder.setVoiceRegion(VoiceRegion.from(props.getProperty(VOICE_REGION_KEY))); + + VoiceRegion region = + configuration.getVoiceContext().map(VoiceContext::getVoiceRegion).orElse(null); + + String voiceUrl = configuration.getVoiceContext().map(VoiceContext::getVoiceUrl).orElse(null); + + String voiceApplicationManagementUrl = + configuration + .getVoiceContext() + .map(VoiceContext::getVoiceApplicationManagementUrl) + .orElse(null); + + // default region to be used ? + if (null == region && props.containsKey(VOICE_REGION_KEY)) { + region = VoiceRegion.from(props.getProperty(VOICE_REGION_KEY)); } // server is not defined: use the region to set to an existing one and use "global" as a default // fallback - if (StringUtil.isEmpty(builder.getVoiceUrl())) { - VoiceRegion region = - StringUtil.isEmpty(builder.getVoiceRegion().value()) - ? VoiceRegion.GLOBAL - : builder.getVoiceRegion(); - builder.setVoiceUrl(props.getProperty(String.format("voice-server-%s", region.value()))); + if (StringUtil.isEmpty(voiceUrl)) { + VoiceRegion regionForFormat = null == region ? VoiceRegion.GLOBAL : region; + voiceUrl = props.getProperty(String.format("voice-server-%s", regionForFormat.value())); } // application management server - if (null == configuration.getVoiceApplicationManagementUrl() + if (StringUtil.isEmpty(voiceApplicationManagementUrl) && props.containsKey(VOICE_APPLICATION_MANAGEMENT_SERVER_KEY)) { - builder.setVoiceApplicationMngmtUrl( - props.getProperty(VOICE_APPLICATION_MANAGEMENT_SERVER_KEY)); + voiceApplicationManagementUrl = props.getProperty(VOICE_APPLICATION_MANAGEMENT_SERVER_KEY); + } + + if (null != region || null != voiceUrl || null != voiceApplicationManagementUrl) { + builder.setVoiceContext( + VoiceContext.builder() + .setVoiceRegion(region) + .setVoiceUrl(voiceUrl) + .setVoiceApplicationMngmtUrl(voiceApplicationManagementUrl) + .build()); } } @@ -212,40 +261,44 @@ public VoiceService voice() { private void checkConfiguration(Configuration configuration) throws NullPointerException { Objects.requireNonNull(configuration.getOAuthUrl(), "'oauthUrl' cannot be null"); - Objects.requireNonNull(configuration.getNumbersUrl(), "'numbersUrl' cannot be null"); - Objects.requireNonNull(configuration.getSmsUrl(), "'smsUrl' cannot be null"); - Objects.requireNonNull(configuration.getVerificationUrl(), "'verificationUrl' cannot be null"); } private NumbersService numbersInit() { - LOGGER.fine( - "Activate numbers API with server='" - + getConfiguration().getNumbersServer().getUrl() - + "'"); return new com.sinch.sdk.domains.numbers.adapters.NumbersService( - getConfiguration(), getHttpClient()); + getConfiguration().getUnifiedCredentials().orElse(null), + configuration.getNumbersContext().orElse(null), + getHttpClient()); } private SMSService smsInit() { - LOGGER.fine( - "Activate SMS API with server='" + getConfiguration().getSmsServer().getUrl() + "'"); - return new com.sinch.sdk.domains.sms.adapters.SMSService(getConfiguration(), getHttpClient()); + + return getConfiguration() + .getSmsServicePlanCredentials() + .map( + f -> + new com.sinch.sdk.domains.sms.adapters.SMSService( + f, getConfiguration().getSmsContext().orElse(null), getHttpClient())) + .orElseGet( + () -> + new com.sinch.sdk.domains.sms.adapters.SMSService( + getConfiguration().getUnifiedCredentials().orElse(null), + getConfiguration().getSmsContext().orElse(null), + configuration.getOAuthServer(), + getHttpClient())); } private VerificationService verificationInit() { - LOGGER.fine( - "Activate verification API with server='" - + getConfiguration().getVerificationServer().getUrl() - + "'"); return new com.sinch.sdk.domains.verification.adapters.VerificationService( - getConfiguration(), getHttpClient()); + getConfiguration().getApplicationCredentials().orElse(null), + getConfiguration().getVerificationContext().orElse(null), + getHttpClient()); } private VoiceService voiceInit() { - LOGGER.fine( - "Activate voice API with server='" + getConfiguration().getVoiceServer().getUrl() + "'"); return new com.sinch.sdk.domains.voice.adapters.VoiceService( - getConfiguration(), getHttpClient()); + getConfiguration().getApplicationCredentials().orElse(null), + getConfiguration().getVoiceContext().orElse(null), + getHttpClient()); } private Properties handlePropertiesFile(String fileName) { @@ -289,7 +342,7 @@ private String formatSdkUserAgentHeader(Properties versionProperties) { private String formatAuxiliaryFlag(String auxiliaryFlag) { - Collection values = Arrays.asList(System.getProperty("java.vendor")); + Collection values = Collections.singletonList(System.getProperty("java.vendor")); if (!StringUtil.isEmpty(auxiliaryFlag)) { values.add(auxiliaryFlag); diff --git a/client/src/main/com/sinch/sdk/auth/adapters/BasicAuthManager.java b/client/src/main/com/sinch/sdk/auth/adapters/BasicAuthManager.java index b91471cd..3e7b970e 100644 --- a/client/src/main/com/sinch/sdk/auth/adapters/BasicAuthManager.java +++ b/client/src/main/com/sinch/sdk/auth/adapters/BasicAuthManager.java @@ -2,7 +2,7 @@ import com.sinch.sdk.core.http.AuthManager; import com.sinch.sdk.core.utils.Pair; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.UnifiedCredentials; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Collection; @@ -18,8 +18,8 @@ public class BasicAuthManager implements AuthManager { private final String keyId; private final String keySecret; - public BasicAuthManager(Configuration configuration) { - this(configuration.getKeyId(), configuration.getKeySecret()); + public BasicAuthManager(UnifiedCredentials credentials) { + this(credentials.getKeyId(), credentials.getKeySecret()); } public BasicAuthManager(String keyId, String keySecret) { diff --git a/client/src/main/com/sinch/sdk/auth/adapters/BearerAuthManager.java b/client/src/main/com/sinch/sdk/auth/adapters/BearerAuthManager.java index 461e0984..67299a29 100644 --- a/client/src/main/com/sinch/sdk/auth/adapters/BearerAuthManager.java +++ b/client/src/main/com/sinch/sdk/auth/adapters/BearerAuthManager.java @@ -1,57 +1,21 @@ package com.sinch.sdk.auth.adapters; -import com.fasterxml.jackson.core.type.TypeReference; -import com.sinch.sdk.auth.models.BearerAuthResponse; -import com.sinch.sdk.core.exceptions.ApiAuthException; import com.sinch.sdk.core.http.AuthManager; -import com.sinch.sdk.core.http.HttpClient; -import com.sinch.sdk.core.http.HttpMapper; -import com.sinch.sdk.core.http.HttpMethod; -import com.sinch.sdk.core.http.HttpRequest; -import com.sinch.sdk.core.http.HttpResponse; -import com.sinch.sdk.core.models.ServerConfiguration; import com.sinch.sdk.core.utils.Pair; -import com.sinch.sdk.models.Configuration; -import java.util.AbstractMap; import java.util.Collection; import java.util.Collections; import java.util.Map; -import java.util.Optional; import java.util.logging.Logger; -import java.util.stream.Collectors; -import java.util.stream.Stream; public class BearerAuthManager implements AuthManager { - public static final String BEARER_EXPIRED_KEYWORD = "expired"; - public static final String BEARER_AUTHENTICATE_RESPONSE_HEADER_KEYWORD = "www-authenticate"; private static final Logger LOGGER = Logger.getLogger(BearerAuthManager.class.getName()); - private static final String AUTH_KEYWORD = "Bearer"; - private static final int maxRefreshAttempt = 5; - private final ServerConfiguration oAuthServer; - private final HttpMapper mapper; - private final HttpClient httpClient; - private final Map authManagers; - private String token; - - public BearerAuthManager(Configuration configuration, HttpMapper mapper, HttpClient httpClient) { - this(configuration.getKeyId(), configuration.getKeySecret(), configuration, mapper, httpClient); - } - public BearerAuthManager( - String keyId, - String keySecret, - Configuration configuration, - HttpMapper mapper, - HttpClient httpClient) { - this.oAuthServer = configuration.getOAuthServer(); - this.mapper = mapper; - this.httpClient = httpClient; + private static final String AUTH_KEYWORD = "Bearer"; + private final String token; - AuthManager basicAuthManager = new BasicAuthManager(keyId, keySecret); - authManagers = - Stream.of(new AbstractMap.SimpleEntry<>(SCHEMA_KEYWORD_BASIC, basicAuthManager)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + public BearerAuthManager(String token) { + this.token = token; } public String getSchema() { @@ -60,56 +24,16 @@ public String getSchema() { @Override public void resetToken() { - token = null; + // no op } @Override public Collection> getAuthorizationHeaders( String timestamp, String method, String httpContentType, String path, String body) { - if (token == null) { - refreshToken(); - } return Collections.singletonList(new Pair<>("Authorization", AUTH_KEYWORD + " " + token)); } - private void refreshToken() { - - int attempt = 0; - while (attempt < maxRefreshAttempt) { - Optional newValue = getNewToken(); - if (newValue.isPresent()) { - token = newValue.get(); - return; - } - attempt++; - } - throw new ApiAuthException("Unable to get new token"); - } - - private Optional getNewToken() { - - LOGGER.fine("Refreshing OAuth token"); - HttpRequest request = - new HttpRequest( - null, - HttpMethod.POST, - Collections.emptyList(), - "grant_type=client_credentials", - null, - null, - Collections.singletonList("application/x-www-form-urlencoded"), - Collections.singletonList(SCHEMA_KEYWORD_BASIC)); - try { - HttpResponse httpResponse = httpClient.invokeAPI(oAuthServer, authManagers, request); - BearerAuthResponse authResponse = - mapper.deserialize(httpResponse, new TypeReference() {}); - return Optional.ofNullable(authResponse.getAccessToken()); - } catch (Exception e) { - return Optional.empty(); - } - } - public boolean validateAuthenticatedRequest( String method, String path, Map headers, String jsonPayload) { LOGGER.severe("checkAuthentication not implemented"); diff --git a/client/src/main/com/sinch/sdk/auth/adapters/OAuthManager.java b/client/src/main/com/sinch/sdk/auth/adapters/OAuthManager.java new file mode 100644 index 00000000..f6aa0e4b --- /dev/null +++ b/client/src/main/com/sinch/sdk/auth/adapters/OAuthManager.java @@ -0,0 +1,122 @@ +package com.sinch.sdk.auth.adapters; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.sinch.sdk.auth.models.BearerAuthResponse; +import com.sinch.sdk.core.exceptions.ApiAuthException; +import com.sinch.sdk.core.http.AuthManager; +import com.sinch.sdk.core.http.HttpClient; +import com.sinch.sdk.core.http.HttpMapper; +import com.sinch.sdk.core.http.HttpMethod; +import com.sinch.sdk.core.http.HttpRequest; +import com.sinch.sdk.core.http.HttpResponse; +import com.sinch.sdk.core.models.ServerConfiguration; +import com.sinch.sdk.core.utils.Pair; +import com.sinch.sdk.models.UnifiedCredentials; +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Optional; +import java.util.logging.Logger; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class OAuthManager implements AuthManager { + + public static final String BEARER_EXPIRED_KEYWORD = "expired"; + public static final String BEARER_AUTHENTICATE_RESPONSE_HEADER_KEYWORD = "www-authenticate"; + private static final Logger LOGGER = Logger.getLogger(OAuthManager.class.getName()); + private static final String AUTH_KEYWORD = "Bearer"; + private static final int maxRefreshAttempt = 5; + private final ServerConfiguration oAuthServer; + private final HttpMapper mapper; + private final HttpClient httpClient; + private final Map authManagers; + private String token; + + public OAuthManager( + UnifiedCredentials credentials, + ServerConfiguration oAuthServer, + HttpMapper mapper, + HttpClient httpClient) { + this(credentials.getKeyId(), credentials.getKeySecret(), oAuthServer, mapper, httpClient); + } + + public OAuthManager( + String keyId, + String keySecret, + ServerConfiguration oAuthServer, + HttpMapper mapper, + HttpClient httpClient) { + this.oAuthServer = oAuthServer; + this.mapper = mapper; + this.httpClient = httpClient; + + AuthManager basicAuthManager = new BasicAuthManager(keyId, keySecret); + authManagers = + Stream.of(new AbstractMap.SimpleEntry<>(SCHEMA_KEYWORD_BASIC, basicAuthManager)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + public String getSchema() { + return SCHEMA_KEYWORD_BEARER; + } + + @Override + public void resetToken() { + token = null; + } + + @Override + public Collection> getAuthorizationHeaders( + String timestamp, String method, String httpContentType, String path, String body) { + + if (token == null) { + refreshToken(); + } + return Collections.singletonList(new Pair<>("Authorization", AUTH_KEYWORD + " " + token)); + } + + private void refreshToken() { + + int attempt = 0; + while (attempt < maxRefreshAttempt) { + Optional newValue = getNewToken(); + if (newValue.isPresent()) { + token = newValue.get(); + return; + } + attempt++; + } + throw new ApiAuthException("Unable to get new token"); + } + + private Optional getNewToken() { + + LOGGER.fine("Refreshing OAuth token"); + HttpRequest request = + new HttpRequest( + null, + HttpMethod.POST, + Collections.emptyList(), + "grant_type=client_credentials", + null, + null, + Collections.singletonList("application/x-www-form-urlencoded"), + Collections.singletonList(SCHEMA_KEYWORD_BASIC)); + try { + HttpResponse httpResponse = httpClient.invokeAPI(oAuthServer, authManagers, request); + BearerAuthResponse authResponse = + mapper.deserialize(httpResponse, new TypeReference() {}); + return Optional.ofNullable(authResponse.getAccessToken()); + } catch (Exception e) { + return Optional.empty(); + } + } + + public boolean validateAuthenticatedRequest( + String method, String path, Map headers, String jsonPayload) { + LOGGER.severe("checkAuthentication not implemented"); + return false; + } +} diff --git a/client/src/main/com/sinch/sdk/domains/numbers/adapters/ActiveNumberService.java b/client/src/main/com/sinch/sdk/domains/numbers/adapters/ActiveNumberService.java index 38100312..79735a02 100644 --- a/client/src/main/com/sinch/sdk/domains/numbers/adapters/ActiveNumberService.java +++ b/client/src/main/com/sinch/sdk/domains/numbers/adapters/ActiveNumberService.java @@ -21,7 +21,7 @@ import com.sinch.sdk.domains.numbers.models.requests.ActiveNumberListRequestParameters; import com.sinch.sdk.domains.numbers.models.requests.ActiveNumberUpdateRequestParameters; import com.sinch.sdk.domains.numbers.models.responses.ActiveNumberListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.NumbersContext; import java.util.Collection; import java.util.List; import java.util.Map; @@ -29,20 +29,20 @@ public class ActiveNumberService implements com.sinch.sdk.domains.numbers.ActiveNumberService { - private Configuration configuration; - private ActiveNumberApi api; - - public ActiveNumberService() {} + private final String uriUUID; + private final ActiveNumberApi api; public ActiveNumberService( - Configuration configuration, HttpClient httpClient, Map authManagers) { - this.configuration = configuration; + String uriUUID, + NumbersContext context, + HttpClient httpClient, + Map authManagers) { + this.uriUUID = uriUUID; this.api = - new ActiveNumberApi( - httpClient, configuration.getNumbersServer(), authManagers, new HttpMapper()); + new ActiveNumberApi(httpClient, context.getNumbersServer(), authManagers, new HttpMapper()); } - private ActiveNumberApi getApi() { + protected ActiveNumberApi getApi() { return this.api; } @@ -80,7 +80,7 @@ public ActiveNumberListResponse list(ActiveNumberListRequestParameters parameter ActiveNumbersResponseDto response = getApi() .numberServiceListActiveNumbers( - configuration.getProjectId(), + uriUUID, regionCode, type.value(), patternPattern, @@ -96,14 +96,12 @@ public ActiveNumberListResponse list(ActiveNumberListRequestParameters parameter } public ActiveNumber get(String phoneNumber) throws ApiException { - ActiveNumberDto response = - getApi().numberServiceGetActiveNumber(configuration.getProjectId(), phoneNumber); + ActiveNumberDto response = getApi().numberServiceGetActiveNumber(uriUUID, phoneNumber); return ActiveNumberDtoConverter.convert(response); } public ActiveNumber release(String phoneNumber) throws ApiException { - ActiveNumberDto response = - getApi().numberServiceReleaseNumber(configuration.getProjectId(), phoneNumber); + ActiveNumberDto response = getApi().numberServiceReleaseNumber(uriUUID, phoneNumber); return ActiveNumberDtoConverter.convert(response); } @@ -112,7 +110,7 @@ public ActiveNumber update(String phoneNumber, ActiveNumberUpdateRequestParamete ActiveNumberDto response = getApi() .numberServiceUpdateActiveNumber( - configuration.getProjectId(), + uriUUID, phoneNumber, ActiveNumberUpdateRequestParametersDtoConverter.convert(parameters)); return ActiveNumberDtoConverter.convert(response); diff --git a/client/src/main/com/sinch/sdk/domains/numbers/adapters/AvailableNumberService.java b/client/src/main/com/sinch/sdk/domains/numbers/adapters/AvailableNumberService.java index 172a62b7..ed253cf5 100644 --- a/client/src/main/com/sinch/sdk/domains/numbers/adapters/AvailableNumberService.java +++ b/client/src/main/com/sinch/sdk/domains/numbers/adapters/AvailableNumberService.java @@ -11,7 +11,11 @@ import com.sinch.sdk.domains.numbers.adapters.converters.AvailableNumberDtoConverter; import com.sinch.sdk.domains.numbers.adapters.converters.AvailableRentAnyRequestParametersDtoConverter; import com.sinch.sdk.domains.numbers.adapters.converters.AvailableRentRequestParametersDtoConverter; -import com.sinch.sdk.domains.numbers.models.*; +import com.sinch.sdk.domains.numbers.models.ActiveNumber; +import com.sinch.sdk.domains.numbers.models.AvailableNumber; +import com.sinch.sdk.domains.numbers.models.NumberPattern; +import com.sinch.sdk.domains.numbers.models.NumberType; +import com.sinch.sdk.domains.numbers.models.SearchPattern; import com.sinch.sdk.domains.numbers.models.dto.v1.ActiveNumberDto; import com.sinch.sdk.domains.numbers.models.dto.v1.AvailableNumberDto; import com.sinch.sdk.domains.numbers.models.dto.v1.AvailableNumbersResponseDto; @@ -19,7 +23,7 @@ import com.sinch.sdk.domains.numbers.models.requests.AvailableNumberRentAnyRequestParameters; import com.sinch.sdk.domains.numbers.models.requests.AvailableNumberRentRequestParameters; import com.sinch.sdk.domains.numbers.models.responses.AvailableNumberListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.NumbersContext; import java.util.Collection; import java.util.List; import java.util.Map; @@ -28,20 +32,21 @@ public class AvailableNumberService implements com.sinch.sdk.domains.numbers.AvailableNumberService { - private Configuration configuration; - private AvailableNumberApi api; - - public AvailableNumberService() {} + private final String uriUUID; + private final AvailableNumberApi api; public AvailableNumberService( - Configuration configuration, HttpClient httpClient, Map authManagers) { - this.configuration = configuration; + String uriUUID, + NumbersContext context, + HttpClient httpClient, + Map authManagers) { + this.uriUUID = uriUUID; this.api = new AvailableNumberApi( - httpClient, configuration.getNumbersServer(), authManagers, new HttpMapper()); + httpClient, context.getNumbersServer(), authManagers, new HttpMapper()); } - private AvailableNumberApi getApi() { + protected AvailableNumberApi getApi() { return this.api; } @@ -72,7 +77,7 @@ public AvailableNumberListResponse list(AvailableNumberListAllRequestParameters AvailableNumbersResponseDto response = getApi() .numberServiceListAvailableNumbers( - configuration.getProjectId(), + uriUUID, regionCode, type.value(), patternPattern, @@ -85,8 +90,7 @@ public AvailableNumberListResponse list(AvailableNumberListAllRequestParameters } public AvailableNumber checkAvailability(String phoneNumber) throws ApiException { - AvailableNumberDto response = - getApi().numberServiceGetAvailableNumber(configuration.getProjectId(), phoneNumber); + AvailableNumberDto response = getApi().numberServiceGetAvailableNumber(uriUUID, phoneNumber); return AvailableNumberDtoConverter.convert(response); } @@ -99,7 +103,7 @@ public ActiveNumber rent(String phoneNumber, AvailableNumberRentRequestParameter ActiveNumberDto response = getApi() .numberServiceRentNumber( - configuration.getProjectId(), + uriUUID, phoneNumber, AvailableRentRequestParametersDtoConverter.convert(guardParameters)); return ActiveNumberDtoConverter.convert(response); @@ -111,8 +115,7 @@ public ActiveNumber rentAny(AvailableNumberRentAnyRequestParameters parameters) ActiveNumberDto response = getApi() .numberServiceRentAnyNumber( - configuration.getProjectId(), - AvailableRentAnyRequestParametersDtoConverter.convert(parameters)); + uriUUID, AvailableRentAnyRequestParametersDtoConverter.convert(parameters)); return ActiveNumberDtoConverter.convert(response); } } diff --git a/client/src/main/com/sinch/sdk/domains/numbers/adapters/AvailableRegionService.java b/client/src/main/com/sinch/sdk/domains/numbers/adapters/AvailableRegionService.java index 12ec8f8d..22fade1d 100644 --- a/client/src/main/com/sinch/sdk/domains/numbers/adapters/AvailableRegionService.java +++ b/client/src/main/com/sinch/sdk/domains/numbers/adapters/AvailableRegionService.java @@ -11,7 +11,7 @@ import com.sinch.sdk.domains.numbers.models.dto.v1.ListAvailableRegionsResponseDto; import com.sinch.sdk.domains.numbers.models.requests.AvailableRegionListAllRequestParameters; import com.sinch.sdk.domains.numbers.models.responses.AvailableRegionListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.NumbersContext; import java.util.Collection; import java.util.List; import java.util.Map; @@ -20,17 +20,22 @@ public class AvailableRegionService implements com.sinch.sdk.domains.numbers.AvailableRegionService { - private Configuration configuration; - private AvailableRegionsApi api; - - public AvailableRegionService() {} + private final String uriUUID; + private final AvailableRegionsApi api; public AvailableRegionService( - Configuration configuration, HttpClient httpClient, Map authManagers) { - this.configuration = configuration; + String uriUUID, + NumbersContext context, + HttpClient httpClient, + Map authManagers) { + this.uriUUID = uriUUID; this.api = new AvailableRegionsApi( - httpClient, configuration.getNumbersServer(), authManagers, new HttpMapper()); + httpClient, context.getNumbersServer(), authManagers, new HttpMapper()); + } + + protected AvailableRegionsApi getApi() { + return this.api; } public AvailableRegionListResponse list(AvailableRegionListAllRequestParameters parameters) @@ -43,7 +48,7 @@ public AvailableRegionListResponse list(AvailableRegionListAllRequestParameters } ListAvailableRegionsResponseDto response = - api.numberServiceListAvailableRegions(configuration.getProjectId(), types); + getApi().numberServiceListAvailableRegions(uriUUID, types); Collection entities = AvailableRegionsDtoConverter.convert(response); return new AvailableRegionListResponse(entities); diff --git a/client/src/main/com/sinch/sdk/domains/numbers/adapters/CallbackConfigurationService.java b/client/src/main/com/sinch/sdk/domains/numbers/adapters/CallbackConfigurationService.java index 16f7fb67..c2acf13a 100644 --- a/client/src/main/com/sinch/sdk/domains/numbers/adapters/CallbackConfigurationService.java +++ b/client/src/main/com/sinch/sdk/domains/numbers/adapters/CallbackConfigurationService.java @@ -10,32 +10,31 @@ import com.sinch.sdk.domains.numbers.models.CallbackConfiguration; import com.sinch.sdk.domains.numbers.models.dto.v1.CallbackConfigurationDto; import com.sinch.sdk.domains.numbers.models.requests.CallbackConfigurationUpdateRequestParameters; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.NumbersContext; import java.util.Map; public class CallbackConfigurationService implements com.sinch.sdk.domains.numbers.CallbackConfigurationService { - private Configuration configuration; - private CallbacksApi api; - - public CallbackConfigurationService() {} + private final String uriUUID; + private final CallbacksApi api; public CallbackConfigurationService( - Configuration configuration, HttpClient httpClient, Map authManagers) { - this.configuration = configuration; + String uriUUID, + NumbersContext context, + HttpClient httpClient, + Map authManagers) { + this.uriUUID = uriUUID; this.api = - new CallbacksApi( - httpClient, configuration.getNumbersServer(), authManagers, new HttpMapper()); + new CallbacksApi(httpClient, context.getNumbersServer(), authManagers, new HttpMapper()); } - private CallbacksApi getApi() { + protected CallbacksApi getApi() { return this.api; } public CallbackConfiguration get() throws ApiException { - CallbackConfigurationDto response = - getApi().getCallbackConfiguration(configuration.getProjectId()); + CallbackConfigurationDto response = getApi().getCallbackConfiguration(uriUUID); return CallbackConfigurationDtoConverter.convert(response); } @@ -45,7 +44,7 @@ public CallbackConfiguration update(CallbackConfigurationUpdateRequestParameters CallbackConfigurationDto response = getApi() .updateCallbackConfiguration( - configuration.getProjectId(), + uriUUID, CallbackConfigurationUpdateRequestParametersDtoConverter.convert(parameters)); return CallbackConfigurationDtoConverter.convert(response); } diff --git a/client/src/main/com/sinch/sdk/domains/numbers/adapters/NumbersService.java b/client/src/main/com/sinch/sdk/domains/numbers/adapters/NumbersService.java index ce2f1788..6b60127b 100644 --- a/client/src/main/com/sinch/sdk/domains/numbers/adapters/NumbersService.java +++ b/client/src/main/com/sinch/sdk/domains/numbers/adapters/NumbersService.java @@ -4,16 +4,21 @@ import com.sinch.sdk.core.http.AuthManager; import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.core.utils.StringUtil; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.NumbersContext; +import com.sinch.sdk.models.UnifiedCredentials; import java.util.AbstractMap; import java.util.Map; +import java.util.Objects; +import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; public class NumbersService implements com.sinch.sdk.domains.numbers.NumbersService { + private static final Logger LOGGER = Logger.getLogger(NumbersService.class.getName()); private static final String SECURITY_SCHEME_KEYWORD_NUMBERS = "BasicAuth"; - private final Configuration configuration; + private final String uriUUID; + private final NumbersContext context; private final HttpClient httpClient; private AvailableNumberService available; private ActiveNumberService active; @@ -23,15 +28,24 @@ public class NumbersService implements com.sinch.sdk.domains.numbers.NumbersServ private final Map authManagers; - public NumbersService(Configuration configuration, HttpClient httpClient) { + public NumbersService( + UnifiedCredentials credentials, NumbersContext context, HttpClient httpClient) { - StringUtil.requireNonEmpty(configuration.getKeyId(), "'keyId' must be defined"); - StringUtil.requireNonEmpty(configuration.getKeySecret(), "'keySecret' must be defined"); - StringUtil.requireNonEmpty(configuration.getProjectId(), "'projectId' must be defined"); + Objects.requireNonNull(credentials, "Credentials must be defined"); + Objects.requireNonNull(context, "Context must be defined"); + StringUtil.requireNonEmpty(credentials.getKeyId(), "'keyId' must be defined"); + StringUtil.requireNonEmpty(credentials.getKeySecret(), "'keySecret' must be defined"); + StringUtil.requireNonEmpty(credentials.getProjectId(), "'projectId' must be defined"); + StringUtil.requireNonEmpty(context.getNumbersUrl(), "'numbersUrl' must be defined"); - this.configuration = configuration; + LOGGER.fine("Activate numbers API with server='" + context.getNumbersServer().getUrl() + "'"); + + this.uriUUID = credentials.getProjectId(); + this.context = context; this.httpClient = httpClient; - AuthManager basicAuthManager = new BasicAuthManager(configuration); + + AuthManager basicAuthManager = + new BasicAuthManager(credentials.getKeyId(), credentials.getKeySecret()); authManagers = Stream.of(new AbstractMap.SimpleEntry<>(SECURITY_SCHEME_KEYWORD_NUMBERS, basicAuthManager)) @@ -40,28 +54,28 @@ public NumbersService(Configuration configuration, HttpClient httpClient) { public AvailableNumberService available() { if (null == this.available) { - this.available = new AvailableNumberService(configuration, httpClient, authManagers); + this.available = new AvailableNumberService(uriUUID, context, httpClient, authManagers); } return this.available; } public AvailableRegionService regions() { if (null == this.regions) { - this.regions = new AvailableRegionService(configuration, httpClient, authManagers); + this.regions = new AvailableRegionService(uriUUID, context, httpClient, authManagers); } return this.regions; } public ActiveNumberService active() { if (null == this.active) { - this.active = new ActiveNumberService(configuration, httpClient, authManagers); + this.active = new ActiveNumberService(uriUUID, context, httpClient, authManagers); } return this.active; } public CallbackConfigurationService callback() { if (null == this.callback) { - this.callback = new CallbackConfigurationService(configuration, httpClient, authManagers); + this.callback = new CallbackConfigurationService(uriUUID, context, httpClient, authManagers); } return this.callback; } diff --git a/client/src/main/com/sinch/sdk/domains/sms/adapters/BatchesService.java b/client/src/main/com/sinch/sdk/domains/sms/adapters/BatchesService.java index 20b0bbd4..eebc4c35 100644 --- a/client/src/main/com/sinch/sdk/domains/sms/adapters/BatchesService.java +++ b/client/src/main/com/sinch/sdk/domains/sms/adapters/BatchesService.java @@ -16,47 +16,41 @@ import com.sinch.sdk.domains.sms.models.requests.BatchesListRequestParameters; import com.sinch.sdk.domains.sms.models.requests.UpdateBaseBatchRequest; import com.sinch.sdk.domains.sms.models.responses.BatchesListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.SmsContext; import java.time.Instant; import java.util.Collection; import java.util.Map; public class BatchesService implements com.sinch.sdk.domains.sms.BatchesService { - private Configuration configuration; - private BatchesApi api; - - public BatchesService() {} + private final String uriPathID; + private final BatchesApi api; public BatchesService( - Configuration configuration, HttpClient httpClient, Map authManagers) { - this.configuration = configuration; - this.api = - new BatchesApi(httpClient, configuration.getSmsServer(), authManagers, new HttpMapper()); + String uriPathID, + SmsContext context, + HttpClient httpClient, + Map authManagers) { + this.uriPathID = uriPathID; + this.api = new BatchesApi(httpClient, context.getSmsServer(), authManagers, new HttpMapper()); } - private BatchesApi getApi() { + protected BatchesApi getApi() { return this.api; } public > T get(String batchId) throws ApiException { - return BatchDtoConverter.convert( - getApi().getBatchMessage(configuration.getProjectId(), batchId)); + return BatchDtoConverter.convert(getApi().getBatchMessage(uriPathID, batchId)); } public > T send(BaseBatch batch) throws ApiException { - return BatchDtoConverter.convert( - getApi().sendSMS(configuration.getProjectId(), BatchDtoConverter.convert(batch))); + return BatchDtoConverter.convert(getApi().sendSMS(uriPathID, BatchDtoConverter.convert(batch))); } public DryRun dryRun(boolean perRecipient, int numberOfRecipient, BaseBatch batch) { return DryRunDtoConverter.convert( getApi() - .dryRun( - configuration.getProjectId(), - perRecipient, - numberOfRecipient, - BatchDtoConverter.convert(batch))); + .dryRun(uriPathID, perRecipient, numberOfRecipient, BatchDtoConverter.convert(batch))); } public BatchesListResponse list() throws ApiException { @@ -71,7 +65,7 @@ public BatchesListResponse list(BatchesListRequestParameters parameters) throws ApiBatchListDto response = getApi() .listBatches( - configuration.getProjectId(), + uriPathID, guardParameters.getPage().orElse(null), guardParameters.getPageSize().orElse(null), guardParameters.getFrom().orElse(null), @@ -89,26 +83,20 @@ public BatchesListResponse list(BatchesListRequestParameters parameters) throws public > T update(String batchId, UpdateBaseBatchRequest batch) throws ApiException { return BatchDtoConverter.convert( - getApi() - .updateBatchMessage( - configuration.getProjectId(), batchId, BatchDtoConverter.convert(batch))); + getApi().updateBatchMessage(uriPathID, batchId, BatchDtoConverter.convert(batch))); } public > T replace(String batchId, BaseBatch batch) throws ApiException { return BatchDtoConverter.convert( - getApi() - .replaceBatch(configuration.getProjectId(), batchId, BatchDtoConverter.convert(batch))); + getApi().replaceBatch(uriPathID, batchId, BatchDtoConverter.convert(batch))); } public > T cancel(String batchId) throws ApiException { - return BatchDtoConverter.convert( - getApi().cancelBatchMessage(configuration.getProjectId(), batchId)); + return BatchDtoConverter.convert(getApi().cancelBatchMessage(uriPathID, batchId)); } public void sendDeliveryFeedback(String batchId, Collection recipients) throws ApiException { - getApi() - .deliveryFeedback( - configuration.getProjectId(), batchId, BatchDtoConverter.convert(recipients)); + getApi().deliveryFeedback(uriPathID, batchId, BatchDtoConverter.convert(recipients)); } } diff --git a/client/src/main/com/sinch/sdk/domains/sms/adapters/DeliveryReportsService.java b/client/src/main/com/sinch/sdk/domains/sms/adapters/DeliveryReportsService.java index fb88cb0a..77cb2b1f 100644 --- a/client/src/main/com/sinch/sdk/domains/sms/adapters/DeliveryReportsService.java +++ b/client/src/main/com/sinch/sdk/domains/sms/adapters/DeliveryReportsService.java @@ -16,7 +16,7 @@ import com.sinch.sdk.domains.sms.models.requests.DeliveryReportBatchGetRequestParameters; import com.sinch.sdk.domains.sms.models.requests.DeliveryReportListRequestParameters; import com.sinch.sdk.domains.sms.models.responses.DeliveryReportsListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.SmsContext; import java.time.Instant; import java.util.Collection; import java.util.Map; @@ -36,21 +36,21 @@ */ public class DeliveryReportsService implements com.sinch.sdk.domains.sms.DeliveryReportsService { - private Configuration configuration; - private DeliveryReportsApi api; + private final String uriPathID; + private final DeliveryReportsApi api; - public DeliveryReportsService() {} - - private DeliveryReportsApi getApi() { + protected DeliveryReportsApi getApi() { return this.api; } public DeliveryReportsService( - Configuration configuration, HttpClient httpClient, Map authManagers) { - this.configuration = configuration; + String uriPathID, + SmsContext context, + HttpClient httpClient, + Map authManagers) { + this.uriPathID = uriPathID; this.api = - new DeliveryReportsApi( - httpClient, configuration.getSmsServer(), authManagers, new HttpMapper()); + new DeliveryReportsApi(httpClient, context.getSmsServer(), authManagers, new HttpMapper()); } public DeliveryReportBatch get(String batchId, DeliveryReportBatchGetRequestParameters parameters) @@ -62,7 +62,7 @@ public DeliveryReportBatch get(String batchId, DeliveryReportBatchGetRequestPara return DeliveryReportDtoConverter.convert( getApi() .getDeliveryReportByBatchId( - configuration.getProjectId(), + uriPathID, batchId, guardParameters.getType().map(DeliveryReportType::value).orElse(null), guardParameters @@ -78,7 +78,7 @@ public DeliveryReportBatch get(String batchId, DeliveryReportBatchGetRequestPara public DeliveryReportRecipient getForNumber(String batchId, String recipient) throws ApiException { return DeliveryReportDtoConverter.convert( - getApi().getDeliveryReportByPhoneNumber(configuration.getProjectId(), batchId, recipient)); + getApi().getDeliveryReportByPhoneNumber(uriPathID, batchId, recipient)); } public DeliveryReportsListResponse list() throws ApiException { @@ -93,7 +93,7 @@ public DeliveryReportsListResponse list(DeliveryReportListRequestParameters para DeliveryReportListDto response = getApi() .getDeliveryReports( - configuration.getProjectId(), + uriPathID, guardParameters.getPage().orElse(null), guardParameters.getPageSize().orElse(null), guardParameters.getStartDate().map(Instant::toString).orElse(null), diff --git a/client/src/main/com/sinch/sdk/domains/sms/adapters/GroupsService.java b/client/src/main/com/sinch/sdk/domains/sms/adapters/GroupsService.java index f2e582b4..f04c4c0d 100644 --- a/client/src/main/com/sinch/sdk/domains/sms/adapters/GroupsService.java +++ b/client/src/main/com/sinch/sdk/domains/sms/adapters/GroupsService.java @@ -16,31 +16,31 @@ import com.sinch.sdk.domains.sms.models.requests.GroupUpdateRequestParameters; import com.sinch.sdk.domains.sms.models.requests.GroupsListRequestParameters; import com.sinch.sdk.domains.sms.models.responses.GroupsListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.SmsContext; import java.util.Collection; import java.util.Map; public class GroupsService implements com.sinch.sdk.domains.sms.GroupsService { - private Configuration configuration; - private GroupsApi api; + private final String uriPathID; + private final GroupsApi api; - public GroupsService() {} - - private GroupsApi getApi() { + protected GroupsApi getApi() { return this.api; } public GroupsService( - Configuration configuration, HttpClient httpClient, Map authManagers) { - this.configuration = configuration; - this.api = - new GroupsApi(httpClient, configuration.getSmsServer(), authManagers, new HttpMapper()); + String uriPathID, + SmsContext context, + HttpClient httpClient, + Map authManagers) { + this.uriPathID = uriPathID; + this.api = new GroupsApi(httpClient, context.getSmsServer(), authManagers, new HttpMapper()); } public Group get(String groupId) throws ApiException { - CreateGroupResponseDto response = getApi().retrieveGroup(configuration.getProjectId(), groupId); + CreateGroupResponseDto response = getApi().retrieveGroup(uriPathID, groupId); return GroupsDtoConverter.convert(response); } @@ -53,8 +53,7 @@ public Group create(GroupCreateRequestParameters parameters) throws ApiException null != parameters ? parameters : GroupCreateRequestParameters.builder().build(); CreateGroupResponseDto response = - getApi() - .createGroup(configuration.getProjectId(), GroupsDtoConverter.convert(guardParameters)); + getApi().createGroup(uriPathID, GroupsDtoConverter.convert(guardParameters)); return GroupsDtoConverter.convert(response); } @@ -69,7 +68,7 @@ public GroupsListResponse list(GroupsListRequestParameters parameters) throws Ap ApiGroupListDto response = getApi() .listGroups( - configuration.getProjectId(), + uriPathID, guardParameters.getPage().orElse(null), guardParameters.getPageSize().orElse(null)); @@ -86,9 +85,7 @@ public Group replace(String groupId, GroupReplaceRequestParameters parameters) null != parameters ? parameters : GroupReplaceRequestParameters.builder().build(); CreateGroupResponseDto response = - getApi() - .replaceGroup( - configuration.getProjectId(), groupId, GroupsDtoConverter.convert(guardParameters)); + getApi().replaceGroup(uriPathID, groupId, GroupsDtoConverter.convert(guardParameters)); return GroupsDtoConverter.convert(response); } @@ -97,17 +94,15 @@ public Group update(String groupId, GroupUpdateRequestParameters parameters) thr null != parameters ? parameters : GroupUpdateRequestParameters.builder().build(); CreateGroupResponseDto response = - getApi() - .updateGroup( - configuration.getProjectId(), groupId, GroupsDtoConverter.convert(guardParameters)); + getApi().updateGroup(uriPathID, groupId, GroupsDtoConverter.convert(guardParameters)); return GroupsDtoConverter.convert(response); } public void delete(String groupId) throws ApiException { - getApi().deleteGroup(configuration.getProjectId(), groupId); + getApi().deleteGroup(uriPathID, groupId); } public Collection listMembers(String groupId) throws ApiException { - return getApi().getMembers(configuration.getProjectId(), groupId); + return getApi().getMembers(uriPathID, groupId); } } diff --git a/client/src/main/com/sinch/sdk/domains/sms/adapters/InboundsService.java b/client/src/main/com/sinch/sdk/domains/sms/adapters/InboundsService.java index e896211f..92a63399 100644 --- a/client/src/main/com/sinch/sdk/domains/sms/adapters/InboundsService.java +++ b/client/src/main/com/sinch/sdk/domains/sms/adapters/InboundsService.java @@ -13,27 +13,27 @@ import com.sinch.sdk.domains.sms.models.dto.v1.InboundDto; import com.sinch.sdk.domains.sms.models.requests.InboundsListRequestParameters; import com.sinch.sdk.domains.sms.models.responses.InboundsListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.SmsContext; import java.time.Instant; import java.util.Collection; import java.util.Map; public class InboundsService implements com.sinch.sdk.domains.sms.InboundsService { - private Configuration configuration; - private InboundsApi api; + private final String uriPathID; + private final InboundsApi api; - public InboundsService() {} - - private InboundsApi getApi() { + protected InboundsApi getApi() { return this.api; } public InboundsService( - Configuration configuration, HttpClient httpClient, Map authManagers) { - this.configuration = configuration; - this.api = - new InboundsApi(httpClient, configuration.getSmsServer(), authManagers, new HttpMapper()); + String uriPathID, + SmsContext context, + HttpClient httpClient, + Map authManagers) { + this.uriPathID = uriPathID; + this.api = new InboundsApi(httpClient, context.getSmsServer(), authManagers, new HttpMapper()); } public InboundsListResponse list() throws ApiException { @@ -47,7 +47,7 @@ public InboundsListResponse list(InboundsListRequestParameters parameters) throw ApiInboundListDto response = getApi() .listInboundMessages( - configuration.getProjectId(), + uriPathID, guardParameters.getPage().orElse(null), guardParameters.getPageSize().orElse(null), guardParameters.getTo().map(f -> String.join(",", f)).orElse(null), @@ -64,7 +64,7 @@ public InboundsListResponse list(InboundsListRequestParameters parameters) throw public Inbound get(String inboundId) throws ApiException { - InboundDto response = getApi().retrieveInboundMessage(configuration.getProjectId(), inboundId); + InboundDto response = getApi().retrieveInboundMessage(uriPathID, inboundId); return InboundsDtoConverter.convert(response); } } diff --git a/client/src/main/com/sinch/sdk/domains/sms/adapters/SMSService.java b/client/src/main/com/sinch/sdk/domains/sms/adapters/SMSService.java index 813010ea..11f8f892 100644 --- a/client/src/main/com/sinch/sdk/domains/sms/adapters/SMSService.java +++ b/client/src/main/com/sinch/sdk/domains/sms/adapters/SMSService.java @@ -1,24 +1,33 @@ package com.sinch.sdk.domains.sms.adapters; import com.sinch.sdk.auth.adapters.BearerAuthManager; +import com.sinch.sdk.auth.adapters.OAuthManager; import com.sinch.sdk.core.http.AuthManager; import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.core.http.HttpMapper; +import com.sinch.sdk.core.models.ServerConfiguration; import com.sinch.sdk.core.utils.StringUtil; import com.sinch.sdk.domains.sms.BatchesService; import com.sinch.sdk.domains.sms.DeliveryReportsService; import com.sinch.sdk.domains.sms.InboundsService; import com.sinch.sdk.domains.sms.WebHooksService; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.SmsContext; +import com.sinch.sdk.models.SmsServicePlanCredentials; +import com.sinch.sdk.models.UnifiedCredentials; import java.util.AbstractMap; import java.util.Map; +import java.util.Objects; +import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; public class SMSService implements com.sinch.sdk.domains.sms.SMSService { - private static final String SECURITY_SCHEME_KEYWORD_SMS = "BearerAuth"; - private final Configuration configuration; + private static final Logger LOGGER = Logger.getLogger(SMSService.class.getName()); + + private static final String SECURITY_SCHEME_KEYWORD_SMS = "BearerAuth"; + private final String uriUUID; + private final SmsContext context; private final HttpClient httpClient; private BatchesService batches; private WebHooksService webHooks; @@ -27,22 +36,52 @@ public class SMSService implements com.sinch.sdk.domains.sms.SMSService { private GroupsService groups; private final Map authManagers; - public SMSService(Configuration configuration, HttpClient httpClient) { + public SMSService( + UnifiedCredentials credentials, + SmsContext context, + ServerConfiguration oAuthServer, + HttpClient httpClient) { - // Currently, we are only supporting unified credentials: ensure credentials are - // defined - StringUtil.requireNonEmpty(configuration.getKeyId(), "'keyId' must be defined"); - StringUtil.requireNonEmpty(configuration.getKeySecret(), "'keySecret' must be defined"); - StringUtil.requireNonEmpty(configuration.getProjectId(), "'projectId' must be defined"); + Objects.requireNonNull(credentials, "Credentials must be defined"); + Objects.requireNonNull(context, "Context must be defined"); + StringUtil.requireNonEmpty(credentials.getKeyId(), "'keyId' must be defined"); + StringUtil.requireNonEmpty(credentials.getKeySecret(), "'keySecret' must be defined"); + StringUtil.requireNonEmpty(credentials.getProjectId(), "'projectId' must be defined"); + StringUtil.requireNonEmpty(context.getSmsUrl(), "'smsUrl' must be defined"); - this.configuration = configuration; + LOGGER.fine("Activate SMS API with server='" + context.getSmsServer().getUrl() + "'"); + + OAuthManager oAuthManager = + new OAuthManager(credentials, oAuthServer, new HttpMapper(), httpClient); + + this.uriUUID = credentials.getProjectId(); + this.context = context; this.httpClient = httpClient; + this.authManagers = + Stream.of(new AbstractMap.SimpleEntry<>(SECURITY_SCHEME_KEYWORD_SMS, oAuthManager)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + public SMSService( + SmsServicePlanCredentials credentials, SmsContext context, HttpClient httpClient) { + + Objects.requireNonNull(credentials, "Credentials must be defined"); + Objects.requireNonNull(context, "Context must be defined"); + StringUtil.requireNonEmpty(credentials.getServicePlanId(), "'servicePlanId' must be defined"); + StringUtil.requireNonEmpty(credentials.getApiToken(), "'apiToken' must be defined"); - BearerAuthManager bearerAuthManager = - new BearerAuthManager(configuration, new HttpMapper(), httpClient); + LOGGER.fine( + "Activate SMS API with service plan ID support and server='" + + context.getSmsServer().getUrl() + + "'"); - authManagers = - Stream.of(new AbstractMap.SimpleEntry<>(SECURITY_SCHEME_KEYWORD_SMS, bearerAuthManager)) + BearerAuthManager authManager = new BearerAuthManager(credentials.getApiToken()); + + this.uriUUID = credentials.getServicePlanId(); + this.context = context; + this.httpClient = httpClient; + this.authManagers = + Stream.of(new AbstractMap.SimpleEntry<>(SECURITY_SCHEME_KEYWORD_SMS, authManager)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @@ -51,7 +90,7 @@ public BatchesService batches() { if (null == this.batches) { this.batches = new com.sinch.sdk.domains.sms.adapters.BatchesService( - configuration, httpClient, authManagers); + uriUUID, context, httpClient, authManagers); } return this.batches; } @@ -69,7 +108,7 @@ public DeliveryReportsService deliveryReports() { if (null == this.deliveryReports) { this.deliveryReports = new com.sinch.sdk.domains.sms.adapters.DeliveryReportsService( - configuration, httpClient, authManagers); + uriUUID, context, httpClient, authManagers); } return this.deliveryReports; } @@ -79,7 +118,7 @@ public InboundsService inbounds() { if (null == this.inbounds) { this.inbounds = new com.sinch.sdk.domains.sms.adapters.InboundsService( - configuration, httpClient, authManagers); + uriUUID, context, httpClient, authManagers); } return this.inbounds; } @@ -89,7 +128,7 @@ public GroupsService groups() { if (null == this.groups) { this.groups = new com.sinch.sdk.domains.sms.adapters.GroupsService( - configuration, httpClient, authManagers); + uriUUID, context, httpClient, authManagers); } return this.groups; } diff --git a/client/src/main/com/sinch/sdk/domains/verification/adapters/VerificationService.java b/client/src/main/com/sinch/sdk/domains/verification/adapters/VerificationService.java index ec6ae9c8..9fc782fc 100644 --- a/client/src/main/com/sinch/sdk/domains/verification/adapters/VerificationService.java +++ b/client/src/main/com/sinch/sdk/domains/verification/adapters/VerificationService.java @@ -9,19 +9,23 @@ import com.sinch.sdk.domains.verification.VerificationStatusService; import com.sinch.sdk.domains.verification.VerificationsService; import com.sinch.sdk.domains.verification.WebHooksService; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.ApplicationCredentials; +import com.sinch.sdk.models.VerificationContext; import java.util.Map; +import java.util.Objects; import java.util.TreeMap; +import java.util.logging.Logger; public class VerificationService implements com.sinch.sdk.domains.verification.VerificationService { + private static final Logger LOGGER = Logger.getLogger(VerificationService.class.getName()); // FIXME: Verification OAS file claim it support "Basic" but miss the "Application" definition // trick to adapt the mapping of "Basic" keyword to the dedicated "Application" auth manager private static final String BASIC_SECURITY_SCHEME_KEYWORD_VERIFICATION = "Basic"; private static final String APPLICATION_SECURITY_SCHEME_KEYWORD_VERIFICATION = "Application"; - private final Configuration configuration; + private final VerificationContext context; private final HttpClient httpClient; private VerificationsService verifications; private VerificationStatusService verificationStatus; @@ -29,25 +33,33 @@ public class VerificationService implements com.sinch.sdk.domains.verification.V private Map clientAuthManagers; private Map webhooksAuthManagers; - public VerificationService(Configuration configuration, HttpClient httpClient) { + public VerificationService( + ApplicationCredentials credentials, VerificationContext context, HttpClient httpClient) { // Currently, we are not supporting unified credentials: ensure application credentials are // defined + Objects.requireNonNull(credentials, "Credentials must be defined"); + Objects.requireNonNull(context, "Context must be defined"); + StringUtil.requireNonEmpty(credentials.getApplicationKey(), "'applicationKey' must be defined"); StringUtil.requireNonEmpty( - configuration.getApplicationKey(), "'applicationKey' must be defined"); - StringUtil.requireNonEmpty( - configuration.getApplicationSecret(), "'applicationSecret' must be defined"); + credentials.getApplicationSecret(), "'applicationSecret' must be defined"); + StringUtil.requireNonEmpty(context.getVerificationUrl(), "'verificationUrl' must be defined"); + + LOGGER.fine( + "Activate verification API with server='" + context.getVerificationServer().getUrl() + "'"); - this.configuration = configuration; + this.context = context; this.httpClient = httpClient; - setApplicationCredentials( - configuration.getApplicationKey(), configuration.getApplicationSecret()); + setApplicationCredentials(credentials); } - private void setApplicationCredentials(String key, String secret) { + private void setApplicationCredentials(ApplicationCredentials credentials) { - AuthManager basicAuthManager = new BasicAuthManager(key, secret); - AuthManager applicationAuthManager = new ApplicationAuthManager(key, secret); + AuthManager basicAuthManager = + new BasicAuthManager(credentials.getApplicationKey(), credentials.getApplicationSecret()); + AuthManager applicationAuthManager = + new ApplicationAuthManager( + credentials.getApplicationKey(), credentials.getApplicationSecret()); boolean useApplicationAuth = true; // to handle request from client we can only have "Basic" keyword behind the auth managers @@ -73,7 +85,7 @@ public VerificationsService verifications() { checkCredentials(); this.verifications = new com.sinch.sdk.domains.verification.adapters.VerificationsService( - configuration, httpClient, clientAuthManagers); + context, httpClient, clientAuthManagers); } return this.verifications; } @@ -83,7 +95,7 @@ public VerificationStatusService verificationStatus() { checkCredentials(); this.verificationStatus = new com.sinch.sdk.domains.verification.adapters.VerificationStatusService( - configuration, httpClient, clientAuthManagers); + context, httpClient, clientAuthManagers); } return this.verificationStatus; } diff --git a/client/src/main/com/sinch/sdk/domains/verification/adapters/VerificationStatusService.java b/client/src/main/com/sinch/sdk/domains/verification/adapters/VerificationStatusService.java index cba983f3..2f1b6208 100644 --- a/client/src/main/com/sinch/sdk/domains/verification/adapters/VerificationStatusService.java +++ b/client/src/main/com/sinch/sdk/domains/verification/adapters/VerificationStatusService.java @@ -10,7 +10,7 @@ import com.sinch.sdk.domains.verification.models.VerificationMethodType; import com.sinch.sdk.domains.verification.models.VerificationReference; import com.sinch.sdk.domains.verification.models.VerificationReport; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.VerificationContext; import java.util.Map; public class VerificationStatusService @@ -19,10 +19,10 @@ public class VerificationStatusService private final QueryVerificationsApi api; public VerificationStatusService( - Configuration configuration, HttpClient httpClient, Map authManagers) { + VerificationContext context, HttpClient httpClient, Map authManagers) { this.api = new QueryVerificationsApi( - httpClient, configuration.getVerificationServer(), authManagers, new HttpMapper()); + httpClient, context.getVerificationServer(), authManagers, new HttpMapper()); } protected QueryVerificationsApi getApi() { diff --git a/client/src/main/com/sinch/sdk/domains/verification/adapters/VerificationsService.java b/client/src/main/com/sinch/sdk/domains/verification/adapters/VerificationsService.java index e3ee36ea..8761419a 100644 --- a/client/src/main/com/sinch/sdk/domains/verification/adapters/VerificationsService.java +++ b/client/src/main/com/sinch/sdk/domains/verification/adapters/VerificationsService.java @@ -25,7 +25,7 @@ import com.sinch.sdk.domains.verification.models.response.StartVerificationResponseFlashCall; import com.sinch.sdk.domains.verification.models.response.StartVerificationResponseSMS; import com.sinch.sdk.domains.verification.models.response.StartVerificationResponseSeamless; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.VerificationContext; import java.util.Map; public class VerificationsService @@ -34,10 +34,10 @@ public class VerificationsService private final SendingAndReportingVerificationsApi api; public VerificationsService( - Configuration configuration, HttpClient httpClient, Map authManagers) { + VerificationContext context, HttpClient httpClient, Map authManagers) { this.api = new SendingAndReportingVerificationsApi( - httpClient, configuration.getVerificationServer(), authManagers, new HttpMapper()); + httpClient, context.getVerificationServer(), authManagers, new HttpMapper()); } protected SendingAndReportingVerificationsApi getApi() { diff --git a/client/src/main/com/sinch/sdk/domains/voice/adapters/ApplicationsService.java b/client/src/main/com/sinch/sdk/domains/voice/adapters/ApplicationsService.java index c6952919..8f05602f 100644 --- a/client/src/main/com/sinch/sdk/domains/voice/adapters/ApplicationsService.java +++ b/client/src/main/com/sinch/sdk/domains/voice/adapters/ApplicationsService.java @@ -9,8 +9,8 @@ import com.sinch.sdk.domains.voice.models.NumberInformation; import com.sinch.sdk.domains.voice.models.requests.ApplicationsAssignNumbersRequestParameters; import com.sinch.sdk.domains.voice.models.response.AssignedNumbers; -import com.sinch.sdk.models.Configuration; import com.sinch.sdk.models.E164PhoneNumber; +import com.sinch.sdk.models.VoiceContext; import java.util.Map; public class ApplicationsService implements com.sinch.sdk.domains.voice.ApplicationsService { @@ -18,11 +18,11 @@ public class ApplicationsService implements com.sinch.sdk.domains.voice.Applicat private final ApplicationsApi api; public ApplicationsService( - Configuration configuration, HttpClient httpClient, Map authManagers) { + VoiceContext context, HttpClient httpClient, Map authManagers) { this.api = new ApplicationsApi( httpClient, - configuration.getVoiceApplicationManagementServer(), + context.getVoiceApplicationManagementServer(), authManagers, new HttpMapper()); } diff --git a/client/src/main/com/sinch/sdk/domains/voice/adapters/CalloutsService.java b/client/src/main/com/sinch/sdk/domains/voice/adapters/CalloutsService.java index 2b66ec34..85948d06 100644 --- a/client/src/main/com/sinch/sdk/domains/voice/adapters/CalloutsService.java +++ b/client/src/main/com/sinch/sdk/domains/voice/adapters/CalloutsService.java @@ -9,7 +9,7 @@ import com.sinch.sdk.domains.voice.models.requests.CalloutRequestParametersConference; import com.sinch.sdk.domains.voice.models.requests.CalloutRequestParametersCustom; import com.sinch.sdk.domains.voice.models.requests.CalloutRequestParametersTTS; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.VoiceContext; import java.util.Map; public class CalloutsService implements com.sinch.sdk.domains.voice.CalloutsService { @@ -17,9 +17,9 @@ public class CalloutsService implements com.sinch.sdk.domains.voice.CalloutsServ private final CalloutsApi api; public CalloutsService( - Configuration configuration, HttpClient httpClient, Map authManagers) { + VoiceContext context, HttpClient httpClient, Map authManagers) { this.api = - new CalloutsApi(httpClient, configuration.getVoiceServer(), authManagers, new HttpMapper()); + new CalloutsApi(httpClient, context.getVoiceServer(), authManagers, new HttpMapper()); } protected CalloutsApi getApi() { diff --git a/client/src/main/com/sinch/sdk/domains/voice/adapters/CallsService.java b/client/src/main/com/sinch/sdk/domains/voice/adapters/CallsService.java index 7c5a94f0..8806c1c5 100644 --- a/client/src/main/com/sinch/sdk/domains/voice/adapters/CallsService.java +++ b/client/src/main/com/sinch/sdk/domains/voice/adapters/CallsService.java @@ -8,7 +8,7 @@ import com.sinch.sdk.domains.voice.models.CallLegType; import com.sinch.sdk.domains.voice.models.response.CallInformation; import com.sinch.sdk.domains.voice.models.svaml.SVAMLControl; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.VoiceContext; import java.util.Map; public class CallsService implements com.sinch.sdk.domains.voice.CallsService { @@ -16,9 +16,8 @@ public class CallsService implements com.sinch.sdk.domains.voice.CallsService { private final CallsApi api; public CallsService( - Configuration configuration, HttpClient httpClient, Map authManagers) { - this.api = - new CallsApi(httpClient, configuration.getVoiceServer(), authManagers, new HttpMapper()); + VoiceContext context, HttpClient httpClient, Map authManagers) { + this.api = new CallsApi(httpClient, context.getVoiceServer(), authManagers, new HttpMapper()); } protected CallsApi getApi() { diff --git a/client/src/main/com/sinch/sdk/domains/voice/adapters/ConferencesService.java b/client/src/main/com/sinch/sdk/domains/voice/adapters/ConferencesService.java index 45f4078b..49e07997 100644 --- a/client/src/main/com/sinch/sdk/domains/voice/adapters/ConferencesService.java +++ b/client/src/main/com/sinch/sdk/domains/voice/adapters/ConferencesService.java @@ -9,7 +9,7 @@ import com.sinch.sdk.domains.voice.models.requests.CalloutRequestParametersConference; import com.sinch.sdk.domains.voice.models.requests.ConferenceManageParticipantRequestParameters; import com.sinch.sdk.domains.voice.models.response.ConferenceParticipant; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.VoiceContext; import java.util.Collection; import java.util.Map; @@ -18,10 +18,9 @@ public class ConferencesService implements com.sinch.sdk.domains.voice.Conferenc private final ConferencesApi api; public ConferencesService( - Configuration configuration, HttpClient httpClient, Map authManagers) { + VoiceContext context, HttpClient httpClient, Map authManagers) { this.api = - new ConferencesApi( - httpClient, configuration.getVoiceServer(), authManagers, new HttpMapper()); + new ConferencesApi(httpClient, context.getVoiceServer(), authManagers, new HttpMapper()); } protected ConferencesApi getApi() { diff --git a/client/src/main/com/sinch/sdk/domains/voice/adapters/VoiceService.java b/client/src/main/com/sinch/sdk/domains/voice/adapters/VoiceService.java index 56ec0cd9..045df590 100644 --- a/client/src/main/com/sinch/sdk/domains/voice/adapters/VoiceService.java +++ b/client/src/main/com/sinch/sdk/domains/voice/adapters/VoiceService.java @@ -9,11 +9,15 @@ import com.sinch.sdk.domains.voice.ApplicationsService; import com.sinch.sdk.domains.voice.CalloutsService; import com.sinch.sdk.domains.voice.WebHooksService; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.ApplicationCredentials; +import com.sinch.sdk.models.VoiceContext; import java.util.Map; +import java.util.Objects; import java.util.TreeMap; +import java.util.logging.Logger; public class VoiceService implements com.sinch.sdk.domains.voice.VoiceService { + private static final Logger LOGGER = Logger.getLogger(VoiceService.class.getName()); private static final String SECURITY_SCHEME_KEYWORD = "Signed"; @@ -21,7 +25,7 @@ public class VoiceService implements com.sinch.sdk.domains.voice.VoiceService { private static final String APPLICATION_SECURITY_SCHEME_KEYWORD = "Application"; - private final Configuration configuration; + private final VoiceContext context; private final HttpClient httpClient; private CalloutsService callouts; private ConferencesService conferences; @@ -32,25 +36,31 @@ public class VoiceService implements com.sinch.sdk.domains.voice.VoiceService { private Map clientAuthManagers; private Map webhooksAuthManagers; - public VoiceService(Configuration configuration, HttpClient httpClient) { + public VoiceService( + ApplicationCredentials credentials, VoiceContext context, HttpClient httpClient) { // Currently, we are not supporting unified credentials: ensure application credentials are // defined + Objects.requireNonNull(credentials, "Credentials must be defined"); + Objects.requireNonNull(context, "Context must be defined"); + StringUtil.requireNonEmpty(credentials.getApplicationKey(), "'applicationKey' must be defined"); StringUtil.requireNonEmpty( - configuration.getApplicationKey(), "'applicationKey' must be defined"); - StringUtil.requireNonEmpty( - configuration.getApplicationSecret(), "'applicationSecret' must be defined"); + credentials.getApplicationSecret(), "'applicationSecret' must be defined"); + + LOGGER.fine("Activate voice API with server='" + context.getVoiceServer().getUrl() + "'"); - this.configuration = configuration; + this.context = context; this.httpClient = httpClient; - setApplicationCredentials( - configuration.getApplicationKey(), configuration.getApplicationSecret()); + setApplicationCredentials(credentials); } - private void setApplicationCredentials(String key, String secret) { + private void setApplicationCredentials(ApplicationCredentials credentials) { - AuthManager basicAuthManager = new BasicAuthManager(key, secret); - AuthManager applicationAuthManager = new ApplicationAuthManager(key, secret); + AuthManager basicAuthManager = + new BasicAuthManager(credentials.getApplicationKey(), credentials.getApplicationSecret()); + AuthManager applicationAuthManager = + new ApplicationAuthManager( + credentials.getApplicationKey(), credentials.getApplicationSecret()); clientAuthManagers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); clientAuthManagers.put(SECURITY_SCHEME_KEYWORD, applicationAuthManager); @@ -67,7 +77,7 @@ public CalloutsService callouts() { checkCredentials(); this.callouts = new com.sinch.sdk.domains.voice.adapters.CalloutsService( - configuration, httpClient, clientAuthManagers); + context, httpClient, clientAuthManagers); } return this.callouts; } @@ -77,7 +87,7 @@ public ConferencesService conferences() { checkCredentials(); this.conferences = new com.sinch.sdk.domains.voice.adapters.ConferencesService( - configuration, httpClient, clientAuthManagers); + context, httpClient, clientAuthManagers); } return this.conferences; } @@ -87,7 +97,7 @@ public CallsService calls() { checkCredentials(); this.calls = new com.sinch.sdk.domains.voice.adapters.CallsService( - configuration, httpClient, clientAuthManagers); + context, httpClient, clientAuthManagers); } return this.calls; } @@ -97,7 +107,7 @@ public ApplicationsService applications() { checkCredentials(); this.applications = new com.sinch.sdk.domains.voice.adapters.ApplicationsService( - configuration, httpClient, clientAuthManagers); + context, httpClient, clientAuthManagers); } return this.applications; } diff --git a/client/src/main/com/sinch/sdk/http/HttpClientApache.java b/client/src/main/com/sinch/sdk/http/HttpClientApache.java index b6972072..5be5c105 100644 --- a/client/src/main/com/sinch/sdk/http/HttpClientApache.java +++ b/client/src/main/com/sinch/sdk/http/HttpClientApache.java @@ -1,11 +1,11 @@ package com.sinch.sdk.http; -import static com.sinch.sdk.auth.adapters.BearerAuthManager.BEARER_AUTHENTICATE_RESPONSE_HEADER_KEYWORD; -import static com.sinch.sdk.auth.adapters.BearerAuthManager.BEARER_EXPIRED_KEYWORD; +import static com.sinch.sdk.auth.adapters.OAuthManager.BEARER_AUTHENTICATE_RESPONSE_HEADER_KEYWORD; +import static com.sinch.sdk.auth.adapters.OAuthManager.BEARER_EXPIRED_KEYWORD; import static com.sinch.sdk.core.http.HttpContentType.CONTENT_TYPE_HEADER; import static com.sinch.sdk.core.http.URLParameterUtils.encodeParametersAsString; -import com.sinch.sdk.auth.adapters.BearerAuthManager; +import com.sinch.sdk.auth.adapters.OAuthManager; import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.core.http.AuthManager; import com.sinch.sdk.core.http.HttpMethod; @@ -159,7 +159,7 @@ private boolean processUnauthorizedResponse( .map(authManager -> new AbstractMap.SimpleEntry<>(authManager.getSchema(), authManager)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a1, a2) -> a1)); AuthManager bearerAuthManager = - authManagersByAuthSchemes.get(BearerAuthManager.SCHEMA_KEYWORD_BEARER); + authManagersByAuthSchemes.get(OAuthManager.SCHEMA_KEYWORD_BEARER); if (null == bearerAuthManager) { // no bearer manager registered return false; @@ -174,7 +174,7 @@ private boolean processUnauthorizedResponse( && authManagersByOasSecuritySchemes .get(f) .getSchema() - .equals(BearerAuthManager.SCHEMA_KEYWORD_BEARER)) + .equals(OAuthManager.SCHEMA_KEYWORD_BEARER)) .findFirst(); if (!requestSupportBearerAuthentication.isPresent()) { diff --git a/client/src/main/com/sinch/sdk/models/ApplicationCredentials.java b/client/src/main/com/sinch/sdk/models/ApplicationCredentials.java new file mode 100644 index 00000000..f1f0e50a --- /dev/null +++ b/client/src/main/com/sinch/sdk/models/ApplicationCredentials.java @@ -0,0 +1,128 @@ +package com.sinch.sdk.models; + +/** + * Credentials related to Voice/Verification authentication + * + * @since 1.0 + */ +public class ApplicationCredentials { + + private final String applicationKey; + private final String applicationSecret; + + private ApplicationCredentials(String applicationKey, String applicationSecret) { + this.applicationKey = applicationKey; + this.applicationSecret = applicationSecret; + } + + /** + * Application key to be used for Verification and Voice services + * + *

Use application secret in place of unified configuration for authentication (see Sinch + * dashboard for details) These credentials are related to Verification & Voice Apps + * + * @return Application key + * @see Sinch + * Documentation + * @since 1.0 + */ + public String getApplicationKey() { + return applicationKey; + } + + /** + * Application secret to be used for Verification and Voice services + * + *

Use application secret in place of unified configuration for authentication (see Sinch + * dashboard for details) These credentials are related to Verification & Voice Apps + * + * @return Application key + * @see Sinch + * Documentation + * @since 1.0 + */ + public String getApplicationSecret() { + return applicationSecret; + } + + /** + * Getting Builder + * + * @return New Builder instance + * @since 1.0 + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Getting Builder + * + * @param credentials Source credentials to fill initial builder state + * @return New Builder instance + * @since 1.0 + */ + public static Builder builder(ApplicationCredentials credentials) { + return new Builder(credentials); + } + + /** + * Dedicated Builder + * + * @since 1.0 + */ + public static class Builder { + + String applicationKey; + String applicationSecret; + + protected Builder() {} + + /** + * Initialize a builder with existing credentials + * + * @param credentials Credentials to be used as initial builder state + * @since 1.0 + */ + protected Builder(ApplicationCredentials credentials) { + this.applicationKey = null != credentials ? credentials.getApplicationKey() : null; + this.applicationSecret = null != credentials ? credentials.getApplicationSecret() : null; + } + + /** + * Set Application secret + * + * @param applicationKey Application key to be used + * @return Current builder + * @since 1.0 + */ + public Builder setApplicationKey(String applicationKey) { + this.applicationKey = applicationKey; + return this; + } + + /** + * Set Application secret + * + * @param applicationSecret Application secret to be used + * @return Current builder + * @since 1.0 + */ + public Builder setApplicationSecret(String applicationSecret) { + this.applicationSecret = applicationSecret; + return this; + } + + /** + * Create instance + * + * @return The instance build with current builder values + * @since 1.0 + */ + public ApplicationCredentials build() { + return new ApplicationCredentials(applicationKey, applicationSecret); + } + } +} diff --git a/client/src/main/com/sinch/sdk/models/Configuration.java b/client/src/main/com/sinch/sdk/models/Configuration.java index 0f351bcc..b1bb618a 100644 --- a/client/src/main/com/sinch/sdk/models/Configuration.java +++ b/client/src/main/com/sinch/sdk/models/Configuration.java @@ -1,52 +1,37 @@ package com.sinch.sdk.models; import com.sinch.sdk.core.models.ServerConfiguration; +import java.util.Optional; /** Configuration used by Sinch Client */ public class Configuration { - private final String keyId; - private final String keySecret; - private final String projectId; + private final UnifiedCredentials unifiedCredentials; + private final ApplicationCredentials applicationCredentials; + private final SmsServicePlanCredentials smsServicePlanCredentials; private final String oauthUrl; - private final String numbersUrl; - private final SMSRegion smsRegion; - private final String smsUrl; - private final String verificationUrl; - private final VoiceRegion voiceRegion; - private final String voiceUrl; - private final String voiceApplicationManagementUrl; - - private final String applicationKey; - private final String applicationSecret; + private final NumbersContext numbersContext; + private final SmsContext smsContext; + private final VerificationContext verificationContext; + private final VoiceContext voiceContext; private Configuration( - String keyId, - String keySecret, - String projectId, + UnifiedCredentials unifiedCredentials, + ApplicationCredentials applicationCredentials, + SmsServicePlanCredentials smsServicePlanCredentials, String oauthUrl, - String numbersUrl, - SMSRegion smsRegion, - String smsUrl, - String verificationUrl, - VoiceRegion voiceRegion, - String voiceUrl, - String voiceApplicationManagementUrl, - String applicationKey, - String applicationSecret) { - this.keyId = keyId; - this.keySecret = keySecret; - this.projectId = projectId; + NumbersContext numbersContext, + SmsContext smsContext, + VerificationContext verificationContext, + VoiceContext voiceContext) { + this.unifiedCredentials = unifiedCredentials; + this.applicationCredentials = applicationCredentials; + this.smsServicePlanCredentials = smsServicePlanCredentials; this.oauthUrl = oauthUrl; - this.numbersUrl = numbersUrl; - this.smsRegion = null == smsRegion ? SMSRegion.US : smsRegion; - this.smsUrl = smsUrl; - this.verificationUrl = verificationUrl; - this.voiceRegion = voiceRegion; - this.voiceUrl = voiceUrl; - this.voiceApplicationManagementUrl = voiceApplicationManagementUrl; - this.applicationKey = applicationKey; - this.applicationSecret = applicationSecret; + this.numbersContext = numbersContext; + this.smsContext = smsContext; + this.voiceContext = voiceContext; + this.verificationContext = verificationContext; } @Override @@ -55,59 +40,36 @@ public String toString() { + "oauthUrl='" + oauthUrl + '\'' - + ", numbersUrl='" - + numbersUrl - + '\'' - + ", smsRegion=" - + smsRegion - + ", smsUrl='" - + smsUrl - + '\'' - + ", verificationUrl='" - + verificationUrl - + '\'' - + ", voiceRegion=" - + voiceRegion - + ", voiceUrl='" - + voiceUrl - + '\'' - + ", voiceApplicationMngmtUrl='" - + voiceApplicationManagementUrl - + '\'' + + ", numbersContext=" + + numbersContext + + ", smsContext=" + + smsContext + + ", verificationContext=" + + verificationContext + + ", voiceContext=" + + voiceContext + '}'; } /** - * Get Key ID + * Get Sinch unified credentials * - * @return key id. + * @return Credentials * @see https://developers.sinch.com/ * @since 1.0 */ - public String getKeyId() { - return keyId; + public Optional getUnifiedCredentials() { + return Optional.ofNullable(unifiedCredentials); } /** - * Get key ID + * Get SMS service plan ID credentials * - * @return key secret. - * @see https://developers.sinch.com/ + * @return Credentials * @since 1.0 */ - public String getKeySecret() { - return keySecret; - } - - /** - * Get Project ID - * - * @return Project id. - * @see https://developers.sinch.com/ - * @since 1.0 - */ - public String getProjectId() { - return projectId; + public Optional getSmsServicePlanCredentials() { + return Optional.ofNullable(smsServicePlanCredentials); } /** @@ -131,157 +93,56 @@ public String getOAuthUrl() { } /** - * Numbers Server Configuration - * - * @return Numbers Server configuration to be used - * @since 1.0 - */ - public ServerConfiguration getNumbersServer() { - return new ServerConfiguration(getNumbersUrl()); - } - - /** - * Numbers URL - * - * @return Numbers Server URL - * @since 1.0 - */ - public String getNumbersUrl() { - return numbersUrl; - } - - /** - * SMS Server Configuration - * - * @return SMS Server configuration to be used - * @since 1.0 - */ - public ServerConfiguration getSmsServer() { - return new ServerConfiguration(String.format(getSmsUrl(), getSmsRegion())); - } - - /** - * SMS Region - * - * @return SMS region - * @see https://developers.sinch.com/docs/sms/api-reference/#base-url/ - * @since 1.0 - */ - public SMSRegion getSmsRegion() { - return smsRegion; - } - - /** - * SMS URL - * - * @return SMS Server URL - * @since 1.0 - */ - public String getSmsUrl() { - return smsUrl; - } - - /** - * Verification Server Configuration - * - * @return Verification Server configuration to be used - * @since 1.0 - */ - public ServerConfiguration getVerificationServer() { - return new ServerConfiguration(getVerificationUrl()); - } - - /** - * Verification URL - * - * @return Verification Server URL - * @since 1.0 - */ - public String getVerificationUrl() { - return verificationUrl; - } - - /** - * Voice region - * - * @return Selected Voice Region - * @since 1.0 - */ - public VoiceRegion getVoiceRegion() { - return voiceRegion; - } - - /** - * Voice URL + * Get Numbers domain related execution context * - * @return Voice Server URL + * @return Current Numbers context * @since 1.0 */ - public String getVoiceUrl() { - return voiceUrl; + public Optional getNumbersContext() { + return Optional.ofNullable(numbersContext); } /** - * Voice Server Configuration + * Get SMS domain related execution context * - * @return Voice Server configuration to be used + * @return Current SMS context * @since 1.0 */ - public ServerConfiguration getVoiceServer() { - return new ServerConfiguration(getVoiceUrl()); + public Optional getSmsContext() { + return Optional.ofNullable(smsContext); } /** - * Voice Application Management URL + * Get Verification domain related execution context * - * @return Voice Application Management URL + * @return Current Verification context * @since 1.0 */ - public String getVoiceApplicationManagementUrl() { - return voiceApplicationManagementUrl; + public Optional getVerificationContext() { + return Optional.ofNullable(verificationContext); } /** - * Voice Application Management Configuration + * Get Voice domain related execution context * - * @return Voice Application Management to be used + * @return Current Voice context * @since 1.0 */ - public ServerConfiguration getVoiceApplicationManagementServer() { - return new ServerConfiguration(getVoiceApplicationManagementUrl()); + public Optional getVoiceContext() { + return Optional.ofNullable(voiceContext); } /** - * Application key to be used for Verification and Voice services + * Credentials to be used for Verification and Voice services * - *

Use application secret in place of unified configuration for authentication (see Sinch - * dashboard for details) These credentials are related to Verification & Voice Apps - * - * @return Application key - * @see Sinch - * Documentation - * @since 1.0 - */ - public String getApplicationKey() { - return applicationKey; - } - - /** - * Application secret to be used for Verification and Voice services - * - *

Use application secret in place of unified configuration for authentication (see Sinch - * dashboard for details) These credentials are related to Verification & Voice Apps - * - * @return Application key + * @return Application credentials * @see Sinch * Documentation * @since 1.0 */ - public String getApplicationSecret() { - return applicationSecret; + public Optional getApplicationCredentials() { + return Optional.ofNullable(applicationCredentials); } /** @@ -312,19 +173,14 @@ public static Builder builder(Configuration configuration) { */ public static class Builder { - String keyId; - String keySecret; - String projectId; + UnifiedCredentials.Builder unifiedCredentials; + ApplicationCredentials.Builder applicationCredentials; + SmsServicePlanCredentials.Builder smsServicePlanCredentials; String oauthUrl; - String numbersUrl; - SMSRegion smsRegion; - String smsUrl; - String verificationUrl; - String applicationKey; - String applicationSecret; - VoiceRegion voiceRegion; - String voiceUrl; - String voiceApplicationMngmtUrl; + NumbersContext.Builder numbersContext; + SmsContext.Builder smsContext; + VerificationContext.Builder verificationContext; + VoiceContext.Builder voiceContext; protected Builder() {} @@ -335,19 +191,25 @@ protected Builder() {} * @since 1.0 */ protected Builder(Configuration configuration) { - this.keyId = configuration.getKeyId(); - this.keySecret = configuration.getKeySecret(); - this.projectId = configuration.getProjectId(); + this.unifiedCredentials = + configuration.getUnifiedCredentials().map(UnifiedCredentials::builder).orElse(null); + this.applicationCredentials = + configuration + .getApplicationCredentials() + .map(ApplicationCredentials::builder) + .orElse(null); + this.smsServicePlanCredentials = + configuration + .getSmsServicePlanCredentials() + .map(SmsServicePlanCredentials::builder) + .orElse(null); this.oauthUrl = configuration.getOAuthUrl(); - this.numbersUrl = configuration.getNumbersUrl(); - this.smsRegion = configuration.getSmsRegion(); - this.smsUrl = configuration.getSmsUrl(); - this.verificationUrl = configuration.getVerificationUrl(); - this.applicationKey = configuration.getApplicationKey(); - this.applicationSecret = configuration.getApplicationSecret(); - this.voiceRegion = configuration.getVoiceRegion(); - this.voiceUrl = configuration.getVoiceUrl(); - this.voiceApplicationMngmtUrl = configuration.getVoiceApplicationManagementUrl(); + this.numbersContext = + configuration.getNumbersContext().map(NumbersContext::builder).orElse(null); + this.smsContext = configuration.getSmsContext().map(SmsContext::builder).orElse(null); + this.verificationContext = + configuration.getVerificationContext().map(VerificationContext::builder).orElse(null); + this.voiceContext = configuration.getVoiceContext().map(VoiceContext::builder).orElse(null); } /** @@ -355,10 +217,14 @@ protected Builder(Configuration configuration) { * * @param keyId key ID * @return Current builder + * @see UnifiedCredentials#getKeyId() getter * @since 1.0 */ public Builder setKeyId(String keyId) { - this.keyId = keyId; + if (null == this.unifiedCredentials) { + this.unifiedCredentials = UnifiedCredentials.builder(); + } + this.unifiedCredentials.setKeyId(keyId); return this; } @@ -367,10 +233,14 @@ public Builder setKeyId(String keyId) { * * @param keySecret key secret * @return Current builder + * @see UnifiedCredentials#getKeySecret() getter * @since 1.0 */ public Builder setKeySecret(String keySecret) { - this.keySecret = keySecret; + if (null == this.unifiedCredentials) { + this.unifiedCredentials = UnifiedCredentials.builder(); + } + this.unifiedCredentials.setKeySecret(keySecret); return this; } @@ -379,155 +249,167 @@ public Builder setKeySecret(String keySecret) { * * @param projectId Project ID * @return Current builder + * @see UnifiedCredentials#getProjectId() getter * @since 1.0 */ public Builder setProjectId(String projectId) { - this.projectId = projectId; + if (null == this.unifiedCredentials) { + this.unifiedCredentials = UnifiedCredentials.builder(); + } + this.unifiedCredentials.setProjectId(projectId); return this; } /** - * Set OAuth URL + * Set Application key * - * @param oauthUrl OAuth URL + * @param applicationKey key * @return Current builder + * @see ApplicationCredentials#getApplicationKey() getter * @since 1.0 */ - public Builder setOAuthUrl(String oauthUrl) { - this.oauthUrl = oauthUrl; + public Builder setApplicationKey(String applicationKey) { + if (null == this.applicationCredentials) { + this.applicationCredentials = ApplicationCredentials.builder(); + } + this.applicationCredentials.setApplicationKey(applicationKey); return this; } /** - * Set Numbers API URL + * Set Application secret * - * @param numbersUrl Numbers API URL + * @param applicationSecret key * @return Current builder + * @see ApplicationCredentials#getApplicationSecret() () getter * @since 1.0 */ - public Builder setNumbersUrl(String numbersUrl) { - this.numbersUrl = numbersUrl; + public Builder setApplicationSecret(String applicationSecret) { + if (null == this.applicationCredentials) { + this.applicationCredentials = ApplicationCredentials.builder(); + } + this.applicationCredentials.setApplicationSecret(applicationSecret); return this; } /** - * Set SMS region + * Set OAuth URL * - * @param smsRegion SMS region + * @param oauthUrl OAuth URL * @return Current builder * @since 1.0 */ - public Builder setSmsRegion(SMSRegion smsRegion) { - this.smsRegion = smsRegion; + public Builder setOAuthUrl(String oauthUrl) { + this.oauthUrl = oauthUrl; return this; } /** - * Set SMS API URL + * Set Numbers related context * - * @param smsUrl SMS API URL + * @param context {@link #getNumbersContext()} () getter} * @return Current builder * @since 1.0 */ - public Builder setSmsUrl(String smsUrl) { - this.smsUrl = smsUrl; + public Builder setNumbersContext(NumbersContext context) { + this.numbersContext = null != context ? NumbersContext.builder(context) : null; return this; } /** - * Set Verification API URL + * Set SMS related service plan ID * - * @param verificationUrl Verification API URL + * @param servicePlanId {@link SmsServicePlanCredentials#getServicePlanId() getter} * @return Current builder * @since 1.0 */ - public Builder setVerificationUrl(String verificationUrl) { - this.verificationUrl = verificationUrl; + public Builder setSmsServicePlanId(String servicePlanId) { + if (null == this.smsServicePlanCredentials) { + this.smsServicePlanCredentials = SmsServicePlanCredentials.builder(); + } + this.smsServicePlanCredentials.setServicePlanId(servicePlanId); return this; } /** - * Set region to be used for Vioce service + * Set SMS related service plan token * - * @param voiceRegion The regino + * @param token {@link SmsServicePlanCredentials#getApiToken()} () getter} * @return Current builder * @since 1.0 */ - public Builder setVoiceRegion(VoiceRegion voiceRegion) { - this.voiceRegion = voiceRegion; + public Builder setSmsApiToken(String token) { + if (null == this.smsServicePlanCredentials) { + this.smsServicePlanCredentials = SmsServicePlanCredentials.builder(); + } + this.smsServicePlanCredentials.setApiToken(token); return this; } /** - * Set Voice URL to be used + * Set SMS related region * - * @param voiceUrl Voice URL + * @param region {@link SmsContext#getSmsRegion()} () getter} * @return Current builder * @since 1.0 */ - public Builder setVoiceUrl(String voiceUrl) { - this.voiceUrl = voiceUrl; + public Builder setSmsRegion(SMSRegion region) { + if (null == this.smsContext) { + this.smsContext = SmsContext.builder(); + } + this.smsContext.setSmsRegion(region); return this; } /** - * Set URL dedicated to Voice Application management to be used + * Set Sms related context * - * @param voiceApplicationMngmtUrl Voice Application Management URL + * @param context {@link #getSmsContext()} ()} () getter} * @return Current builder * @since 1.0 */ - public Builder setVoiceApplicationMngmtUrl(String voiceApplicationMngmtUrl) { - this.voiceApplicationMngmtUrl = voiceApplicationMngmtUrl; + public Builder setSmsContext(SmsContext context) { + this.smsContext = null != context ? SmsContext.builder(context) : null; return this; } /** - * Set Application secret + * Set Verification related context * - * @param applicationKey Application key to be used + * @param context {@link #getVerificationContext() getter} * @return Current builder * @since 1.0 */ - public Builder setApplicationKey(String applicationKey) { - this.applicationKey = applicationKey; + public Builder setVerificationContext(VerificationContext context) { + this.verificationContext = null != context ? VerificationContext.builder(context) : null; return this; } /** - * Set Application secret + * Set Voice related region * - * @param applicationSecret Application secret to be used + * @param region {@link VoiceContext#getVoiceRegion() getter} * @return Current builder * @since 1.0 */ - public Builder setApplicationSecret(String applicationSecret) { - this.applicationSecret = applicationSecret; + public Builder setVoiceRegion(VoiceRegion region) { + if (null == this.voiceContext) { + this.voiceContext = VoiceContext.builder(); + } + this.voiceContext.setVoiceRegion(region); return this; } /** - * Setter - * - *

See {@link Configuration#getVoiceRegion()} getter - * - * @return Current builder - * @since 1.0 - */ - public VoiceRegion getVoiceRegion() { - return voiceRegion; - } - - /** - * Setter - * - *

See {@link Configuration#getVoiceUrl()} getter + * Set Voice related context * + * @param context {@link #getVoiceContext() getter} * @return Current builder * @since 1.0 */ - public String getVoiceUrl() { - return voiceUrl; + public Builder setVoiceContext(VoiceContext context) { + this.voiceContext = null != context ? VoiceContext.builder(context) : null; + return this; } /** @@ -537,20 +419,16 @@ public String getVoiceUrl() { * @since 1.0 */ public Configuration build() { + return new Configuration( - keyId, - keySecret, - projectId, + null != unifiedCredentials ? unifiedCredentials.build() : null, + null != applicationCredentials ? applicationCredentials.build() : null, + null != smsServicePlanCredentials ? smsServicePlanCredentials.build() : null, oauthUrl, - numbersUrl, - smsRegion, - smsUrl, - verificationUrl, - voiceRegion, - voiceUrl, - voiceApplicationMngmtUrl, - applicationKey, - applicationSecret); + null != numbersContext ? numbersContext.build() : null, + null != smsContext ? smsContext.build() : null, + null != verificationContext ? verificationContext.build() : null, + null != voiceContext ? voiceContext.build() : null); } } } diff --git a/client/src/main/com/sinch/sdk/models/NumbersContext.java b/client/src/main/com/sinch/sdk/models/NumbersContext.java new file mode 100644 index 00000000..f8633fe0 --- /dev/null +++ b/client/src/main/com/sinch/sdk/models/NumbersContext.java @@ -0,0 +1,94 @@ +package com.sinch.sdk.models; + +import com.sinch.sdk.core.models.ServerConfiguration; +import com.sinch.sdk.models.UnifiedCredentials.Builder; + +/** Execution context related to Numbers domains */ +public class NumbersContext { + + private final String numbersUrl; + + private NumbersContext(String numbersUrl) { + this.numbersUrl = numbersUrl; + } + + /** + * Numbers Server Configuration + * + * @return Numbers Server configuration to be used + * @since 1.0 + */ + public ServerConfiguration getNumbersServer() { + return new ServerConfiguration(getNumbersUrl()); + } + + /** + * Numbers URL + * + * @return Numbers Server URL + * @since 1.0 + */ + public String getNumbersUrl() { + return numbersUrl; + } + + /** + * Getting Builder + * + * @return New Builder instance + * @since 1.0 + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Getting Builder + * + * @param context Source context to fill initial builder state + * @return New Builder instance + * @since 1.0 + */ + public static Builder builder(NumbersContext context) { + return new Builder(context); + } + + /** + * Dedicated Builder + * + * @since 1.0 + */ + public static class Builder { + + String numbersUrl; + + protected Builder() {} + + protected Builder(NumbersContext context) { + this.numbersUrl = null != context ? context.getNumbersUrl() : null; + } + + /** + * Set Numbers API URL + * + * @param numbersUrl Numbers API URL + * @return Current builder + * @since 1.0 + */ + public Builder setNumbersUrl(String numbersUrl) { + this.numbersUrl = numbersUrl; + return this; + } + + /** + * Create instance + * + * @return The instance build with current builder values + * @since 1.0 + */ + public NumbersContext build() { + + return new NumbersContext(numbersUrl); + } + } +} diff --git a/client/src/main/com/sinch/sdk/models/SmsContext.java b/client/src/main/com/sinch/sdk/models/SmsContext.java new file mode 100644 index 00000000..4b4b34db --- /dev/null +++ b/client/src/main/com/sinch/sdk/models/SmsContext.java @@ -0,0 +1,128 @@ +package com.sinch.sdk.models; + +import com.sinch.sdk.core.models.ServerConfiguration; +import com.sinch.sdk.models.Configuration.Builder; + +/** Execution context related to Voice domains */ +public class SmsContext { + + private final SMSRegion smsRegion; + private final String smsUrl; + + public SmsContext(SMSRegion smsRegion, String smsUrl) { + this.smsRegion = null == smsRegion ? SMSRegion.US : smsRegion; + this.smsUrl = smsUrl; + } + + /** + * SMS Server Configuration + * + * @return SMS Server configuration to be used + * @since 1.0 + */ + public ServerConfiguration getSmsServer() { + return new ServerConfiguration(String.format(getSmsUrl(), getSmsRegion())); + } + + /** + * SMS Region + * + * @return SMS region + * @see https://developers.sinch.com/docs/sms/api-reference/#base-url/ + * @since 1.0 + */ + public SMSRegion getSmsRegion() { + return smsRegion; + } + + /** + * SMS URL + * + * @return SMS Server URL + * @since 1.0 + */ + public String getSmsUrl() { + return smsUrl; + } + + /** + * Getting Builder + * + * @return New Builder instance + * @since 1.0 + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Getting Builder + * + * @param configuration Source configuration to fill initial builder state + * @return New Builder instance + * @since 1.0 + */ + public static Builder builder(SmsContext configuration) { + return new Builder(configuration); + } + + /** + * Dedicated Builder + * + * @since 1.0 + */ + public static class Builder { + + SMSRegion smsRegion; + String smsUrl; + + protected Builder() {} + + /** + * Initialize a builder with existing configuration + * + * @param context Configuration to be used as initial builder state + * @since 1.0 + */ + protected Builder(SmsContext context) { + this.smsRegion = null != context ? context.getSmsRegion() : null; + this.smsUrl = null != context ? context.getSmsUrl() : null; + } + + /** + * Set SMS region + * + * @param smsRegion SMS region + * @return Current builder + * @since 1.0 + */ + public Builder setSmsRegion(SMSRegion smsRegion) { + this.smsRegion = smsRegion; + return this; + } + + /** + * Set SMS API URL + * + * @param smsUrl SMS API URL + * @return Current builder + * @since 1.0 + */ + public Builder setSmsUrl(String smsUrl) { + this.smsUrl = smsUrl; + return this; + } + + /** + * Create instance + * + * @return The instance build with current builder values + * @since 1.0 + */ + public SmsContext build() { + + return new SmsContext(smsRegion, smsUrl); + } + } +} diff --git a/client/src/main/com/sinch/sdk/models/SmsServicePlanCredentials.java b/client/src/main/com/sinch/sdk/models/SmsServicePlanCredentials.java new file mode 100644 index 00000000..eeaa4c47 --- /dev/null +++ b/client/src/main/com/sinch/sdk/models/SmsServicePlanCredentials.java @@ -0,0 +1,117 @@ +package com.sinch.sdk.models; + +/** + * Credentials related to SMS authentication based onto service plan + * + * @see Dashboard + * @since 1.0 + */ +public class SmsServicePlanCredentials { + + private final String servicePlanId; + private final String apiToken; + + private SmsServicePlanCredentials(String servicePlanId, String apiToken) { + this.servicePlanId = servicePlanId; + this.apiToken = apiToken; + } + + /** + * Service plan ID - + * + * @return service plan ID + * @since 1.0 + */ + public String getServicePlanId() { + return servicePlanId; + } + + /** + * Service plan token + * + * @return service plan token + * @since 1.0 + */ + public String getApiToken() { + return apiToken; + } + + /** + * Getting Builder + * + * @return New Builder instance + * @since 1.0 + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Getting Builder + * + * @param credentials Source credentials to fill initial builder state + * @return New Builder instance + * @since 1.0 + */ + public static Builder builder(SmsServicePlanCredentials credentials) { + return new Builder(credentials); + } + + /** + * Dedicated Builder + * + * @since 1.0 + */ + public static class Builder { + + String servicePlanId; + String apiToken; + + protected Builder() {} + + /** + * Initialize a builder with existing credentials + * + * @param credentials Credentials to be used as initial builder state + * @since 1.0 + */ + protected Builder(SmsServicePlanCredentials credentials) { + this.servicePlanId = null != credentials ? credentials.getServicePlanId() : null; + this.apiToken = null != credentials ? credentials.getApiToken() : null; + } + + /** + * Set service plan ID + * + * @param servicePlanId See {@link #getServicePlanId() getter} + * @return Current builder + * @since 1.0 + */ + public Builder setServicePlanId(String servicePlanId) { + this.servicePlanId = servicePlanId; + return this; + } + + /** + * Set service plan token + * + * @param apiToken See {@link #getApiToken() getter} + * @return Current builder + * @since 1.0 + */ + public Builder setApiToken(String apiToken) { + this.apiToken = apiToken; + return this; + } + + /** + * Create instance + * + * @return The instance build with current builder values + * @since 1.0 + */ + public SmsServicePlanCredentials build() { + return new SmsServicePlanCredentials(servicePlanId, apiToken); + } + } +} diff --git a/client/src/main/com/sinch/sdk/models/UnifiedCredentials.java b/client/src/main/com/sinch/sdk/models/UnifiedCredentials.java new file mode 100644 index 00000000..85384673 --- /dev/null +++ b/client/src/main/com/sinch/sdk/models/UnifiedCredentials.java @@ -0,0 +1,150 @@ +package com.sinch.sdk.models; + +/** + * Credentials related to unified Sinch authentication + * + * @since 1.0 + */ +public class UnifiedCredentials { + + private final String keyId; + private final String keySecret; + private final String projectId; + + private UnifiedCredentials(String keyId, String keySecret, String projectId) { + this.keyId = keyId; + this.keySecret = keySecret; + this.projectId = projectId; + } + + /** + * Get Key ID + * + * @return key id. + * @see https://developers.sinch.com/ + * @since 1.0 + */ + public String getKeyId() { + return keyId; + } + + /** + * Get key secret + * + * @return key secret. + * @see https://developers.sinch.com/ + * @since 1.0 + */ + public String getKeySecret() { + return keySecret; + } + + /** + * Get Project ID + * + * @return Project id. + * @see https://developers.sinch.com/ + * @since 1.0 + */ + public String getProjectId() { + return projectId; + } + + @Override + public String toString() { + return "UnifiedCredentials{" + "keyId='***'" + ", keySecret='***'" + ", projectId='***'" + '}'; + } + + /** + * Getting Builder + * + * @return New Builder instance + * @since 1.0 + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Getting Builder + * + * @param credentials Source credentials to fill initial builder state + * @return New Builder instance + * @since 1.0 + */ + static Builder builder(UnifiedCredentials credentials) { + return new Builder(credentials); + } + + /** + * Dedicated Builder + * + * @since 1.0 + */ + public static class Builder { + + String keyId; + String keySecret; + String projectId; + + protected Builder() {} + + /** + * Initialize a builder with existing credentials + * + * @param credentials Credentials to be used as initial builder state + * @since 1.0 + */ + protected Builder(UnifiedCredentials credentials) { + this.keyId = credentials.getKeyId(); + this.keySecret = credentials.getKeySecret(); + this.projectId = credentials.getProjectId(); + } + + /** + * Set key ID + * + * @param keyId key ID + * @return Current builder + * @since 1.0 + */ + public Builder setKeyId(String keyId) { + this.keyId = keyId; + return this; + } + + /** + * Set key secret + * + * @param keySecret key secret + * @return Current builder + * @since 1.0 + */ + public Builder setKeySecret(String keySecret) { + this.keySecret = keySecret; + return this; + } + + /** + * Set Project ID + * + * @param projectId Project ID + * @return Current builder + * @since 1.0 + */ + public Builder setProjectId(String projectId) { + this.projectId = projectId; + return this; + } + + /** + * Create instance + * + * @return The instance build with current builder values + * @since 1.0 + */ + public UnifiedCredentials build() { + return new UnifiedCredentials(keyId, keySecret, projectId); + } + } +} diff --git a/client/src/main/com/sinch/sdk/models/VerificationContext.java b/client/src/main/com/sinch/sdk/models/VerificationContext.java new file mode 100644 index 00000000..5d740076 --- /dev/null +++ b/client/src/main/com/sinch/sdk/models/VerificationContext.java @@ -0,0 +1,99 @@ +package com.sinch.sdk.models; + +import com.sinch.sdk.core.models.ServerConfiguration; + +/** Execution context related to Verification domains */ +public class VerificationContext { + + private final String verificationUrl; + + private VerificationContext(String verificationUrl) { + this.verificationUrl = verificationUrl; + } + + /** + * Verification Server Configuration + * + * @return Verification Server configuration to be used + * @since 1.0 + */ + public ServerConfiguration getVerificationServer() { + return new ServerConfiguration(getVerificationUrl()); + } + + /** + * Verification URL + * + * @return Verification Server URL + * @since 1.0 + */ + public String getVerificationUrl() { + return verificationUrl; + } + + /** + * Getting Builder + * + * @return New Builder instance + * @since 1.0 + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Getting Builder + * + * @param configuration Source configuration to fill initial builder state + * @return New Builder instance + * @since 1.0 + */ + public static Builder builder(VerificationContext configuration) { + return new Builder(configuration); + } + + /** + * Dedicated Builder + * + * @since 1.0 + */ + public static class Builder { + + String verificationUrl; + + protected Builder() {} + + /** + * Initialize a builder with existing configuration + * + * @param context Configuration to be used as initial builder state + * @since 1.0 + */ + protected Builder(VerificationContext context) { + this.verificationUrl = null != context ? context.getVerificationUrl() : null; + } + + /** + * Set Verification API URL + * + * @param verificationUrl Verification API URL + * @return Current builder + * @since 1.0 + */ + public Builder setVerificationUrl(String verificationUrl) { + this.verificationUrl = verificationUrl; + return this; + } + + /** + * Create instance + * + * @return The instance build with current builder values + * @since 1.0 + */ + public VerificationContext build() { + + return new VerificationContext(verificationUrl); + } + } +} diff --git a/client/src/main/com/sinch/sdk/models/VoiceContext.java b/client/src/main/com/sinch/sdk/models/VoiceContext.java new file mode 100644 index 00000000..780ac49a --- /dev/null +++ b/client/src/main/com/sinch/sdk/models/VoiceContext.java @@ -0,0 +1,163 @@ +package com.sinch.sdk.models; + +import com.sinch.sdk.core.models.ServerConfiguration; + +/** Execution context related to Voice domains */ +public class VoiceContext { + + private final VoiceRegion voiceRegion; + private final String voiceUrl; + private final String voiceApplicationManagementUrl; + + public VoiceContext( + VoiceRegion voiceRegion, String voiceUrl, String voiceApplicationManagementUrl) { + this.voiceRegion = voiceRegion; + this.voiceUrl = voiceUrl; + this.voiceApplicationManagementUrl = voiceApplicationManagementUrl; + } + + /** + * Voice region + * + * @return Selected Voice Region + * @since 1.0 + */ + public VoiceRegion getVoiceRegion() { + return voiceRegion; + } + + /** + * Voice URL + * + * @return Voice Server URL + * @since 1.0 + */ + public String getVoiceUrl() { + return voiceUrl; + } + + /** + * Voice Server Configuration + * + * @return Voice Server configuration to be used + * @since 1.0 + */ + public ServerConfiguration getVoiceServer() { + return new ServerConfiguration(getVoiceUrl()); + } + + /** + * Voice Application Management URL + * + * @return Voice Application Management URL + * @since 1.0 + */ + public String getVoiceApplicationManagementUrl() { + return voiceApplicationManagementUrl; + } + + /** + * Voice Application Management Configuration + * + * @return Voice Application Management to be used + * @since 1.0 + */ + public ServerConfiguration getVoiceApplicationManagementServer() { + return new ServerConfiguration(getVoiceApplicationManagementUrl()); + } + + /** + * Getting Builder + * + * @return New Builder instance + * @since 1.0 + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Getting Builder + * + * @param configuration Source configuration to fill initial builder state + * @return New Builder instance + * @since 1.0 + */ + public static Builder builder(VoiceContext configuration) { + return new Builder(configuration); + } + + /** + * Dedicated Builder + * + * @since 1.0 + */ + public static class Builder { + + VoiceRegion voiceRegion; + String voiceUrl; + String voiceApplicationMngmtUrl; + + protected Builder() {} + + /** + * Initialize a builder with existing configuration + * + * @param context Configuration to be used as initial builder state + * @since 1.0 + */ + protected Builder(VoiceContext context) { + this.voiceRegion = null != context ? context.getVoiceRegion() : null; + this.voiceUrl = null != context ? context.getVoiceUrl() : null; + this.voiceApplicationMngmtUrl = + null != context ? context.getVoiceApplicationManagementUrl() : null; + } + + /** + * Set region to be used for Voice service + * + * @param voiceRegion The region + * @return Current builder + * @since 1.0 + */ + public Builder setVoiceRegion(VoiceRegion voiceRegion) { + this.voiceRegion = voiceRegion; + return this; + } + + /** + * Set Voice URL to be used + * + * @param voiceUrl Voice URL + * @return Current builder + * @since 1.0 + */ + public Builder setVoiceUrl(String voiceUrl) { + this.voiceUrl = voiceUrl; + return this; + } + + /** + * Set URL dedicated to Voice Application management to be used + * + * @param voiceApplicationMngmtUrl Voice Application Management URL + * @return Current builder + * @since 1.0 + */ + public Builder setVoiceApplicationMngmtUrl(String voiceApplicationMngmtUrl) { + this.voiceApplicationMngmtUrl = voiceApplicationMngmtUrl; + return this; + } + + /** + * Create instance + * + * @return The instance build with current builder values + * @since 1.0 + */ + public VoiceContext build() { + + return new VoiceContext(voiceRegion, voiceUrl, voiceApplicationMngmtUrl); + } + } +} diff --git a/client/src/test/java/com/sinch/sdk/SinchClientTest.java b/client/src/test/java/com/sinch/sdk/SinchClientTest.java index 70093bd1..9ac490cf 100644 --- a/client/src/test/java/com/sinch/sdk/SinchClientTest.java +++ b/client/src/test/java/com/sinch/sdk/SinchClientTest.java @@ -4,6 +4,7 @@ import com.sinch.sdk.core.utils.StringUtil; import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.VoiceContext; import com.sinch.sdk.models.VoiceRegion; import org.junit.jupiter.api.Test; @@ -22,7 +23,7 @@ void defaultNumbersUrlAvailable() { Configuration configuration = Configuration.builder().setKeyId("foo").setKeySecret("foo").setProjectId("foo").build(); SinchClient client = new SinchClient(configuration); - assertNotNull(client.getConfiguration().getNumbersUrl()); + assertNotNull(client.getConfiguration().getNumbersContext().get().getNumbersUrl()); } @Test @@ -30,7 +31,7 @@ void defaultSmsUrlAvailable() { Configuration configuration = Configuration.builder().setKeyId("foo").setKeySecret("foo").setProjectId("foo").build(); SinchClient client = new SinchClient(configuration); - assertNotNull(client.getConfiguration().getSmsUrl()); + assertNotNull(client.getConfiguration().getSmsContext().get().getSmsUrl()); } @Test @@ -38,7 +39,7 @@ void defaultVerificationUrlAvailable() { Configuration configuration = Configuration.builder().setKeyId("foo").setKeySecret("foo").setProjectId("foo").build(); SinchClient client = new SinchClient(configuration); - assertNotNull(client.getConfiguration().getVerificationUrl()); + assertNotNull(client.getConfiguration().getVerificationContext().get().getVerificationUrl()); } @Test @@ -46,7 +47,8 @@ void defaultVoiceUrl() { Configuration configuration = Configuration.builder().setKeyId("foo").setKeySecret("foo").setProjectId("foo").build(); SinchClient client = new SinchClient(configuration); - assertFalse(StringUtil.isEmpty(client.getConfiguration().getVoiceUrl())); + assertFalse( + StringUtil.isEmpty(client.getConfiguration().getVoiceContext().get().getVoiceUrl())); } @Test @@ -54,7 +56,9 @@ void defaultVoiceApplicationManagementUrl() { Configuration configuration = Configuration.builder().setKeyId("foo").setKeySecret("foo").setProjectId("foo").build(); SinchClient client = new SinchClient(configuration); - assertFalse(StringUtil.isEmpty(client.getConfiguration().getVoiceApplicationManagementUrl())); + assertFalse( + StringUtil.isEmpty( + client.getConfiguration().getVoiceContext().get().getVoiceApplicationManagementUrl())); } @Test @@ -64,10 +68,12 @@ void voiceUrlFromRegion() { .setKeyId("foo") .setKeySecret("foo") .setProjectId("foo") - .setVoiceRegion(VoiceRegion.EUROPE) + .setVoiceContext(VoiceContext.builder().setVoiceRegion(VoiceRegion.EUROPE).build()) .build(); SinchClient client = new SinchClient(configuration); - assertEquals(client.getConfiguration().getVoiceUrl(), "https://calling-euc1.api.sinch.com"); + assertEquals( + client.getConfiguration().getVoiceContext().get().getVoiceUrl(), + "https://calling-euc1.api.sinch.com"); } @Test @@ -77,12 +83,16 @@ void voiceUrlFromUrl() { .setKeyId("foo") .setKeySecret("foo") .setProjectId("foo") - .setVoiceRegion(VoiceRegion.EUROPE) - .setVoiceUrl("my foo url") + .setVoiceContext( + VoiceContext.builder() + .setVoiceRegion(VoiceRegion.EUROPE) + .setVoiceUrl("my foo url") + .build()) .build(); SinchClient client = new SinchClient(configuration); - assertEquals(client.getConfiguration().getVoiceRegion(), VoiceRegion.EUROPE); - assertEquals(client.getConfiguration().getVoiceUrl(), "my foo url"); + assertEquals( + client.getConfiguration().getVoiceContext().get().getVoiceRegion(), VoiceRegion.EUROPE); + assertEquals(client.getConfiguration().getVoiceContext().get().getVoiceUrl(), "my foo url"); } @Test @@ -92,9 +102,12 @@ void voiceApplicationManagementUrlFromUrl() { .setKeyId("foo") .setKeySecret("foo") .setProjectId("foo") - .setVoiceApplicationMngmtUrl("my foo url") + .setVoiceContext( + VoiceContext.builder().setVoiceApplicationMngmtUrl("my foo url").build()) .build(); SinchClient client = new SinchClient(configuration); - assertEquals(client.getConfiguration().getVoiceApplicationManagementUrl(), "my foo url"); + assertEquals( + client.getConfiguration().getVoiceContext().get().getVoiceApplicationManagementUrl(), + "my foo url"); } } diff --git a/client/src/test/java/com/sinch/sdk/SinchClientTestIT.java b/client/src/test/java/com/sinch/sdk/SinchClientTestIT.java index eaa16672..5075c6c1 100644 --- a/client/src/test/java/com/sinch/sdk/SinchClientTestIT.java +++ b/client/src/test/java/com/sinch/sdk/SinchClientTestIT.java @@ -5,6 +5,7 @@ import com.adelean.inject.resources.junit.jupiter.TestWithResources; import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.NumbersContext; import java.io.IOException; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; @@ -23,7 +24,7 @@ class SinchClientTestIT extends BaseTest { .setKeyId("foo") .setKeySecret("foo") .setProjectId("foo") - .setNumbersUrl(serverUrl) + .setNumbersContext(NumbersContext.builder().setNumbersUrl(serverUrl).build()) .build(); SinchClient sinchClient = new SinchClient(configuration); diff --git a/client/src/test/java/com/sinch/sdk/auth/adapters/BasicAuthManagerTest.java b/client/src/test/java/com/sinch/sdk/auth/adapters/BasicAuthManagerTest.java index 7d71c2f3..dfbc7c93 100644 --- a/client/src/test/java/com/sinch/sdk/auth/adapters/BasicAuthManagerTest.java +++ b/client/src/test/java/com/sinch/sdk/auth/adapters/BasicAuthManagerTest.java @@ -4,7 +4,7 @@ import com.sinch.sdk.core.http.AuthManager; import com.sinch.sdk.core.utils.Pair; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.UnifiedCredentials; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Collection; @@ -18,10 +18,10 @@ class BasicAuthManagerTest { static final String SECRET = "fooSecret"; static final String PROJECT = "fooProject"; - Configuration configuration = - Configuration.builder().setKeyId(KEY).setKeySecret(SECRET).setProjectId(PROJECT).build(); + UnifiedCredentials credentials = + UnifiedCredentials.builder().setKeyId(KEY).setKeySecret(SECRET).setProjectId(PROJECT).build(); - AuthManager authManager = new BasicAuthManager(configuration); + AuthManager authManager = new BasicAuthManager(credentials); @Test void getSchema() { @@ -38,7 +38,7 @@ void getAuthorizationHeaders() { "Basic " + Base64.getEncoder() .encodeToString( - (configuration.getKeyId() + ":" + configuration.getKeySecret()) + (credentials.getKeyId() + ":" + credentials.getKeySecret()) .getBytes(StandardCharsets.UTF_8)))); Collection> headers = diff --git a/client/src/test/java/com/sinch/sdk/auth/adapters/BearerAuthManagerTest.java b/client/src/test/java/com/sinch/sdk/auth/adapters/OAuthManagerTest.java similarity index 90% rename from client/src/test/java/com/sinch/sdk/auth/adapters/BearerAuthManagerTest.java rename to client/src/test/java/com/sinch/sdk/auth/adapters/OAuthManagerTest.java index affa6fb3..1d2dcd03 100644 --- a/client/src/test/java/com/sinch/sdk/auth/adapters/BearerAuthManagerTest.java +++ b/client/src/test/java/com/sinch/sdk/auth/adapters/OAuthManagerTest.java @@ -15,7 +15,7 @@ import com.sinch.sdk.core.http.HttpResponse; import com.sinch.sdk.core.models.ServerConfiguration; import com.sinch.sdk.core.utils.Pair; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.UnifiedCredentials; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Collections; @@ -27,7 +27,7 @@ import org.mockito.Mock; @TestWithResources -public class BearerAuthManagerTest extends BaseTest { +public class OAuthManagerTest extends BaseTest { static final String KEY = "fooKey"; static final String SECRET = "fooSecret"; static final String PROJECT = "fooProject"; @@ -38,19 +38,16 @@ public class BearerAuthManagerTest extends BaseTest { @Mock HttpClient httpClient; @Captor ArgumentCaptor serverConfigurationCaptor; @Captor ArgumentCaptor httpRequestCaptor; - Configuration configuration = - Configuration.builder() - .setKeyId(KEY) - .setKeySecret(SECRET) - .setProjectId(PROJECT) - .setOAuthUrl("OAuth url") - .build(); + UnifiedCredentials credentials = + UnifiedCredentials.builder().setKeyId(KEY).setKeySecret(SECRET).setProjectId(PROJECT).build(); AuthManager authManager; @BeforeEach public void initEach() { - authManager = new BearerAuthManager(configuration, new HttpMapper(), httpClient); + authManager = + new OAuthManager( + credentials, new ServerConfiguration("OAuth url"), new HttpMapper(), httpClient); } @Test diff --git a/client/src/test/java/com/sinch/sdk/core/adapters/apache/HttpClientTestIT.java b/client/src/test/java/com/sinch/sdk/core/adapters/apache/HttpClientTestIT.java index 071afc3e..bc5f6652 100644 --- a/client/src/test/java/com/sinch/sdk/core/adapters/apache/HttpClientTestIT.java +++ b/client/src/test/java/com/sinch/sdk/core/adapters/apache/HttpClientTestIT.java @@ -7,7 +7,7 @@ import com.adelean.inject.resources.junit.jupiter.TestWithResources; import com.sinch.sdk.BaseTest; import com.sinch.sdk.auth.adapters.BasicAuthManager; -import com.sinch.sdk.auth.adapters.BearerAuthManager; +import com.sinch.sdk.auth.adapters.OAuthManager; import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.core.http.AuthManager; import com.sinch.sdk.core.http.HttpMapper; @@ -16,7 +16,7 @@ import com.sinch.sdk.core.http.HttpStatus; import com.sinch.sdk.core.models.ServerConfiguration; import com.sinch.sdk.http.HttpClientApache; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.UnifiedCredentials; import java.io.IOException; import java.util.AbstractMap; import java.util.Collections; @@ -38,17 +38,15 @@ class HttpClientTestIT extends BaseTest { String jsonResponse; String serverUrl = String.format("http://localhost:%s", mockBackEnd.getPort()); - Configuration configuration = - Configuration.builder().setOAuthUrl(String.format("%s/auth", serverUrl)).build(); - + UnifiedCredentials credentials = UnifiedCredentials.builder().build(); + ServerConfiguration server = new ServerConfiguration(String.format("%s/auth", serverUrl)); HttpClientApache httpClient = new HttpClientApache(); - AuthManager basicAuthManager = new BasicAuthManager(configuration); - BearerAuthManager bearerAuthManager = - new BearerAuthManager(configuration, new HttpMapper(), httpClient); + AuthManager basicAuthManager = new BasicAuthManager(credentials); + OAuthManager oAuthManager = new OAuthManager(credentials, server, new HttpMapper(), httpClient); Map authManagers = - Stream.of(basicAuthManager, bearerAuthManager) + Stream.of(basicAuthManager, oAuthManager) .map(e -> new AbstractMap.SimpleEntry<>(e.getSchema(), e)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); @@ -104,7 +102,7 @@ void initialBearerAuthorization() throws InterruptedException { null, null, null, - Collections.singletonList(bearerAuthManager.getSchema()))); + Collections.singletonList(oAuthManager.getSchema()))); RecordedRequest recordedRequest = mockBackEnd.takeRequest(); @@ -147,7 +145,7 @@ void bearerAutoRefresh() throws InterruptedException { null, null, null, - Collections.singletonList(bearerAuthManager.getSchema()))); + Collections.singletonList(oAuthManager.getSchema()))); } catch (ApiException ae) { // noop } diff --git a/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/ActiveNumberServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/ActiveNumberServiceTest.java index fe7a083d..5e2c4736 100644 --- a/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/ActiveNumberServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/ActiveNumberServiceTest.java @@ -1,12 +1,16 @@ package com.sinch.sdk.domains.numbers.adapters; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import com.adelean.inject.resources.junit.jupiter.GivenJsonResource; import com.adelean.inject.resources.junit.jupiter.TestWithResources; import com.sinch.sdk.BaseTest; import com.sinch.sdk.core.exceptions.ApiException; +import com.sinch.sdk.core.http.AuthManager; +import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.core.models.pagination.Page; import com.sinch.sdk.core.models.pagination.TokenPageNavigator; import com.sinch.sdk.domains.numbers.adapters.api.v1.ActiveNumberApi; @@ -19,14 +23,15 @@ import com.sinch.sdk.domains.numbers.models.requests.ActiveNumberUpdateSMSConfigurationRequestParameters; import com.sinch.sdk.domains.numbers.models.requests.ActiveNumberUpdateVoiceConfigurationRequestParameters; import com.sinch.sdk.domains.numbers.models.responses.ActiveNumberListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.NumbersContext; import java.time.Instant; import java.util.Arrays; import java.util.Collections; +import java.util.Map; import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; import org.mockito.Mock; @TestWithResources @@ -41,15 +46,25 @@ class ActiveNumberServiceTest extends BaseTest { @GivenJsonResource("/domains/numbers/v1/active-numbers-get.json") ActiveNumberDto activeGetResponseDto; - @Mock Configuration configuration; + @Mock NumbersContext context; + @Mock HttpClient httpClient; + @Mock Map authManagers; @Mock ActiveNumberApi api; - @InjectMocks ActiveNumberService service; + ActiveNumberService service; + + String uriUUID = "foo"; + + @BeforeEach + public void initMocks() { + service = spy(new ActiveNumberService(uriUUID, context, httpClient, authManagers)); + doReturn(api).when(service).getApi(); + } @Test void list() throws ApiException { when(api.numberServiceListActiveNumbers( - eq(configuration.getProjectId()), + eq(uriUUID), eq("region"), eq(NumberType.MOBILE.value()), eq(null), @@ -99,7 +114,7 @@ void list() throws ApiException { void listWithParameters() throws ApiException { when(api.numberServiceListActiveNumbers( - eq(configuration.getProjectId()), + eq(uriUUID), eq("another region"), eq(NumberType.TOLL_FREE.value()), eq("pattern value"), @@ -184,7 +199,7 @@ void listWithParameters() throws ApiException { @Test void get() throws ApiException { - when(api.numberServiceGetActiveNumber(eq(configuration.getProjectId()), eq("foo phone number"))) + when(api.numberServiceGetActiveNumber(eq(uriUUID), eq("foo phone number"))) .thenReturn(activeGetResponseDto); ActiveNumber expected = @@ -228,7 +243,7 @@ void get() throws ApiException { @Test void release() throws ApiException { - when(api.numberServiceReleaseNumber(eq(configuration.getProjectId()), eq("foo phone number"))) + when(api.numberServiceReleaseNumber(eq(uriUUID), eq("foo phone number"))) .thenReturn(activeGetResponseDto); ActiveNumber expected = @@ -289,7 +304,7 @@ void update() { .build(); when(api.numberServiceUpdateActiveNumber( - eq(configuration.getProjectId()), + eq(uriUUID), eq("foo phone number"), ArgumentMatchers.eq( ActiveNumberUpdateRequestParametersDtoConverter.convert(parameters)))) diff --git a/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/AvailableNumberServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/AvailableNumberServiceTest.java index 15573224..0bc71865 100644 --- a/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/AvailableNumberServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/AvailableNumberServiceTest.java @@ -4,12 +4,16 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import com.adelean.inject.resources.junit.jupiter.GivenJsonResource; import com.adelean.inject.resources.junit.jupiter.TestWithResources; import com.sinch.sdk.BaseTest; import com.sinch.sdk.core.exceptions.ApiException; +import com.sinch.sdk.core.http.AuthManager; +import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.domains.numbers.adapters.api.v1.AvailableNumberApi; import com.sinch.sdk.domains.numbers.models.*; import com.sinch.sdk.domains.numbers.models.dto.v1.ActiveNumberDto; @@ -17,16 +21,17 @@ import com.sinch.sdk.domains.numbers.models.dto.v1.AvailableNumbersResponseDto; import com.sinch.sdk.domains.numbers.models.requests.*; import com.sinch.sdk.domains.numbers.models.responses.AvailableNumberListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.NumbersContext; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.Collection; import java.util.Collections; +import java.util.Map; import java.util.NoSuchElementException; import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; import org.mockito.Mock; @TestWithResources @@ -41,15 +46,25 @@ class AvailableNumberServiceTest extends BaseTest { @GivenJsonResource("/domains/numbers/v1/rent-response.json") ActiveNumberDto rentNumberDto; - @Mock Configuration configuration; + @Mock NumbersContext context; + @Mock HttpClient httpClient; + @Mock Map authManagers; @Mock AvailableNumberApi api; - @InjectMocks AvailableNumberService service; + AvailableNumberService service; + + String uriUUID = "foo"; + + @BeforeEach + public void initMocks() { + service = spy(new AvailableNumberService(uriUUID, context, httpClient, authManagers)); + doReturn(api).when(service).getApi(); + } @Test void list() throws ApiException { when(api.numberServiceListAvailableNumbers( - eq(configuration.getProjectId()), + eq(uriUUID), eq("region"), ArgumentMatchers.eq(NumberType.MOBILE.value()), eq(null), @@ -88,7 +103,7 @@ void list() throws ApiException { void listWithParameters() throws ApiException { when(api.numberServiceListAvailableNumbers( - eq(configuration.getProjectId()), + eq(uriUUID), eq("another region"), ArgumentMatchers.eq(NumberType.TOLL_FREE.value()), eq("pattern value"), @@ -133,8 +148,7 @@ void listWithParameters() throws ApiException { @Test void get() { - when(api.numberServiceGetAvailableNumber(eq(configuration.getProjectId()), eq("foo"))) - .thenReturn(getNumberDto); + when(api.numberServiceGetAvailableNumber(eq(uriUUID), eq("foo"))).thenReturn(getNumberDto); AvailableNumber response = service.checkAvailability("foo"); @@ -156,8 +170,7 @@ void get() { @Test void rent() { - when(api.numberServiceRentNumber(eq(configuration.getProjectId()), eq("foo"), any())) - .thenReturn(rentNumberDto); + when(api.numberServiceRentNumber(eq(uriUUID), eq("foo"), any())).thenReturn(rentNumberDto); ActiveNumber response = service.rent( @@ -221,8 +234,7 @@ void rent() { @Test void rentAny() { - when(api.numberServiceRentAnyNumber(eq(configuration.getProjectId()), any())) - .thenReturn(rentNumberDto); + when(api.numberServiceRentAnyNumber(eq(uriUUID), any())).thenReturn(rentNumberDto); AvailableNumberRentAnyRequestParameters parameters = AvailableNumberRentAnyRequestParameters.builder() diff --git a/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/CallbackConfigurationServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/CallbackConfigurationServiceTest.java index 2caf1c6e..005c5489 100644 --- a/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/CallbackConfigurationServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/CallbackConfigurationServiceTest.java @@ -1,21 +1,26 @@ package com.sinch.sdk.domains.numbers.adapters; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import com.adelean.inject.resources.junit.jupiter.GivenJsonResource; import com.adelean.inject.resources.junit.jupiter.TestWithResources; import com.sinch.sdk.BaseTest; import com.sinch.sdk.core.exceptions.ApiException; +import com.sinch.sdk.core.http.AuthManager; +import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.domains.numbers.adapters.api.v1.CallbacksApi; import com.sinch.sdk.domains.numbers.models.CallbackConfiguration; import com.sinch.sdk.domains.numbers.models.dto.v1.CallbackConfigurationDto; import com.sinch.sdk.domains.numbers.models.dto.v1.CallbackConfigurationUpdateDto; import com.sinch.sdk.domains.numbers.models.requests.CallbackConfigurationUpdateRequestParameters; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.NumbersContext; +import java.util.Map; import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; import org.mockito.Mock; @TestWithResources @@ -24,15 +29,24 @@ class CallbackConfigurationServiceTest extends BaseTest { @GivenJsonResource("/domains/numbers/v1/callback-configuration.json") CallbackConfigurationDto callbackConfigurationDto; - @Mock Configuration configuration; + @Mock NumbersContext context; + @Mock HttpClient httpClient; + @Mock Map authManagers; @Mock CallbacksApi api; - @InjectMocks CallbackConfigurationService service; + CallbackConfigurationService service; + + String uriUUID = "foo"; + + @BeforeEach + public void initMocks() { + service = spy(new CallbackConfigurationService(uriUUID, context, httpClient, authManagers)); + doReturn(api).when(service).getApi(); + } @Test void get() throws ApiException { - when(api.getCallbackConfiguration(eq(configuration.getProjectId()))) - .thenReturn(callbackConfigurationDto); + when(api.getCallbackConfiguration(eq(uriUUID))).thenReturn(callbackConfigurationDto); CallbackConfiguration response = service.get(); @@ -53,7 +67,7 @@ void update() throws ApiException { CallbackConfigurationUpdateRequestParameters parameters = CallbackConfigurationUpdateRequestParameters.builder().setHMACSecret("hmac value").build(); - when(api.updateCallbackConfiguration(eq(configuration.getProjectId()), eq(dtoParameters))) + when(api.updateCallbackConfiguration(eq(uriUUID), eq(dtoParameters))) .thenReturn(callbackConfigurationDto); CallbackConfiguration response = service.update(parameters); diff --git a/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/NumbersServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/NumbersServiceTest.java index e8c2ea0b..a66cfdb9 100644 --- a/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/NumbersServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/NumbersServiceTest.java @@ -4,7 +4,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.sinch.sdk.core.http.HttpClient; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.NumbersContext; +import com.sinch.sdk.models.UnifiedCredentials; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -12,33 +13,69 @@ class NumbersServiceTest { @Mock HttpClient httpClient; + NumbersContext context = NumbersContext.builder().setNumbersUrl("foo url").build(); + @Test void doNotAcceptNullKey() { - Configuration configuration = - Configuration.builder().setKeyId(null).setKeySecret("foo").setProjectId("foo").build(); + UnifiedCredentials credentials = + UnifiedCredentials.builder().setKeyId(null).setKeySecret("foo").setProjectId("foo").build(); Exception exception = assertThrows( - IllegalArgumentException.class, () -> new NumbersService(configuration, httpClient)); + IllegalArgumentException.class, + () -> new NumbersService(credentials, context, httpClient)); assertTrue(exception.getMessage().contains("keyId")); } @Test void doNotAcceptNullKeySecret() { - Configuration configuration = - Configuration.builder().setKeyId("foo").setKeySecret(null).setProjectId("foo").build(); + UnifiedCredentials credentials = + UnifiedCredentials.builder().setKeyId("foo").setKeySecret(null).setProjectId("foo").build(); Exception exception = assertThrows( - IllegalArgumentException.class, () -> new NumbersService(configuration, httpClient)); + IllegalArgumentException.class, + () -> new NumbersService(credentials, context, httpClient)); assertTrue(exception.getMessage().contains("keySecret")); } @Test void doNotAcceptNullProject() { - Configuration configuration = - Configuration.builder().setKeyId("foo").setKeySecret("foo").setProjectId(null).build(); + UnifiedCredentials credentials = + UnifiedCredentials.builder().setKeyId("foo").setKeySecret("foo").setProjectId(null).build(); Exception exception = assertThrows( - IllegalArgumentException.class, () -> new NumbersService(configuration, httpClient)); + IllegalArgumentException.class, + () -> new NumbersService(credentials, context, httpClient)); assertTrue(exception.getMessage().contains("projectId")); } + + @Test + void doNotAcceptNullContext() { + UnifiedCredentials credentials = + UnifiedCredentials.builder() + .setKeyId("foo") + .setKeySecret("foo") + .setProjectId("foo") + .build(); + Exception exception = + assertThrows( + NullPointerException.class, () -> new NumbersService(credentials, null, httpClient)); + assertTrue(exception.getMessage().contains("Context must be defined")); + } + + @Test + void doNotAcceptNullNumbersUrl() { + UnifiedCredentials credentials = + UnifiedCredentials.builder() + .setKeyId("foo") + .setKeySecret("foo") + .setProjectId("foo") + .build(); + NumbersContext context = NumbersContext.builder().build(); + + Exception exception = + assertThrows( + IllegalArgumentException.class, + () -> new NumbersService(credentials, context, httpClient)); + assertTrue(exception.getMessage().contains("numbersUrl")); + } } diff --git a/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/RegionServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/RegionServiceTest.java index dcc92687..367ed661 100644 --- a/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/RegionServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/numbers/adapters/RegionServiceTest.java @@ -1,24 +1,29 @@ package com.sinch.sdk.domains.numbers.adapters; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import com.adelean.inject.resources.junit.jupiter.GivenJsonResource; import com.adelean.inject.resources.junit.jupiter.TestWithResources; import com.sinch.sdk.BaseTest; import com.sinch.sdk.core.exceptions.ApiException; +import com.sinch.sdk.core.http.AuthManager; +import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.domains.numbers.adapters.api.v1.AvailableRegionsApi; import com.sinch.sdk.domains.numbers.models.NumberType; import com.sinch.sdk.domains.numbers.models.Region; import com.sinch.sdk.domains.numbers.models.dto.v1.ListAvailableRegionsResponseDto; import com.sinch.sdk.domains.numbers.models.requests.AvailableRegionListAllRequestParameters; import com.sinch.sdk.domains.numbers.models.responses.AvailableRegionListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.NumbersContext; import java.util.Collection; import java.util.Collections; +import java.util.Map; import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; import org.mockito.Mock; @TestWithResources @@ -27,15 +32,26 @@ class RegionServiceTest extends BaseTest { @GivenJsonResource("/domains/numbers/v1/available-regions-list.json") ListAvailableRegionsResponseDto availableRegionsListDto; - @Mock Configuration configuration; @Mock AvailableRegionsApi api; - @InjectMocks AvailableRegionService service; + @Mock NumbersContext context; + @Mock HttpClient httpClient; + @Mock Map authManagers; + + AvailableRegionService service; + + String uriUUID = "foo"; + + @BeforeEach + public void initMocks() { + service = spy(new AvailableRegionService(uriUUID, context, httpClient, authManagers)); + doReturn(api).when(service).getApi(); + } @Test void list() throws ApiException { when(api.numberServiceListAvailableRegions( - eq(configuration.getProjectId()), eq(Collections.singletonList("MOBILE")))) + eq(uriUUID), eq(Collections.singletonList("MOBILE")))) .thenReturn(availableRegionsListDto); AvailableRegionListResponse response = diff --git a/client/src/test/java/com/sinch/sdk/domains/sms/adapters/BatchesServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/sms/adapters/BatchesServiceTest.java index a6c6dbc0..2018a507 100644 --- a/client/src/test/java/com/sinch/sdk/domains/sms/adapters/BatchesServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/sms/adapters/BatchesServiceTest.java @@ -1,6 +1,8 @@ package com.sinch.sdk.domains.sms.adapters; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -8,6 +10,8 @@ import com.adelean.inject.resources.junit.jupiter.TestWithResources; import com.sinch.sdk.BaseTest; import com.sinch.sdk.core.exceptions.ApiException; +import com.sinch.sdk.core.http.AuthManager; +import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.core.utils.Pair; import com.sinch.sdk.domains.sms.adapters.api.v1.BatchesApi; import com.sinch.sdk.domains.sms.adapters.converters.BatchDtoConverter; @@ -33,18 +37,19 @@ import com.sinch.sdk.domains.sms.models.requests.UpdateSmsBatchMediaRequest; import com.sinch.sdk.domains.sms.models.requests.UpdateSmsBatchTextRequest; import com.sinch.sdk.domains.sms.models.responses.BatchesListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.SmsContext; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; +import java.util.Map; import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; -import org.mockito.InjectMocks; import org.mockito.Mock; @TestWithResources @@ -263,16 +268,25 @@ public class BatchesServiceTest extends BaseTest { @GivenJsonResource("/domains/sms/v1/ListBatchesResponseDtoPage2.json") ApiBatchListDto listBatchesResponseDtoPage2; - @Mock Configuration configuration; + @Mock SmsContext context; + @Mock HttpClient httpClient; + @Mock Map authManagers; @Mock BatchesApi api; - @InjectMocks BatchesService service; + BatchesService service; + String uriPartID = "foovalue"; @Captor ArgumentCaptor recipientsCaptor; + @BeforeEach + public void initMocks() { + service = spy(new BatchesService(uriPartID, context, httpClient, authManagers)); + doReturn(api).when(service).getApi(); + } + @Test void getBinary() throws ApiException { - when(api.getBatchMessage(eq(configuration.getProjectId()), eq("foo binary batch id"))) + when(api.getBatchMessage(eq(uriPartID), eq("foo binary batch id"))) .thenReturn(binaryResponseDto); Batch response = service.get("foo binary batch id"); @@ -283,8 +297,7 @@ void getBinary() throws ApiException { @Test void getMedia() throws ApiException { - when(api.getBatchMessage(eq(configuration.getProjectId()), eq("foo media batch id"))) - .thenReturn(mediaResponseDto); + when(api.getBatchMessage(eq(uriPartID), eq("foo media batch id"))).thenReturn(mediaResponseDto); Batch response = service.get("foo media batch id"); @@ -294,8 +307,7 @@ void getMedia() throws ApiException { @Test void getText() throws ApiException { - when(api.getBatchMessage(eq(configuration.getProjectId()), eq("foo text batch id"))) - .thenReturn(textResponseDto); + when(api.getBatchMessage(eq(uriPartID), eq("foo text batch id"))).thenReturn(textResponseDto); Batch response = service.get("foo text batch id"); @@ -305,9 +317,7 @@ void getText() throws ApiException { @Test void sendBinary() throws ApiException { - when(api.sendSMS( - eq(configuration.getProjectId()), - eq(BatchDtoConverter.convert(sendSmsBatchBinaryRequest)))) + when(api.sendSMS(eq(uriPartID), eq(BatchDtoConverter.convert(sendSmsBatchBinaryRequest)))) .thenReturn(binaryResponseDto); Batch response = service.send(sendSmsBatchBinaryRequest); @@ -318,9 +328,7 @@ void sendBinary() throws ApiException { @Test void sendMedia() throws ApiException { - when(api.sendSMS( - eq(configuration.getProjectId()), - eq(BatchDtoConverter.convert(sendSmsBatchMediaRequest)))) + when(api.sendSMS(eq(uriPartID), eq(BatchDtoConverter.convert(sendSmsBatchMediaRequest)))) .thenReturn(mediaResponseDto); Batch response = service.send(sendSmsBatchMediaRequest); @@ -331,9 +339,7 @@ void sendMedia() throws ApiException { @Test void sendText() throws ApiException { - when(api.sendSMS( - eq(configuration.getProjectId()), - eq(BatchDtoConverter.convert(sendSmsBatchTextRequest)))) + when(api.sendSMS(eq(uriPartID), eq(BatchDtoConverter.convert(sendSmsBatchTextRequest)))) .thenReturn(textResponseDto); Batch response = service.send(sendSmsBatchTextRequest); @@ -345,7 +351,7 @@ void sendText() throws ApiException { void dryRun() throws ApiException { when(api.dryRun( - eq(configuration.getProjectId()), + eq(uriPartID), eq(true), eq(456), eq(BatchDtoConverter.convert(sendSmsBatchTextRequest)))) @@ -361,32 +367,11 @@ void dryRun() throws ApiException { @Test void list() throws ApiException { - when(api.listBatches( - eq(configuration.getProjectId()), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null))) + when(api.listBatches(eq(uriPartID), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null))) .thenReturn(listBatchesResponseDtoPage0); - when(api.listBatches( - eq(configuration.getProjectId()), - eq(1), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null))) + when(api.listBatches(eq(uriPartID), eq(1), eq(null), eq(null), eq(null), eq(null), eq(null))) .thenReturn(listBatchesResponseDtoPage1); - when(api.listBatches( - eq(configuration.getProjectId()), - eq(2), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null))) + when(api.listBatches(eq(uriPartID), eq(2), eq(null), eq(null), eq(null), eq(null), eq(null))) .thenReturn(listBatchesResponseDtoPage2); BatchesListResponse response = service.list(null); @@ -451,7 +436,7 @@ void list() throws ApiException { void updateText() throws ApiException { when(api.updateBatchMessage( - eq(configuration.getProjectId()), + eq(uriPartID), eq("foo text batch id"), eq(BatchDtoConverter.convert(updateSmsBatchTextRequest)))) .thenReturn(textResponseDto); @@ -465,7 +450,7 @@ void updateText() throws ApiException { void updateMedia() throws ApiException { when(api.updateBatchMessage( - eq(configuration.getProjectId()), + eq(uriPartID), eq("foo text batch id"), eq(BatchDtoConverter.convert(updateSmsBatchMediaRequest)))) .thenReturn(mediaResponseDto); @@ -479,7 +464,7 @@ void updateMedia() throws ApiException { void updateBinary() throws ApiException { when(api.updateBatchMessage( - eq(configuration.getProjectId()), + eq(uriPartID), eq("foo text batch id"), eq(BatchDtoConverter.convert(updateSmsBatchBinaryRequest)))) .thenReturn(binaryResponseDto); @@ -493,7 +478,7 @@ void updateBinary() throws ApiException { void replaceBinary() throws ApiException { when(api.replaceBatch( - eq(configuration.getProjectId()), + eq(uriPartID), eq("foo text batch id"), eq(BatchDtoConverter.convert(sendSmsBatchBinaryRequest)))) .thenReturn(binaryResponseDto); @@ -507,7 +492,7 @@ void replaceBinary() throws ApiException { void replaceMedia() throws ApiException { when(api.replaceBatch( - eq(configuration.getProjectId()), + eq(uriPartID), eq("foo text batch id"), eq(BatchDtoConverter.convert(sendSmsBatchMediaRequest)))) .thenReturn(mediaResponseDto); @@ -521,7 +506,7 @@ void replaceMedia() throws ApiException { void replaceText() throws ApiException { when(api.replaceBatch( - eq(configuration.getProjectId()), + eq(uriPartID), eq("foo text batch id"), eq(BatchDtoConverter.convert(sendSmsBatchTextRequest)))) .thenReturn(textResponseDto); @@ -534,7 +519,7 @@ void replaceText() throws ApiException { @Test void cancelBatch() throws ApiException { - when(api.cancelBatchMessage(eq(configuration.getProjectId()), eq("foo text batch id"))) + when(api.cancelBatchMessage(eq(uriPartID), eq("foo text batch id"))) .thenReturn(textResponseDto); Batch response = service.cancel("foo text batch id"); @@ -549,8 +534,7 @@ void sendDeliveryFeedback() throws ApiException { service.sendDeliveryFeedback("foo text batch id", recipients); verify(api) - .deliveryFeedback( - eq(configuration.getProjectId()), eq("foo text batch id"), recipientsCaptor.capture()); + .deliveryFeedback(eq(uriPartID), eq("foo text batch id"), recipientsCaptor.capture()); ApiDeliveryFeedbackDto dto = recipientsCaptor.getValue(); Assertions.assertThat(dto.getRecipients()).usingRecursiveComparison().isEqualTo(recipients); diff --git a/client/src/test/java/com/sinch/sdk/domains/sms/adapters/DeliveryReportsServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/sms/adapters/DeliveryReportsServiceTest.java index abba01af..dde86378 100644 --- a/client/src/test/java/com/sinch/sdk/domains/sms/adapters/DeliveryReportsServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/sms/adapters/DeliveryReportsServiceTest.java @@ -2,12 +2,16 @@ import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import com.adelean.inject.resources.junit.jupiter.GivenJsonResource; import com.adelean.inject.resources.junit.jupiter.TestWithResources; import com.sinch.sdk.BaseTest; import com.sinch.sdk.core.exceptions.ApiException; +import com.sinch.sdk.core.http.AuthManager; +import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.domains.sms.adapters.api.v1.DeliveryReportsApi; import com.sinch.sdk.domains.sms.adapters.converters.DeliveryReportDtoConverter; import com.sinch.sdk.domains.sms.models.DeliveryReportBatch; @@ -25,21 +29,26 @@ import com.sinch.sdk.domains.sms.models.dto.v1.RecipientDeliveryReportDto; import com.sinch.sdk.domains.sms.models.requests.DeliveryReportBatchGetRequestParameters; import com.sinch.sdk.domains.sms.models.responses.DeliveryReportsListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.SmsContext; import java.time.Instant; import java.util.Arrays; import java.util.Iterator; +import java.util.Map; import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; import org.mockito.Mock; @TestWithResources class DeliveryReportsServiceTest extends BaseTest { - @Mock Configuration configuration; + @Mock SmsContext context; + @Mock HttpClient httpClient; + @Mock Map authManagers; + @Mock DeliveryReportsApi api; - @InjectMocks DeliveryReportsService service; + DeliveryReportsService service; + String uriPartID = "foovalue"; @GivenJsonResource("/domains/sms/v1/DeliveryReportBatchSMSDto.json") DeliveryReportDto deliveryReportBatchSMSDto; @@ -62,11 +71,17 @@ class DeliveryReportsServiceTest extends BaseTest { @GivenJsonResource("/domains/sms/v1/ListDeliveryReportResponseDtoPage2.json") DeliveryReportListDto listDeliveryReportResponseDtoPage2; + @BeforeEach + public void initMocks() { + service = spy(new DeliveryReportsService(uriPartID, context, httpClient, authManagers)); + doReturn(api).when(service).getApi(); + } + @Test void getDeliveryReportBatchSMS() throws ApiException { when(api.getDeliveryReportByBatchId( - eq(configuration.getProjectId()), + eq(uriPartID), eq("foo binary batch id"), eq("foo type"), eq("foo status1,Cancelled"), @@ -94,7 +109,7 @@ void getDeliveryReportBatchSMS() throws ApiException { void getDeliveryReportBatchMMS() throws ApiException { when(api.getDeliveryReportByBatchId( - eq(configuration.getProjectId()), + eq(uriPartID), eq("foo binary batch id"), eq("foo type"), eq("foo status1,Cancelled"), @@ -122,7 +137,7 @@ void getDeliveryReportBatchMMS() throws ApiException { void getDeliveryReportRecipientSMS() throws ApiException { when(api.getDeliveryReportByPhoneNumber( - eq(configuration.getProjectId()), eq("foo binary batch id"), eq("foo number"))) + eq(uriPartID), eq("foo binary batch id"), eq("foo number"))) .thenReturn(deliveryReportRecipientSMSDto); DeliveryReportRecipient response = service.getForNumber("foo binary batch id", "foo number"); @@ -137,7 +152,7 @@ void getDeliveryReportRecipientSMS() throws ApiException { void getDeliveryReportRecipientMMS() throws ApiException { when(api.getDeliveryReportByPhoneNumber( - eq(configuration.getProjectId()), eq("foo binary batch id"), eq("foo number"))) + eq(uriPartID), eq("foo binary batch id"), eq("foo number"))) .thenReturn(deliveryReportRecipientMMSDto); DeliveryReportRecipient response = service.getForNumber("foo binary batch id", "foo number"); @@ -152,34 +167,13 @@ void getDeliveryReportRecipientMMS() throws ApiException { void list() throws ApiException { when(api.getDeliveryReports( - eq(configuration.getProjectId()), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null))) + eq(uriPartID), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null))) .thenReturn(listDeliveryReportResponseDtoPage0); when(api.getDeliveryReports( - eq(configuration.getProjectId()), - eq(1), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null))) + eq(uriPartID), eq(1), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null))) .thenReturn(listDeliveryReportResponseDtoPage1); when(api.getDeliveryReports( - eq(configuration.getProjectId()), - eq(2), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null))) + eq(uriPartID), eq(2), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null))) .thenReturn(listDeliveryReportResponseDtoPage2); DeliveryReportsListResponse response = service.list(null); diff --git a/client/src/test/java/com/sinch/sdk/domains/sms/adapters/GroupsServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/sms/adapters/GroupsServiceTest.java index 8e223880..9bc1bfe9 100644 --- a/client/src/test/java/com/sinch/sdk/domains/sms/adapters/GroupsServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/sms/adapters/GroupsServiceTest.java @@ -1,6 +1,8 @@ package com.sinch.sdk.domains.sms.adapters; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -8,6 +10,8 @@ import com.adelean.inject.resources.junit.jupiter.TestWithResources; import com.sinch.sdk.BaseTest; import com.sinch.sdk.core.exceptions.ApiException; +import com.sinch.sdk.core.http.AuthManager; +import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.domains.sms.adapters.api.v1.GroupsApi; import com.sinch.sdk.domains.sms.adapters.converters.GroupsDtoConverter; import com.sinch.sdk.domains.sms.models.Group; @@ -21,25 +25,29 @@ import com.sinch.sdk.domains.sms.models.requests.GroupReplaceRequestParameters; import com.sinch.sdk.domains.sms.models.requests.GroupUpdateRequestParameters; import com.sinch.sdk.domains.sms.models.responses.GroupsListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.SmsContext; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; +import java.util.Map; import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; -import org.mockito.InjectMocks; import org.mockito.Mock; @TestWithResources class GroupsServiceTest extends BaseTest { - @Mock Configuration configuration; + @Mock SmsContext context; + @Mock HttpClient httpClient; + @Mock Map authManagers; @Mock GroupsApi api; - @InjectMocks GroupsService service; + GroupsService service; + String uriPartID = "foovalue"; @Captor ArgumentCaptor groupIdCaptor; @@ -55,11 +63,16 @@ class GroupsServiceTest extends BaseTest { @GivenJsonResource("/domains/sms/v1/GroupsListResponseDtoPage2.json") ApiGroupListDto groupsListResponseDtoPage2; + @BeforeEach + public void initMocks() { + service = spy(new GroupsService(uriPartID, context, httpClient, authManagers)); + doReturn(api).when(service).getApi(); + } + @Test void get() throws ApiException { - when(api.retrieveGroup(eq(configuration.getProjectId()), eq("foo group ID"))) - .thenReturn(createGroupResponseDto); + when(api.retrieveGroup(eq(uriPartID), eq("foo group ID"))).thenReturn(createGroupResponseDto); Group response = service.get("foo group ID"); @@ -71,7 +84,7 @@ void get() throws ApiException { @Test void create() throws ApiException { - when(api.createGroup(eq(configuration.getProjectId()), eq(new GroupObjectDto()))) + when(api.createGroup(eq(uriPartID), eq(new GroupObjectDto()))) .thenReturn(createGroupResponseDto); Group response = service.create(null); @@ -84,12 +97,9 @@ void create() throws ApiException { @Test void list() throws ApiException { - when(api.listGroups(eq(configuration.getProjectId()), eq(null), eq(null))) - .thenReturn(groupsListResponseDtoPage0); - when(api.listGroups(eq(configuration.getProjectId()), eq(1), eq(null))) - .thenReturn(groupsListResponseDtoPage1); - when(api.listGroups(eq(configuration.getProjectId()), eq(2), eq(null))) - .thenReturn(groupsListResponseDtoPage2); + when(api.listGroups(eq(uriPartID), eq(null), eq(null))).thenReturn(groupsListResponseDtoPage0); + when(api.listGroups(eq(uriPartID), eq(1), eq(null))).thenReturn(groupsListResponseDtoPage1); + when(api.listGroups(eq(uriPartID), eq(2), eq(null))).thenReturn(groupsListResponseDtoPage2); GroupsListResponse response = service.list(null); @@ -162,7 +172,7 @@ void list() throws ApiException { void replace() throws ApiException { when(api.replaceGroup( - eq(configuration.getProjectId()), + eq(uriPartID), eq("group id"), eq( new ReplaceGroupRequestDto() @@ -187,9 +197,7 @@ void replace() throws ApiException { void update() throws ApiException { when(api.updateGroup( - eq(configuration.getProjectId()), - eq("group id"), - eq(new UpdateGroupRequestDto().name("foo name")))) + eq(uriPartID), eq("group id"), eq(new UpdateGroupRequestDto().name("foo name")))) .thenReturn(createGroupResponseDto); Group response = @@ -206,7 +214,7 @@ void delete() throws ApiException { service.delete("foo group id"); - verify(api).deleteGroup(eq(configuration.getProjectId()), groupIdCaptor.capture()); + verify(api).deleteGroup(eq(uriPartID), groupIdCaptor.capture()); String parameter = groupIdCaptor.getValue(); Assertions.assertThat(parameter).isEqualTo("foo group id"); @@ -215,7 +223,7 @@ void delete() throws ApiException { @Test void listMembers() throws ApiException { - when(api.getMembers(eq(configuration.getProjectId()), eq("group id"))) + when(api.getMembers(eq(uriPartID), eq("group id"))) .thenReturn(Arrays.asList("entry 1", "entry 2")); Collection response = service.listMembers("group id"); diff --git a/client/src/test/java/com/sinch/sdk/domains/sms/adapters/InboundsServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/sms/adapters/InboundsServiceTest.java index 1e07cc83..f75637c6 100644 --- a/client/src/test/java/com/sinch/sdk/domains/sms/adapters/InboundsServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/sms/adapters/InboundsServiceTest.java @@ -2,12 +2,16 @@ import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import com.adelean.inject.resources.junit.jupiter.GivenJsonResource; import com.adelean.inject.resources.junit.jupiter.TestWithResources; import com.sinch.sdk.BaseTest; import com.sinch.sdk.core.exceptions.ApiException; +import com.sinch.sdk.core.http.AuthManager; +import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.domains.sms.adapters.api.v1.InboundsApi; import com.sinch.sdk.domains.sms.adapters.converters.InboundsDtoConverter; import com.sinch.sdk.domains.sms.models.Inbound; @@ -16,20 +20,25 @@ import com.sinch.sdk.domains.sms.models.dto.v1.ApiInboundListDto; import com.sinch.sdk.domains.sms.models.dto.v1.InboundDto; import com.sinch.sdk.domains.sms.models.responses.InboundsListResponse; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.SmsContext; import java.time.Instant; import java.util.Iterator; +import java.util.Map; import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; import org.mockito.Mock; @TestWithResources class InboundsServiceTest extends BaseTest { - @Mock Configuration configuration; + @Mock SmsContext context; + @Mock HttpClient httpClient; + @Mock Map authManagers; @Mock InboundsApi api; - @InjectMocks InboundsService service; + InboundsService service; + + String uriPartID = "foovalue"; @GivenJsonResource("/domains/sms/v1/MOBinaryDto.json") InboundDto binary; @@ -46,11 +55,16 @@ class InboundsServiceTest extends BaseTest { @GivenJsonResource("/domains/sms/v1/InboundsListResponseDtoPage2.json") ApiInboundListDto inboundsLisResponseDtoPage2; + @BeforeEach + public void initMocks() { + service = spy(new InboundsService(uriPartID, context, httpClient, authManagers)); + doReturn(api).when(service).getApi(); + } + @Test void getBinary() throws ApiException { - when(api.retrieveInboundMessage(eq(configuration.getProjectId()), eq("foo inbound ID"))) - .thenReturn(binary); + when(api.retrieveInboundMessage(eq(uriPartID), eq("foo inbound ID"))).thenReturn(binary); Inbound response = service.get("foo inbound ID"); @@ -63,8 +77,7 @@ void getBinary() throws ApiException { @Test void getText() throws ApiException { - when(api.retrieveInboundMessage(eq(configuration.getProjectId()), eq("foo inbound ID"))) - .thenReturn(text); + when(api.retrieveInboundMessage(eq(uriPartID), eq("foo inbound ID"))).thenReturn(text); Inbound response = service.get("foo inbound ID"); @@ -78,31 +91,13 @@ void getText() throws ApiException { void list() throws ApiException { when(api.listInboundMessages( - eq(configuration.getProjectId()), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null))) + eq(uriPartID), eq(null), eq(null), eq(null), eq(null), eq(null), eq(null))) .thenReturn(inboundsLisResponseDtoPage0); when(api.listInboundMessages( - eq(configuration.getProjectId()), - eq(1), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null))) + eq(uriPartID), eq(1), eq(null), eq(null), eq(null), eq(null), eq(null))) .thenReturn(inboundsLisResponseDtoPage1); when(api.listInboundMessages( - eq(configuration.getProjectId()), - eq(2), - eq(null), - eq(null), - eq(null), - eq(null), - eq(null))) + eq(uriPartID), eq(2), eq(null), eq(null), eq(null), eq(null), eq(null))) .thenReturn(inboundsLisResponseDtoPage2); InboundsListResponse response = service.list(null); diff --git a/client/src/test/java/com/sinch/sdk/domains/sms/adapters/SMSServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/sms/adapters/SMSServiceTest.java index 8caa8614..dd07f05f 100644 --- a/client/src/test/java/com/sinch/sdk/domains/sms/adapters/SMSServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/sms/adapters/SMSServiceTest.java @@ -4,7 +4,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.sinch.sdk.core.http.HttpClient; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.core.models.ServerConfiguration; +import com.sinch.sdk.models.SmsContext; +import com.sinch.sdk.models.UnifiedCredentials; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -14,31 +16,68 @@ class SMSServiceTest { @Test void doNotAcceptNullKey() { - Configuration configuration = - Configuration.builder().setKeyId(null).setKeySecret("foo").setProjectId("foo").build(); + UnifiedCredentials credentials = + UnifiedCredentials.builder().setKeyId(null).setKeySecret("foo").setProjectId("foo").build(); + SmsContext context = SmsContext.builder().build(); + ServerConfiguration server = new ServerConfiguration(""); Exception exception = assertThrows( - IllegalArgumentException.class, () -> new SMSService(configuration, httpClient)); + IllegalArgumentException.class, + () -> new SMSService(credentials, context, server, httpClient)); assertTrue(exception.getMessage().contains("keyId")); } @Test void doNotAcceptNullKeySecret() { - Configuration configuration = - Configuration.builder().setKeyId("foo").setKeySecret(null).setProjectId("foo").build(); + UnifiedCredentials credentials = + UnifiedCredentials.builder().setKeyId("foo").setKeySecret(null).setProjectId("foo").build(); + SmsContext context = SmsContext.builder().build(); + ServerConfiguration server = new ServerConfiguration(""); Exception exception = assertThrows( - IllegalArgumentException.class, () -> new SMSService(configuration, httpClient)); + IllegalArgumentException.class, + () -> new SMSService(credentials, context, server, httpClient)); assertTrue(exception.getMessage().contains("keySecret")); } @Test void doNotAcceptNullProject() { - Configuration configuration = - Configuration.builder().setKeyId("foo").setKeySecret("foo").setProjectId(null).build(); + UnifiedCredentials credentials = + UnifiedCredentials.builder().setKeyId("foo").setKeySecret("foo").setProjectId(null).build(); + SmsContext context = SmsContext.builder().build(); + ServerConfiguration server = new ServerConfiguration(""); + Exception exception = assertThrows( - IllegalArgumentException.class, () -> new SMSService(configuration, httpClient)); + IllegalArgumentException.class, + () -> new SMSService(credentials, context, server, httpClient)); assertTrue(exception.getMessage().contains("projectId")); } + + @Test + void doNotAcceptNullCredentials() { + + SmsContext context = SmsContext.builder().build(); + ServerConfiguration server = new ServerConfiguration(""); + Exception exception = + assertThrows( + NullPointerException.class, () -> new SMSService(null, context, server, httpClient)); + assertTrue(exception.getMessage().contains("Credentials must be defined")); + } + + @Test + void doNotAcceptNullContext() { + UnifiedCredentials credentials = + UnifiedCredentials.builder() + .setKeyId("foo") + .setKeySecret("foo") + .setProjectId("foo") + .build(); + ServerConfiguration server = new ServerConfiguration(""); + Exception exception = + assertThrows( + NullPointerException.class, + () -> new SMSService(credentials, null, server, httpClient)); + assertTrue(exception.getMessage().contains("Context must be defined")); + } } diff --git a/client/src/test/java/com/sinch/sdk/domains/verification/adapters/VerificationServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/verification/adapters/VerificationServiceTest.java index 0547370c..ed74140b 100644 --- a/client/src/test/java/com/sinch/sdk/domains/verification/adapters/VerificationServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/verification/adapters/VerificationServiceTest.java @@ -4,7 +4,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.sinch.sdk.core.http.HttpClient; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.ApplicationCredentials; +import com.sinch.sdk.models.VerificationContext; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -12,25 +13,76 @@ class VerificationServiceTest { @Mock HttpClient httpClient; + VerificationContext context = VerificationContext.builder().setVerificationUrl("foo url").build(); + + @Test + void doNotAcceptNullApplicationCredentials() { + + Exception exception = + assertThrows( + NullPointerException.class, () -> new VerificationService(null, context, httpClient)); + + assertTrue(exception.getMessage().contains("Credentials must be defined")); + } + @Test void doNotAcceptNullApplicationKey() { - Configuration configuration = - Configuration.builder().setApplicationKey(null).setApplicationSecret("foo secret").build(); + ApplicationCredentials credentials = + ApplicationCredentials.builder() + .setApplicationKey(null) + .setApplicationSecret("foo secret") + .build(); + Exception exception = assertThrows( IllegalArgumentException.class, - () -> new VerificationService(configuration, httpClient)); + () -> new VerificationService(credentials, context, httpClient)); + assertTrue(exception.getMessage().contains("applicationKey")); } @Test void doNotAcceptNullApplicationSecret() { - Configuration configuration = - Configuration.builder().setApplicationKey("foo key").setApplicationSecret(null).build(); + ApplicationCredentials credentials = + ApplicationCredentials.builder() + .setApplicationKey("foo key") + .setApplicationSecret(null) + .build(); + Exception exception = assertThrows( IllegalArgumentException.class, - () -> new VerificationService(configuration, httpClient)); + () -> new VerificationService(credentials, context, httpClient)); + assertTrue(exception.getMessage().contains("applicationSecret")); } + + @Test + void doNotAcceptNullContext() { + ApplicationCredentials credentials = + ApplicationCredentials.builder() + .setApplicationKey("foo key") + .setApplicationSecret("foo secret") + .build(); + Exception exception = + assertThrows( + NullPointerException.class, + () -> new VerificationService(credentials, null, httpClient)); + assertTrue(exception.getMessage().contains("Context must be defined")); + } + + @Test + void doNotAcceptNullVerificationUrl() { + ApplicationCredentials credentials = + ApplicationCredentials.builder() + .setApplicationKey("foo key") + .setApplicationSecret("foo secret") + .build(); + VerificationContext context = VerificationContext.builder().build(); + Exception exception = + assertThrows( + IllegalArgumentException.class, + () -> new VerificationService(credentials, context, httpClient)); + assertTrue(exception.getMessage().contains("verificationUrl")); + } } diff --git a/client/src/test/java/com/sinch/sdk/domains/verification/adapters/VerificationStatusServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/verification/adapters/VerificationStatusServiceTest.java index cbef084f..d066f62a 100644 --- a/client/src/test/java/com/sinch/sdk/domains/verification/adapters/VerificationStatusServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/verification/adapters/VerificationStatusServiceTest.java @@ -18,7 +18,7 @@ import com.sinch.sdk.domains.verification.models.VerificationReference; import com.sinch.sdk.domains.verification.models.VerificationReport; import com.sinch.sdk.domains.verification.models.dto.v1.VerificationReportDtoTest; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.VerificationContext; import java.util.Map; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -29,7 +29,7 @@ public class VerificationStatusServiceTest extends BaseTest { @Mock QueryVerificationsApi api; - @Mock Configuration configuration; + @Mock VerificationContext context; @Mock HttpClient httpClient; @Mock Map authManagers; @@ -37,7 +37,7 @@ public class VerificationStatusServiceTest extends BaseTest { @BeforeEach public void initMocks() { - service = spy(new VerificationStatusService(configuration, httpClient, authManagers)); + service = spy(new VerificationStatusService(context, httpClient, authManagers)); doReturn(api).when(service).getApi(); } diff --git a/client/src/test/java/com/sinch/sdk/domains/verification/adapters/VerificationsServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/verification/adapters/VerificationsServiceTest.java index a1d33f55..f20f3c77 100644 --- a/client/src/test/java/com/sinch/sdk/domains/verification/adapters/VerificationsServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/verification/adapters/VerificationsServiceTest.java @@ -26,7 +26,7 @@ import com.sinch.sdk.domains.verification.models.response.StartVerificationResponseFlashCall; import com.sinch.sdk.domains.verification.models.response.StartVerificationResponseSMS; import com.sinch.sdk.domains.verification.models.response.StartVerificationResponseSeamless; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.VerificationContext; import java.util.Map; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -58,7 +58,7 @@ public class VerificationsServiceTest extends BaseTest { public VerificationReportRequestResourceDto verificationReportSMSRequestDto; @Mock SendingAndReportingVerificationsApi api; - @Mock Configuration configuration; + @Mock VerificationContext context; @Mock HttpClient httpClient; @Mock Map authManagers; @@ -66,7 +66,7 @@ public class VerificationsServiceTest extends BaseTest { @BeforeEach public void initMocks() { - service = spy(new VerificationsService(configuration, httpClient, authManagers)); + service = spy(new VerificationsService(context, httpClient, authManagers)); doReturn(api).when(service).getApi(); } diff --git a/client/src/test/java/com/sinch/sdk/domains/verification/adapters/WebhooksServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/verification/adapters/WebhooksServiceTest.java index 2027bb25..74bfc540 100644 --- a/client/src/test/java/com/sinch/sdk/domains/verification/adapters/WebhooksServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/verification/adapters/WebhooksServiceTest.java @@ -2,10 +2,10 @@ import com.adelean.inject.resources.junit.jupiter.TestWithResources; import com.sinch.sdk.BaseTest; -import com.sinch.sdk.SinchClient; import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.domains.verification.WebHooksService; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.ApplicationCredentials; +import com.sinch.sdk.models.VerificationContext; import java.io.IOException; import java.util.AbstractMap; import java.util.Map; @@ -45,15 +45,12 @@ void checkApplicationAuthentication() throws ApiException { @BeforeEach public void setUp() throws IOException { - Configuration configuration = - Configuration.builder() - .setProjectId("unused") - .setKeyId("unused") - .setKeySecret("unused") + ApplicationCredentials credentials = + ApplicationCredentials.builder() .setApplicationKey("789") .setApplicationSecret("9876543210") .build(); - - webHooksService = new SinchClient(configuration).verification().webhooks(); + VerificationContext context = VerificationContext.builder().setVerificationUrl("foo").build(); + webHooksService = new VerificationService(credentials, context, null).webhooks(); } } diff --git a/client/src/test/java/com/sinch/sdk/domains/voice/adapters/ApplicationsServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/voice/adapters/ApplicationsServiceTest.java index fc1e312d..c167390a 100644 --- a/client/src/test/java/com/sinch/sdk/domains/voice/adapters/ApplicationsServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/voice/adapters/ApplicationsServiceTest.java @@ -21,8 +21,8 @@ import com.sinch.sdk.domains.voice.models.dto.v1.UnassignNumbersDto; import com.sinch.sdk.domains.voice.models.dto.v1.UpdateNumbersDto; import com.sinch.sdk.domains.voice.models.response.AssignedNumbers; -import com.sinch.sdk.models.Configuration; import com.sinch.sdk.models.E164PhoneNumber; +import com.sinch.sdk.models.VoiceContext; import java.util.Map; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -35,7 +35,7 @@ public class ApplicationsServiceTest extends BaseTest { @Mock ApplicationsApi api; - @Mock Configuration configuration; + @Mock VoiceContext context; @Mock HttpClient httpClient; @Mock Map authManagers; @@ -48,7 +48,7 @@ public class ApplicationsServiceTest extends BaseTest { @BeforeEach public void initMocks() { - service = spy(new ApplicationsService(configuration, httpClient, authManagers)); + service = spy(new ApplicationsService(context, httpClient, authManagers)); doReturn(api).when(service).getApi(); } diff --git a/client/src/test/java/com/sinch/sdk/domains/voice/adapters/CalloutsServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/voice/adapters/CalloutsServiceTest.java index c143bf17..00d21c93 100644 --- a/client/src/test/java/com/sinch/sdk/domains/voice/adapters/CalloutsServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/voice/adapters/CalloutsServiceTest.java @@ -16,7 +16,7 @@ import com.sinch.sdk.domains.voice.models.requests.CalloutRequestParametersConferenceTest; import com.sinch.sdk.domains.voice.models.requests.CalloutRequestParametersCustomTest; import com.sinch.sdk.domains.voice.models.requests.CalloutRequestParametersTTSTest; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.VoiceContext; import java.util.Map; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -27,7 +27,7 @@ public class CalloutsServiceTest extends BaseTest { @Mock CalloutsApi api; - @Mock Configuration configuration; + @Mock VoiceContext context; @Mock HttpClient httpClient; @Mock Map authManagers; @@ -35,7 +35,7 @@ public class CalloutsServiceTest extends BaseTest { @BeforeEach public void initMocks() { - service = spy(new CalloutsService(configuration, httpClient, authManagers)); + service = spy(new CalloutsService(context, httpClient, authManagers)); doReturn(api).when(service).getApi(); } diff --git a/client/src/test/java/com/sinch/sdk/domains/voice/adapters/CallsServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/voice/adapters/CallsServiceTest.java index 7913e6d8..0c902fee 100644 --- a/client/src/test/java/com/sinch/sdk/domains/voice/adapters/CallsServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/voice/adapters/CallsServiceTest.java @@ -18,7 +18,7 @@ import com.sinch.sdk.domains.voice.models.dto.v1.SVAMLRequestBodyDto; import com.sinch.sdk.domains.voice.models.response.CallInformation; import com.sinch.sdk.domains.voice.models.svaml.SVAMLControlTest; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.VoiceContext; import java.util.Map; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -31,7 +31,7 @@ public class CallsServiceTest extends BaseTest { @Mock CallsApi api; - @Mock Configuration configuration; + @Mock VoiceContext context; @Mock HttpClient httpClient; @Mock Map authManagers; @@ -42,7 +42,7 @@ public class CallsServiceTest extends BaseTest { @BeforeEach public void initMocks() { - service = spy(new CallsService(configuration, httpClient, authManagers)); + service = spy(new CallsService(context, httpClient, authManagers)); doReturn(api).when(service).getApi(); } diff --git a/client/src/test/java/com/sinch/sdk/domains/voice/adapters/ConferencesServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/voice/adapters/ConferencesServiceTest.java index 75166c7f..3df74417 100644 --- a/client/src/test/java/com/sinch/sdk/domains/voice/adapters/ConferencesServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/voice/adapters/ConferencesServiceTest.java @@ -21,7 +21,7 @@ import com.sinch.sdk.domains.voice.models.requests.CalloutRequestParametersConferenceTest; import com.sinch.sdk.domains.voice.models.requests.ConferenceManageParticipantRequestParametersTest; import com.sinch.sdk.domains.voice.models.response.ConferenceParticipant; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.VoiceContext; import java.util.Collection; import java.util.Map; import org.assertj.core.api.Assertions; @@ -35,7 +35,7 @@ public class ConferencesServiceTest extends BaseTest { @Mock ConferencesApi api; - @Mock Configuration configuration; + @Mock VoiceContext context; @Mock HttpClient httpClient; @Mock Map authManagers; @@ -46,7 +46,7 @@ public class ConferencesServiceTest extends BaseTest { @BeforeEach public void initMocks() { - service = spy(new ConferencesService(configuration, httpClient, authManagers)); + service = spy(new ConferencesService(context, httpClient, authManagers)); doReturn(api).when(service).getApi(); } diff --git a/client/src/test/java/com/sinch/sdk/domains/voice/adapters/VoiceServiceTest.java b/client/src/test/java/com/sinch/sdk/domains/voice/adapters/VoiceServiceTest.java index 4668f2fe..9b565c63 100644 --- a/client/src/test/java/com/sinch/sdk/domains/voice/adapters/VoiceServiceTest.java +++ b/client/src/test/java/com/sinch/sdk/domains/voice/adapters/VoiceServiceTest.java @@ -4,8 +4,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.sinch.sdk.core.http.HttpClient; -import com.sinch.sdk.domains.verification.adapters.VerificationService; -import com.sinch.sdk.models.Configuration; +import com.sinch.sdk.models.ApplicationCredentials; +import com.sinch.sdk.models.VoiceContext; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -13,25 +13,57 @@ class VoiceServiceTest { @Mock HttpClient httpClient; + @Test + void doNotAcceptNullApplicationCredentials() { + VoiceContext context = VoiceContext.builder().build(); + Exception exception = + assertThrows(NullPointerException.class, () -> new VoiceService(null, context, httpClient)); + + assertTrue(exception.getMessage().contains("Credentials must be defined")); + } + + @Test + void doNotAcceptNullContext() { + ApplicationCredentials credentials = ApplicationCredentials.builder().build(); + + Exception exception = + assertThrows( + NullPointerException.class, () -> new VoiceService(credentials, null, httpClient)); + + assertTrue(exception.getMessage().contains("Context must be defined")); + } + @Test void doNotAcceptNullApplicationKey() { - Configuration configuration = - Configuration.builder().setApplicationKey(null).setApplicationSecret("foo secret").build(); + ApplicationCredentials credentials = + ApplicationCredentials.builder() + .setApplicationKey(null) + .setApplicationSecret("foo secret") + .build(); + VoiceContext context = VoiceContext.builder().build(); + Exception exception = assertThrows( IllegalArgumentException.class, - () -> new VerificationService(configuration, httpClient)); + () -> new VoiceService(credentials, context, httpClient)); + assertTrue(exception.getMessage().contains("applicationKey")); } @Test void doNotAcceptNullApplicationSecret() { - Configuration configuration = - Configuration.builder().setApplicationKey("foo key").setApplicationSecret(null).build(); + ApplicationCredentials credentials = + ApplicationCredentials.builder() + .setApplicationKey("foo key") + .setApplicationSecret(null) + .build(); + VoiceContext context = VoiceContext.builder().build(); + Exception exception = assertThrows( IllegalArgumentException.class, - () -> new VerificationService(configuration, httpClient)); + () -> new VoiceService(credentials, context, httpClient)); + assertTrue(exception.getMessage().contains("applicationSecret")); } } diff --git a/client/src/test/java/com/sinch/sdk/models/ApplicationCredentialsTest.java b/client/src/test/java/com/sinch/sdk/models/ApplicationCredentialsTest.java new file mode 100644 index 00000000..48d444f3 --- /dev/null +++ b/client/src/test/java/com/sinch/sdk/models/ApplicationCredentialsTest.java @@ -0,0 +1,37 @@ +package com.sinch.sdk.models; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.junit.jupiter.api.Test; + +class ApplicationCredentialsTest { + static final String APPLICATION_KEY = "fooApplicationKey"; + static final String APPLICATION_SECRET = "fooApplicationSecret"; + + static final ApplicationCredentials credentials = + ApplicationCredentials.builder() + .setApplicationKey(APPLICATION_KEY) + .setApplicationSecret(APPLICATION_SECRET) + .build(); + + @Test + void testToString() { + String value = credentials.toString(); + assertFalse( + value.contains(APPLICATION_KEY), "Config should not contains 'application key' value"); + assertFalse( + value.contains(APPLICATION_SECRET), + "Config should not contains 'application secret' value"); + } + + @Test + void getApplicationKey() { + assertEquals(APPLICATION_KEY, credentials.getApplicationKey()); + } + + @Test + void getApplicationSecret() { + assertEquals(APPLICATION_SECRET, credentials.getApplicationSecret()); + } +} diff --git a/client/src/test/java/com/sinch/sdk/models/ConfigurationBuilderTest.java b/client/src/test/java/com/sinch/sdk/models/ConfigurationBuilderTest.java index 345f6750..12b4cab9 100644 --- a/client/src/test/java/com/sinch/sdk/models/ConfigurationBuilderTest.java +++ b/client/src/test/java/com/sinch/sdk/models/ConfigurationBuilderTest.java @@ -1,7 +1,5 @@ package com.sinch.sdk.models; -import static org.junit.jupiter.api.Assertions.assertEquals; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -16,26 +14,24 @@ class ConfigurationBuilderTest { @Test void build() { - Configuration value = + Configuration builder = new Configuration.Builder() .setKeyId(KEY) .setKeySecret(SECRET) .setProjectId(PROJECT) .setOAuthUrl(OAUTH_URL) - .setNumbersUrl(NUMBERS_SERVER) - .setSmsRegion(SMS_REGION) - .setSmsUrl(SMS_SERVER) + .setNumbersContext(NumbersContext.builder().setNumbersUrl(NUMBERS_SERVER).build()) + .setSmsContext( + SmsContext.builder().setSmsRegion(SMS_REGION).setSmsUrl(SMS_SERVER).build()) .build(); - assertEquals(KEY, value.getKeyId()); - assertEquals(SECRET, value.getKeySecret()); - assertEquals(PROJECT, value.getProjectId()); - Assertions.assertEquals(OAUTH_URL, value.getOAuthServer().getUrl()); - Assertions.assertEquals(NUMBERS_SERVER, value.getNumbersServer().getUrl()); + Assertions.assertEquals(OAUTH_URL, builder.getOAuthServer().getUrl()); + Assertions.assertEquals( + NUMBERS_SERVER, builder.getNumbersContext().get().getNumbersServer().getUrl()); Assertions.assertTrue( - value.getSmsServer().getUrl().contains(SMS_REGION.value()), + builder.getSmsContext().get().getSmsRegion().toString().contains(SMS_REGION.value()), "SMS Region present within SMS server URL"); Assertions.assertTrue( - value.getSmsServer().getUrl().contains("fooSMS_SERVER"), + builder.getSmsContext().get().getSmsServer().getUrl().contains("fooSMS_SERVER"), "SMS server present within SMS server URL"); } } diff --git a/client/src/test/java/com/sinch/sdk/models/ConfigurationTest.java b/client/src/test/java/com/sinch/sdk/models/ConfigurationTest.java deleted file mode 100644 index 94c387aa..00000000 --- a/client/src/test/java/com/sinch/sdk/models/ConfigurationTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.sinch.sdk.models; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.Test; - -class ConfigurationTest { - static final String KEY = "fooKey"; - static final String SECRET = "fooSecret"; - static final String PROJECT = "fooProject"; - static final String APPLICATION_KEY = "fooApplicationKey"; - static final String APPLICATION_SECRET = "fooApplicationSecret"; - - static final String OAUTH_URL = "foo oauth url"; - static final String NUMBERS_SERVER = "fooNUMBERS_SERVER"; - static final SMSRegion SMS_REGION = SMSRegion.AU; - static final String SMS_SERVER = "%sfooSMS_SERVER"; - - static final Configuration configuration = - new Configuration.Builder() - .setKeyId(KEY) - .setKeySecret(SECRET) - .setProjectId(PROJECT) - .setOAuthUrl(OAUTH_URL) - .setNumbersUrl(NUMBERS_SERVER) - .setSmsRegion(SMS_REGION) - .setSmsUrl(SMS_SERVER) - .setApplicationKey(APPLICATION_KEY) - .setApplicationSecret(APPLICATION_SECRET) - .build(); - - @Test - void testToString() { - String value = configuration.toString(); - assertFalse(value.contains(KEY), "Config should not contains 'key' value"); - assertFalse(value.contains(SECRET), "Config should not contains 'secret' value"); - assertFalse(value.contains(PROJECT), "Config should not contains 'project' value"); - assertFalse( - value.contains(APPLICATION_KEY), "Config should not contains 'application key' value"); - assertFalse( - value.contains(APPLICATION_SECRET), - "Config should not contains 'application secret' value"); - } - - @Test - void getKeyId() { - assertEquals(KEY, configuration.getKeyId()); - } - - @Test - void getKeySecret() { - assertEquals(SECRET, configuration.getKeySecret()); - } - - @Test - void getProjectId() { - assertEquals(PROJECT, configuration.getProjectId()); - } - - @Test - void defaultUSForSmSRegion() { - Configuration configuration = - new Configuration.Builder() - .setKeyId(KEY) - .setKeySecret(SECRET) - .setProjectId(PROJECT) - .setOAuthUrl(OAUTH_URL) - .setNumbersUrl(NUMBERS_SERVER) - .setSmsUrl(SMS_SERVER) - .build(); - assertEquals(configuration.getSmsRegion(), SMSRegion.US); - } -} diff --git a/client/src/test/java/com/sinch/sdk/models/SmsContextTest.java b/client/src/test/java/com/sinch/sdk/models/SmsContextTest.java new file mode 100644 index 00000000..fc8d3b91 --- /dev/null +++ b/client/src/test/java/com/sinch/sdk/models/SmsContextTest.java @@ -0,0 +1,16 @@ +package com.sinch.sdk.models; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class SmsContextTest { + + static final String SMS_SERVER = "%sfooSMS_SERVER"; + + @Test + void defaultUSForSmSRegion() { + SmsContext context = SmsContext.builder().setSmsUrl(SMS_SERVER).build(); + assertEquals(context.getSmsRegion(), SMSRegion.US); + } +} diff --git a/client/src/test/java/com/sinch/sdk/models/SmsServicePlanCredentialsTest.java b/client/src/test/java/com/sinch/sdk/models/SmsServicePlanCredentialsTest.java new file mode 100644 index 00000000..dba1d7b3 --- /dev/null +++ b/client/src/test/java/com/sinch/sdk/models/SmsServicePlanCredentialsTest.java @@ -0,0 +1,37 @@ +package com.sinch.sdk.models; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.junit.jupiter.api.Test; + +class SmsServicePlanCredentialsTest { + static final String SERVICE_PLAN_ID = "fooServicePlanId"; + static final String SERVICE_PLAN_TOKEN = "fooServicePlanToken"; + + static final SmsServicePlanCredentials credentials = + SmsServicePlanCredentials.builder() + .setServicePlanId(SERVICE_PLAN_ID) + .setApiToken(SERVICE_PLAN_TOKEN) + .build(); + + @Test + void testToString() { + String value = credentials.toString(); + assertFalse( + value.contains(SERVICE_PLAN_ID), "Config should not contains 'service plan id' value"); + assertFalse( + value.contains(SERVICE_PLAN_TOKEN), + "Config should not contains 'service plan token' value"); + } + + @Test + void getServicePlanId() { + assertEquals(SERVICE_PLAN_ID, credentials.getServicePlanId()); + } + + @Test + void getApiToken() { + assertEquals(SERVICE_PLAN_TOKEN, credentials.getApiToken()); + } +} diff --git a/client/src/test/java/com/sinch/sdk/models/UnifiedCredentialTest.java b/client/src/test/java/com/sinch/sdk/models/UnifiedCredentialTest.java new file mode 100644 index 00000000..b1158ede --- /dev/null +++ b/client/src/test/java/com/sinch/sdk/models/UnifiedCredentialTest.java @@ -0,0 +1,38 @@ +package com.sinch.sdk.models; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.junit.jupiter.api.Test; + +class UnifiedCredentialTest { + static final String KEY = "fooKey"; + static final String SECRET = "fooSecret"; + static final String PROJECT = "fooProject"; + + static final UnifiedCredentials credentials = + UnifiedCredentials.builder().setKeyId(KEY).setKeySecret(SECRET).setProjectId(PROJECT).build(); + + @Test + void testToString() { + String value = credentials.toString(); + assertFalse(value.contains(KEY), "Credentials should not contains 'key' value"); + assertFalse(value.contains(SECRET), "Credentials should not contains 'secret' value"); + assertFalse(value.contains(PROJECT), "Credentials should not contains 'project' value"); + } + + @Test + void getKeyId() { + assertEquals(KEY, credentials.getKeyId()); + } + + @Test + void getKeySecret() { + assertEquals(SECRET, credentials.getKeySecret()); + } + + @Test + void getProjectId() { + assertEquals(PROJECT, credentials.getProjectId()); + } +} diff --git a/sample-app/src/main/java/com/sinch/sample/BaseApplication.java b/sample-app/src/main/java/com/sinch/sample/BaseApplication.java index 86201b99..538c2a2f 100644 --- a/sample-app/src/main/java/com/sinch/sample/BaseApplication.java +++ b/sample-app/src/main/java/com/sinch/sample/BaseApplication.java @@ -1,6 +1,7 @@ package com.sinch.sample; import com.sinch.sdk.SinchClient; +import com.sinch.sdk.models.ApplicationCredentials; import com.sinch.sdk.models.Configuration; import java.io.IOException; import java.util.Properties; @@ -51,7 +52,11 @@ protected BaseApplication() throws IOException { String webhooksUrl = getConfigValue(WEBHOOKS_URL_KEY); webhooksVoicePath = String.format("%s%s", webhooksUrl, getConfigValue(WEBHOOKS_VOICE_PATH_KEY)); - applicationKey = configuration.getApplicationKey(); + applicationKey = + configuration + .getApplicationCredentials() + .map(ApplicationCredentials::getApplicationKey) + .orElse(null); client = new SinchClient(configuration); } diff --git a/sample-app/src/main/java/com/sinch/sample/Utils.java b/sample-app/src/main/java/com/sinch/sample/Utils.java index fc577389..25332124 100644 --- a/sample-app/src/main/java/com/sinch/sample/Utils.java +++ b/sample-app/src/main/java/com/sinch/sample/Utils.java @@ -17,6 +17,10 @@ public class Utils { private static final String APPLICATION_API_KEY = "APPLICATION_API_KEY"; private static final String APPLICATION_API_SECRET = "APPLICATION_API_SECRET"; + // can super sed unified Sinch credentials if SMS service plan ID defined + private static final String SMS_SERVICE_PLAN_ID = "SMS_SERVICE_PLAN_ID"; + private static final String SMS_SERVICE_PLAN_TOKEN = "SMS_SERVICE_PLAN_TOKEN"; + public static Logger initializeLogger(String className) { try (InputStream logConfigInputStream = Utils.class.getClassLoader().getResourceAsStream("logging.properties")) { @@ -49,7 +53,17 @@ public static Properties loadProperties(Logger logger) { public static Configuration loadConfiguration(Logger logger) { Properties properties = loadProperties(logger); + Configuration.Builder builder = Configuration.builder(); + + manageUnifiedCredentials(properties, builder); + manageApplicationCredentials(properties, builder); + manageSmsServicePlanCredentials(properties, builder); + return builder.build(); + } + + private static void manageUnifiedCredentials( + Properties properties, Configuration.Builder builder) { String keyId = null != System.getenv(SINCH_KEY_ID) ? System.getenv(SINCH_KEY_ID) @@ -63,22 +77,53 @@ public static Configuration loadConfiguration(Logger logger) { ? System.getenv(SINCH_PROJECT_ID) : properties.getProperty(SINCH_PROJECT_ID); + if (null != keyId || null != keySecret || null != projectId) { + builder.setKeyId(keyId).setKeySecret(keySecret).setProjectId(projectId); + } + } + + private static void manageApplicationCredentials( + Properties properties, Configuration.Builder builder) { + String verificationApiKey = null != System.getenv(APPLICATION_API_KEY) ? System.getenv(APPLICATION_API_KEY) : properties.getProperty(APPLICATION_API_KEY); + + if (null != verificationApiKey) { + builder.setApplicationKey(verificationApiKey); + } + String verificationApiSecret = null != System.getenv(APPLICATION_API_SECRET) ? System.getenv(APPLICATION_API_SECRET) : properties.getProperty(APPLICATION_API_SECRET); - return Configuration.builder() - .setKeyId(keyId) - .setKeySecret(keySecret) - .setProjectId(projectId) - .setApplicationKey(verificationApiKey) - .setApplicationSecret(verificationApiSecret) - .build(); + if (null != verificationApiSecret) { + builder.setApplicationSecret(verificationApiSecret); + } + } + + private static void manageSmsServicePlanCredentials( + Properties properties, Configuration.Builder builder) { + + String smsServicePlanId = + null != System.getenv(SMS_SERVICE_PLAN_ID) + ? System.getenv(SMS_SERVICE_PLAN_ID) + : properties.getProperty(SMS_SERVICE_PLAN_ID); + + if (null != smsServicePlanId) { + builder.setSmsServicePlanId(smsServicePlanId); + } + + String smsServicePlanToken = + null != System.getenv(SMS_SERVICE_PLAN_TOKEN) + ? System.getenv(SMS_SERVICE_PLAN_TOKEN) + : properties.getProperty(SMS_SERVICE_PLAN_TOKEN); + + if (null != smsServicePlanToken) { + builder.setSmsApiToken(smsServicePlanToken); + } } public static void echoStep(int step, String text) {