diff --git a/core/src/main/java/cloud/stackit/sdk/core/auth/SetupAuth.java b/core/src/main/java/cloud/stackit/sdk/core/auth/SetupAuth.java index c23eaea..bee989c 100644 --- a/core/src/main/java/cloud/stackit/sdk/core/auth/SetupAuth.java +++ b/core/src/main/java/cloud/stackit/sdk/core/auth/SetupAuth.java @@ -39,7 +39,7 @@ public class SetupAuth { * @throws CredentialsInFileNotFoundException when no configuration is set or can be found */ public SetupAuth() throws CredentialsInFileNotFoundException { - this(new CoreConfiguration.Builder().build(), new EnvironmentVariables()); + this(new CoreConfiguration(), new EnvironmentVariables()); } /** @@ -66,7 +66,7 @@ public SetupAuth(CoreConfiguration cfg) throws IOException, CredentialsInFileNot protected SetupAuth(CoreConfiguration cfg, EnvironmentVariables environmentVariables) throws CredentialsInFileNotFoundException { - this.cfg = cfg != null ? cfg : new CoreConfiguration.Builder().build(); + this.cfg = cfg != null ? cfg : new CoreConfiguration(); this.env = environmentVariables != null ? environmentVariables : new EnvironmentVariables(); } diff --git a/core/src/main/java/cloud/stackit/sdk/core/config/CoreConfiguration.java b/core/src/main/java/cloud/stackit/sdk/core/config/CoreConfiguration.java index f100526..caa5ed3 100644 --- a/core/src/main/java/cloud/stackit/sdk/core/config/CoreConfiguration.java +++ b/core/src/main/java/cloud/stackit/sdk/core/config/CoreConfiguration.java @@ -3,27 +3,17 @@ import java.util.Map; public class CoreConfiguration { - private final Map defaultHeader; - private final String serviceAccountKey; - private final String serviceAccountKeyPath; - private final String privateKeyPath; - private final String privateKey; - private final String customEndpoint; - private final String credentialsFilePath; - private final String tokenCustomUrl; - private final Long tokenExpirationLeeway; - - CoreConfiguration(Builder builder) { - this.defaultHeader = builder.defaultHeader; - this.serviceAccountKey = builder.serviceAccountKey; - this.serviceAccountKeyPath = builder.serviceAccountKeyPath; - this.privateKeyPath = builder.privateKeyPath; - this.privateKey = builder.privateKey; - this.customEndpoint = builder.customEndpoint; - this.credentialsFilePath = builder.credentialsFilePath; - this.tokenCustomUrl = builder.tokenCustomUrl; - this.tokenExpirationLeeway = builder.tokenExpirationLeeway; - } + private Map defaultHeader; + private String serviceAccountKey; + private String serviceAccountKeyPath; + private String privateKeyPath; + private String privateKey; + private String customEndpoint; + private String credentialsFilePath; + private String tokenCustomUrl; + private Long tokenExpirationLeeway; + + public CoreConfiguration() {} public Map getDefaultHeader() { return defaultHeader; @@ -61,64 +51,48 @@ public Long getTokenExpirationLeeway() { return tokenExpirationLeeway; } - public static class Builder { - private Map defaultHeader; - private String serviceAccountKey; - private String serviceAccountKeyPath; - private String privateKeyPath; - private String privateKey; - private String customEndpoint; - private String credentialsFilePath; - private String tokenCustomUrl; - private Long tokenExpirationLeeway; - - public Builder defaultHeader(Map defaultHeader) { - this.defaultHeader = defaultHeader; - return this; - } - - public Builder serviceAccountKey(String serviceAccountKey) { - this.serviceAccountKey = serviceAccountKey; - return this; - } - - public Builder serviceAccountKeyPath(String serviceAccountKeyPath) { - this.serviceAccountKeyPath = serviceAccountKeyPath; - return this; - } - - public Builder privateKeyPath(String privateKeyPath) { - this.privateKeyPath = privateKeyPath; - return this; - } - - public Builder privateKey(String privateKey) { - this.privateKey = privateKey; - return this; - } - - public Builder customEndpoint(String customEndpoint) { - this.customEndpoint = customEndpoint; - return this; - } - - public Builder credentialsFilePath(String credentialsFilePath) { - this.credentialsFilePath = credentialsFilePath; - return this; - } - - public Builder tokenCustomUrl(String tokenCustomUrl) { - this.tokenCustomUrl = tokenCustomUrl; - return this; - } - - public Builder tokenExpirationLeeway(Long tokenExpirationLeeway) { - this.tokenExpirationLeeway = tokenExpirationLeeway; - return this; - } - - public CoreConfiguration build() { - return new CoreConfiguration(this); - } + public CoreConfiguration defaultHeader(Map defaultHeader) { + this.defaultHeader = defaultHeader; + return this; + } + + public CoreConfiguration serviceAccountKey(String serviceAccountKey) { + this.serviceAccountKey = serviceAccountKey; + return this; + } + + public CoreConfiguration serviceAccountKeyPath(String serviceAccountKeyPath) { + this.serviceAccountKeyPath = serviceAccountKeyPath; + return this; + } + + public CoreConfiguration privateKeyPath(String privateKeyPath) { + this.privateKeyPath = privateKeyPath; + return this; + } + + public CoreConfiguration privateKey(String privateKey) { + this.privateKey = privateKey; + return this; + } + + public CoreConfiguration customEndpoint(String customEndpoint) { + this.customEndpoint = customEndpoint; + return this; + } + + public CoreConfiguration credentialsFilePath(String credentialsFilePath) { + this.credentialsFilePath = credentialsFilePath; + return this; + } + + public CoreConfiguration tokenCustomUrl(String tokenCustomUrl) { + this.tokenCustomUrl = tokenCustomUrl; + return this; + } + + public CoreConfiguration tokenExpirationLeeway(Long tokenExpirationLeeway) { + this.tokenExpirationLeeway = tokenExpirationLeeway; + return this; } } diff --git a/core/src/test/java/cloud/stackit/sdk/core/KeyFlowAuthenticatorTest.java b/core/src/test/java/cloud/stackit/sdk/core/KeyFlowAuthenticatorTest.java index 0465171..2ca7c24 100644 --- a/core/src/test/java/cloud/stackit/sdk/core/KeyFlowAuthenticatorTest.java +++ b/core/src/test/java/cloud/stackit/sdk/core/KeyFlowAuthenticatorTest.java @@ -116,9 +116,7 @@ void getAccessToken_response200_noException() // Config HttpUrl url = mockWebServer.url("/token"); CoreConfiguration cfg = - new CoreConfiguration.Builder() - .tokenCustomUrl(url.toString()) // Use mockWebServer - .build(); + new CoreConfiguration().tokenCustomUrl(url.toString()); // Use mockWebServer KeyFlowAuthenticator keyFlowAuthenticator = new KeyFlowAuthenticator(cfg, defaultSaKey); @@ -143,9 +141,7 @@ void getAccessToken_expiredToken_noException() // Config HttpUrl url = mockWebServer.url("/token"); CoreConfiguration cfg = - new CoreConfiguration.Builder() - .tokenCustomUrl(url.toString()) // Use mockWebServer - .build(); + new CoreConfiguration().tokenCustomUrl(url.toString()); // Use mockWebServer KeyFlowAuthenticator keyFlowAuthenticator = new KeyFlowAuthenticator(cfg, defaultSaKey); keyFlowAuthenticator.setToken(expiredKey); @@ -162,9 +158,7 @@ void createAccessToken_response200WithEmptyBody_throwsException() { // Config CoreConfiguration cfg = - new CoreConfiguration.Builder() - .tokenCustomUrl(url.toString()) // Use mockWebServer - .build(); + new CoreConfiguration().tokenCustomUrl(url.toString()); // Use mockWebServer // Init keyFlowAuthenticator KeyFlowAuthenticator keyFlowAuthenticator = @@ -182,9 +176,7 @@ void createAccessToken_response400_throwsApiException() { // Config CoreConfiguration cfg = - new CoreConfiguration.Builder() - .tokenCustomUrl(url.toString()) // Use mockWebServer - .build(); + new CoreConfiguration().tokenCustomUrl(url.toString()); // Use mockWebServer // Init keyFlowAuthenticator KeyFlowAuthenticator keyFlowAuthenticator = @@ -206,9 +198,7 @@ void createAccessToken_response200WithValidResponse_noException() // Config HttpUrl url = mockWebServer.url("/token"); CoreConfiguration cfg = - new CoreConfiguration.Builder() - .tokenCustomUrl(url.toString()) // Use mockWebServer - .build(); + new CoreConfiguration().tokenCustomUrl(url.toString()); // Use mockWebServer // Init keyFlowAuthenticator KeyFlowAuthenticator keyFlowAuthenticator = new KeyFlowAuthenticator(cfg, defaultSaKey); @@ -229,9 +219,7 @@ void createAccessTokenWithRefreshToken_response200WithValidResponse_noException( // Config HttpUrl url = mockWebServer.url("/token"); CoreConfiguration cfg = - new CoreConfiguration.Builder() - .tokenCustomUrl(url.toString()) // Use mockWebServer - .build(); + new CoreConfiguration().tokenCustomUrl(url.toString()); // Use mockWebServer // Prepare keyFlowAuthenticator KeyFlowAuthenticator keyFlowAuthenticator = new KeyFlowAuthenticator(cfg, defaultSaKey); @@ -251,9 +239,7 @@ void createAccessTokenWithRefreshToken_response200WithEmptyBody_throwsException( // Config CoreConfiguration cfg = - new CoreConfiguration.Builder() - .tokenCustomUrl(url.toString()) // Use mockWebServer - .build(); + new CoreConfiguration().tokenCustomUrl(url.toString()); // Use mockWebServer // Prepare keyFlowAuthenticator KeyFlowAuthenticator keyFlowAuthenticator = diff --git a/core/src/test/java/cloud/stackit/sdk/core/auth/SetupAuthTest.java b/core/src/test/java/cloud/stackit/sdk/core/auth/SetupAuthTest.java index 6e1d0ec..8946567 100644 --- a/core/src/test/java/cloud/stackit/sdk/core/auth/SetupAuthTest.java +++ b/core/src/test/java/cloud/stackit/sdk/core/auth/SetupAuthTest.java @@ -76,8 +76,7 @@ void getAccessToken_withRunningInit_returnsInterceptor() throws IOException { ServiceAccountKey saKey = createDummyServiceAccount("privateKey"); String initSaKeyJson = new Gson().toJson(saKey); - CoreConfiguration config = - new CoreConfiguration.Builder().serviceAccountKey(initSaKeyJson).build(); + CoreConfiguration config = new CoreConfiguration().serviceAccountKey(initSaKeyJson); SetupAuth setupAuth = new SetupAuth(config); setupAuth.init(); @@ -96,9 +95,8 @@ void setupKeyFlow_readServiceAccountFromPath() // Create config and read setup auth with the previous created saKey CoreConfiguration cfg = - new CoreConfiguration.Builder() - .serviceAccountKeyPath(saKeyPath.toAbsolutePath().toString()) - .build(); + new CoreConfiguration() + .serviceAccountKeyPath(saKeyPath.toAbsolutePath().toString()); ServiceAccountKey parsedSaKey = new SetupAuth().setupKeyFlow(cfg); assertEquals(initSaKey, parsedSaKey); @@ -112,8 +110,7 @@ void setupKeyFlow_readServiceAccountFromConfig() String initSaKeyJson = new Gson().toJson(initSaKey); // Create config and read setup auth with the previous created saKey - CoreConfiguration cfg = - new CoreConfiguration.Builder().serviceAccountKey(initSaKeyJson).build(); + CoreConfiguration cfg = new CoreConfiguration().serviceAccountKey(initSaKeyJson); ServiceAccountKey parsedSaKey = new SetupAuth().setupKeyFlow(cfg); assertEquals(initSaKey, parsedSaKey); @@ -129,7 +126,7 @@ void setupKeyFlow_readServiceAccountFromKeyEnv() throws IOException { when(envs.getStackitServiceAccountKey()).thenReturn(initSaKeyJson); // Create config and read setup auth with the previous created saKey - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); ServiceAccountKey parsedSaKey = new SetupAuth(cfg, envs).setupKeyFlow(cfg); assertEquals(initSaKey, parsedSaKey); @@ -151,7 +148,7 @@ void setupKeyFlow_readServiceAccountFromKeyPathEnv() throws IOException { .thenReturn(keyPathFile.toAbsolutePath().toString()); // Create config and read setup auth with the previous created saKey - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); ServiceAccountKey parsedSaKey = new SetupAuth(cfg, envs).setupKeyFlow(cfg); assertEquals(initSaKey, parsedSaKey); @@ -169,12 +166,11 @@ void setupKeyFlow_readServiceAccountFromPathWithoutPrivateKey_throwsException() // Create config and read setup auth with the previous created saKey CoreConfiguration cfg = - new CoreConfiguration.Builder() + new CoreConfiguration() .serviceAccountKeyPath(saKeyPath.toAbsolutePath().toString()) .credentialsFilePath( // make sure that the defaultCredentialsFile is not // used - invalidCredentialsFilePath) - .build(); + invalidCredentialsFilePath); SetupAuth auth = new SetupAuth(); assertThrows(PrivateKeyNotFoundException.class, () -> auth.setupKeyFlow(cfg)); @@ -189,12 +185,11 @@ void setupKeyFlow_readServiceAccountFromConfigWithoutPrivateKey_throwsException( // Create config and read setup auth with the previous created saKey CoreConfiguration cfg = - new CoreConfiguration.Builder() + new CoreConfiguration() .serviceAccountKey(initSaKeyJson) .credentialsFilePath( // make sure that the defaultCredentialsFile is not // used - invalidCredentialsFilePath) - .build(); + invalidCredentialsFilePath); SetupAuth auth = new SetupAuth(); assertThrows(PrivateKeyNotFoundException.class, () -> auth.setupKeyFlow(cfg)); @@ -207,7 +202,7 @@ void loadPrivateKey_setPrivateKeyFromConfig() ServiceAccountKey saKey = createDummyServiceAccount(null); SetupAuth setupAuth = new SetupAuth(); - CoreConfiguration cfg = new CoreConfiguration.Builder().privateKey(prvKey).build(); + CoreConfiguration cfg = new CoreConfiguration().privateKey(prvKey); assertNull(saKey.getCredentials().getPrivateKey()); assertDoesNotThrow(() -> setupAuth.loadPrivateKey(cfg, saKey)); @@ -223,7 +218,7 @@ void loadPrivateKey_doesNotOverwriteExistingPrivateKey() // Create Service Account ServiceAccountKey saKey = createDummyServiceAccount(initialPrivateKey); SetupAuth setupAuth = new SetupAuth(); - CoreConfiguration cfg = new CoreConfiguration.Builder().privateKey(cfgPrivateKey).build(); + CoreConfiguration cfg = new CoreConfiguration().privateKey(cfgPrivateKey); assertEquals(initialPrivateKey, saKey.getCredentials().getPrivateKey()); assertDoesNotThrow(() -> setupAuth.loadPrivateKey(cfg, saKey)); @@ -243,9 +238,7 @@ void loadPrivateKey_setPrivateKeyPath() ServiceAccountKey saKey = createDummyServiceAccount(null); SetupAuth setupAuth = new SetupAuth(); CoreConfiguration cfg = - new CoreConfiguration.Builder() - .privateKeyPath(tempPrvKeyFile.toAbsolutePath().toString()) - .build(); + new CoreConfiguration().privateKeyPath(tempPrvKeyFile.toAbsolutePath().toString()); assertNull(saKey.getCredentials().getPrivateKey()); assertDoesNotThrow(() -> setupAuth.loadPrivateKey(cfg, saKey)); @@ -280,9 +273,8 @@ void loadPrivateKey_setPrivateKeyPathViaCredentialsFile() ServiceAccountKey saKey = createDummyServiceAccount(null); SetupAuth setupAuth = new SetupAuth(); CoreConfiguration cfg = - new CoreConfiguration.Builder() - .credentialsFilePath(tempCredentialsFile.toAbsolutePath().toString()) - .build(); + new CoreConfiguration() + .credentialsFilePath(tempCredentialsFile.toAbsolutePath().toString()); assertNull(saKey.getCredentials().getPrivateKey()); assertDoesNotThrow(() -> setupAuth.loadPrivateKey(cfg, saKey)); @@ -310,9 +302,8 @@ void loadPrivateKey_setPrivateKeyViaCredentialsFile() SetupAuth setupAuth = new SetupAuth(); CoreConfiguration cfg = - new CoreConfiguration.Builder() - .credentialsFilePath(tempCredentialsFile.toAbsolutePath().toString()) - .build(); + new CoreConfiguration() + .credentialsFilePath(tempCredentialsFile.toAbsolutePath().toString()); assertNull(saKey.getCredentials().getPrivateKey()); assertDoesNotThrow(() -> setupAuth.loadPrivateKey(cfg, saKey)); @@ -325,7 +316,7 @@ void loadPrivateKey_setPrivateKeyViaEnv() throws IOException { ServiceAccountKey saKey = createDummyServiceAccount(null); when(envs.getStackitPrivateKey()).thenReturn(prvKey); - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); SetupAuth setupAuth = new SetupAuth(cfg, envs); assertNull(saKey.getCredentials().getPrivateKey()); @@ -344,7 +335,7 @@ void loadPrivateKey_setPrivateKeyPathViaEnv() throws IOException { when(envs.getStackitPrivateKeyPath()) .thenReturn(tempPrvKeyFile.toAbsolutePath().toString()); - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); SetupAuth setupAuth = new SetupAuth(cfg, envs); assertNull(saKey.getCredentials().getPrivateKey()); @@ -370,7 +361,7 @@ void loadPrivateKey_setPrivateKeyViaCredentialsFileInEnv() // Create dummy service account and config ServiceAccountKey saKey = createDummyServiceAccount(null); - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); SetupAuth setupAuth = new SetupAuth(cfg, envs); when(envs.getStackitCredentialsPath()) .thenReturn(tempCredentialsFile.toAbsolutePath().toString()); @@ -396,7 +387,7 @@ void loadPrivateKey_invalidPrivateKeyPath_throwsException() ServiceAccountKey saKey = createDummyServiceAccount(null); SetupAuth setupAuth = new SetupAuth(); - CoreConfiguration cfg = new CoreConfiguration.Builder().privateKeyPath(invalidPath).build(); + CoreConfiguration cfg = new CoreConfiguration().privateKeyPath(invalidPath); assertNull(saKey.getCredentials().getPrivateKey()); assertThrows(PrivateKeyNotFoundException.class, () -> setupAuth.loadPrivateKey(cfg, saKey)); diff --git a/core/src/test/java/cloud/stackit/sdk/core/config/CoreConfigurationTest.java b/core/src/test/java/cloud/stackit/sdk/core/config/CoreConfigurationTest.java index 4c0e37b..d02897a 100644 --- a/core/src/test/java/cloud/stackit/sdk/core/config/CoreConfigurationTest.java +++ b/core/src/test/java/cloud/stackit/sdk/core/config/CoreConfigurationTest.java @@ -12,7 +12,7 @@ class CoreConfigurationTest { void getDefaultHeader() { HashMap map = new HashMap(); map.put("key", "value"); - CoreConfiguration cfg = new CoreConfiguration.Builder().defaultHeader(map).build(); + CoreConfiguration cfg = new CoreConfiguration().defaultHeader(map); Map cfgHeader = cfg.getDefaultHeader(); assertEquals(map, cfgHeader); @@ -22,7 +22,7 @@ void getDefaultHeader() { void getServiceAccountKey() { final String saKey = ""; - CoreConfiguration cfg = new CoreConfiguration.Builder().serviceAccountKey(saKey).build(); + CoreConfiguration cfg = new CoreConfiguration().serviceAccountKey(saKey); String cfgSaKey = cfg.getServiceAccountKey(); @@ -33,8 +33,7 @@ void getServiceAccountKey() { void getServiceAccountKeyPath() { final String saKeyPath = ""; - CoreConfiguration cfg = - new CoreConfiguration.Builder().serviceAccountKeyPath(saKeyPath).build(); + CoreConfiguration cfg = new CoreConfiguration().serviceAccountKeyPath(saKeyPath); String cfgSaKeyPath = cfg.getServiceAccountKeyPath(); @@ -45,8 +44,7 @@ void getServiceAccountKeyPath() { void getPrivateKeyPath() { final String privateKeyPath = ""; - CoreConfiguration cfg = - new CoreConfiguration.Builder().privateKeyPath(privateKeyPath).build(); + CoreConfiguration cfg = new CoreConfiguration().privateKeyPath(privateKeyPath); String cfgPrivateKeyPath = cfg.getPrivateKeyPath(); @@ -57,7 +55,7 @@ void getPrivateKeyPath() { void getPrivateKey() { final String privateKey = ""; - CoreConfiguration cfg = new CoreConfiguration.Builder().privateKey(privateKey).build(); + CoreConfiguration cfg = new CoreConfiguration().privateKey(privateKey); String cfgPrivateKey = cfg.getPrivateKey(); @@ -68,8 +66,7 @@ void getPrivateKey() { void getCustomEndpoint() { final String customEndpoint = ""; - CoreConfiguration cfg = - new CoreConfiguration.Builder().customEndpoint(customEndpoint).build(); + CoreConfiguration cfg = new CoreConfiguration().customEndpoint(customEndpoint); String cfgCustomEndpoint = cfg.getCustomEndpoint(); @@ -80,8 +77,7 @@ void getCustomEndpoint() { void getCredentialsFilePath() { final String credFilePath = ""; - CoreConfiguration cfg = - new CoreConfiguration.Builder().credentialsFilePath(credFilePath).build(); + CoreConfiguration cfg = new CoreConfiguration().credentialsFilePath(credFilePath); String cfgCredentialsFilePath = cfg.getCredentialsFilePath(); @@ -92,8 +88,7 @@ void getCredentialsFilePath() { void getTokenCustomUrl() { final String tokenCustomUrl = ""; - CoreConfiguration cfg = - new CoreConfiguration.Builder().tokenCustomUrl(tokenCustomUrl).build(); + CoreConfiguration cfg = new CoreConfiguration().tokenCustomUrl(tokenCustomUrl); String cfgTokenUrl = cfg.getTokenCustomUrl(); @@ -104,8 +99,7 @@ void getTokenCustomUrl() { void getTokenExpirationLeeway() { final long tokenExpireLeeway = 100; - CoreConfiguration cfg = - new CoreConfiguration.Builder().tokenExpirationLeeway(tokenExpireLeeway).build(); + CoreConfiguration cfg = new CoreConfiguration().tokenExpirationLeeway(tokenExpireLeeway); Long cfgTokenExpirationLeeway = cfg.getTokenExpirationLeeway(); @@ -114,7 +108,7 @@ void getTokenExpirationLeeway() { @Test void getDefaultHeader_not_set() { - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); Map defaultHeader = cfg.getDefaultHeader(); assertNull(defaultHeader); @@ -122,7 +116,7 @@ void getDefaultHeader_not_set() { @Test void getServiceAccountKey_not_set() { - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); String serviceAccountKey = cfg.getServiceAccountKey(); assertNull(serviceAccountKey); @@ -130,7 +124,7 @@ void getServiceAccountKey_not_set() { @Test void getServiceAccountKeyPath_not_set() { - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); String serviceAccountKeyPath = cfg.getServiceAccountKeyPath(); assertNull(serviceAccountKeyPath); @@ -138,7 +132,7 @@ void getServiceAccountKeyPath_not_set() { @Test void getPrivateKeyPath_not_set() { - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); String privateKeyPath = cfg.getPrivateKeyPath(); assertNull(privateKeyPath); @@ -146,7 +140,7 @@ void getPrivateKeyPath_not_set() { @Test void getPrivateKey_not_set() { - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); String privateKey = cfg.getPrivateKey(); assertNull(privateKey); @@ -154,7 +148,7 @@ void getPrivateKey_not_set() { @Test void getCustomEndpoint_not_set() { - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); String customEndpoint = cfg.getCustomEndpoint(); assertNull(customEndpoint); @@ -162,7 +156,7 @@ void getCustomEndpoint_not_set() { @Test void getCredentialsFilePath_not_set() { - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); String credentialsFilePath = cfg.getCredentialsFilePath(); assertNull(credentialsFilePath); @@ -170,7 +164,7 @@ void getCredentialsFilePath_not_set() { @Test void getTokenCustomUrl_not_set() { - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); String tokenCustomUrl = cfg.getTokenCustomUrl(); assertNull(tokenCustomUrl); @@ -178,7 +172,7 @@ void getTokenCustomUrl_not_set() { @Test void getTokenExpirationLeeway_not_set() { - CoreConfiguration cfg = new CoreConfiguration.Builder().build(); + CoreConfiguration cfg = new CoreConfiguration(); Long tokenExpirationLeeway = cfg.getTokenExpirationLeeway(); assertNull(tokenExpirationLeeway); diff --git a/examples/authentication/src/main/java/cloud/stackit/sdk/authentication/examples/AuthenticationExample.java b/examples/authentication/src/main/java/cloud/stackit/sdk/authentication/examples/AuthenticationExample.java index cc10d65..95bcd8e 100644 --- a/examples/authentication/src/main/java/cloud/stackit/sdk/authentication/examples/AuthenticationExample.java +++ b/examples/authentication/src/main/java/cloud/stackit/sdk/authentication/examples/AuthenticationExample.java @@ -7,19 +7,17 @@ class AuthenticationExample { public static void main(String[] args) { String SERVICE_ACCOUNT_KEY_PATH = "/path/to/your/sa/key.json"; - String SERIVCE_ACCOUNT_MAIL = "name-1234@sa.stackit.cloud"; + String SERVICE_ACCOUNT_MAIL = "name-1234@sa.stackit.cloud"; CoreConfiguration config = - new CoreConfiguration.Builder() - .serviceAccountKeyPath(SERVICE_ACCOUNT_KEY_PATH) - .build(); + new CoreConfiguration().serviceAccountKeyPath(SERVICE_ACCOUNT_KEY_PATH); try { DefaultApi api = new DefaultApi(config); /* list all organizations */ ListOrganizationsResponse response = - api.listOrganizations(null, SERIVCE_ACCOUNT_MAIL, null, null, null); + api.listOrganizations(null, SERVICE_ACCOUNT_MAIL, null, null, null); System.out.println(response); } catch (Exception e) { diff --git a/examples/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/examples/ResourcemanagerExample.java b/examples/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/examples/ResourcemanagerExample.java index 61a1b0f..7979ba7 100644 --- a/examples/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/examples/ResourcemanagerExample.java +++ b/examples/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/examples/ResourcemanagerExample.java @@ -1,19 +1,20 @@ package cloud.stackit.sdk.resourcemanager.examples; -import cloud.stackit.sdk.resourcemanager.ApiClient; -import cloud.stackit.sdk.resourcemanager.ApiException; +import cloud.stackit.sdk.core.exception.ApiException; import cloud.stackit.sdk.resourcemanager.api.DefaultApi; import cloud.stackit.sdk.resourcemanager.model.CreateFolderPayload; import cloud.stackit.sdk.resourcemanager.model.CreateProjectPayload; import cloud.stackit.sdk.resourcemanager.model.FolderResponse; import cloud.stackit.sdk.resourcemanager.model.Project; +import java.io.IOException; import java.util.Map; import java.util.UUID; class ResourcemanagerExample { - public static void main(String[] args) { - ApiClient apiClient = new ApiClient(); - DefaultApi resourceManagerApi = new DefaultApi(apiClient); + public static void main(String[] args) throws IOException { + // Credentials are read from the credentialsFile in `~/.stackit/credentials.json` or the env + // STACKIT_SERVICE_ACCOUNT_KEY_PATH / STACKIT_SERVICE_ACCOUNT_KEY + DefaultApi resourceManagerApi = new DefaultApi(); // replace this with something useful for real use UUID containerParentId = UUID.randomUUID(); diff --git a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/ApiCallback.java b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/ApiCallback.java index 67e412e..7722099 100644 --- a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/ApiCallback.java +++ b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/ApiCallback.java @@ -12,6 +12,7 @@ package cloud.stackit.sdk.resourcemanager; +import cloud.stackit.sdk.core.exception.ApiException; import java.util.List; import java.util.Map; diff --git a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/ApiClient.java b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/ApiClient.java index ecf69c8..1982b1a 100644 --- a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/ApiClient.java +++ b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/ApiClient.java @@ -14,15 +14,12 @@ import cloud.stackit.sdk.core.auth.SetupAuth; import cloud.stackit.sdk.core.config.CoreConfiguration; -import cloud.stackit.sdk.resourcemanager.auth.ApiKeyAuth; -import cloud.stackit.sdk.resourcemanager.auth.Authentication; -import cloud.stackit.sdk.resourcemanager.auth.HttpBasicAuth; +import cloud.stackit.sdk.core.exception.ApiException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; -import java.net.URI; import java.net.URLConnection; import java.net.URLEncoder; import java.nio.file.Files; @@ -33,7 +30,6 @@ import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; -import java.security.spec.InvalidKeySpecException; import java.text.DateFormat; import java.time.LocalDate; import java.time.OffsetDateTime; @@ -80,8 +76,6 @@ public class ApiClient { protected Map defaultCookieMap = new HashMap(); protected String tempFolderPath = null; - protected Map authentications; - protected DateFormat dateFormat; protected DateFormat datetimeFormat; protected boolean lenientDatetimeFormat; @@ -95,36 +89,22 @@ public class ApiClient { protected JSON json; protected HttpLoggingInterceptor loggingInterceptor; + protected SetupAuth authenticationInterceptor; - /** Basic constructor for ApiClient */ - public ApiClient() { - init(); - initHttpClient(); + protected CoreConfiguration configuration; - // Setup authentications (key: authentication name, value: authentication). - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); + /** Basic constructor for ApiClient */ + public ApiClient() throws IOException { + this(new CoreConfiguration()); } /** - * Basic constructor with custom OkHttpClient + * Basic constructor with custom CoreConfiguration * - * @param client a {@link okhttp3.OkHttpClient} object + * @param config a {@link cloud.stackit.sdk.core.config} object + * @throws IOException thrown when a file can not be found */ - public ApiClient(OkHttpClient client) { - init(); - - httpClient = client; - - // Setup authentications (key: authentication name, value: authentication). - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - public ApiClient(CoreConfiguration config) - throws IOException, - InvalidKeySpecException, - cloud.stackit.sdk.core.exception.ApiException { + public ApiClient(CoreConfiguration config) throws IOException { init(); if (config.getCustomEndpoint() != null && !config.getCustomEndpoint().trim().isEmpty()) { @@ -133,12 +113,15 @@ public ApiClient(CoreConfiguration config) if (config.getDefaultHeader() != null) { defaultHeaderMap = config.getDefaultHeader(); } + this.configuration = config; + + // Setup AuthHandler SetupAuth auth; auth = new SetupAuth(config); auth.init(); - List interceptors = new LinkedList<>(); - interceptors.add(auth.getAuthHandler()); - initHttpClient(interceptors); + authenticationInterceptor = auth; + + initHttpClient(); } protected void initHttpClient() { @@ -151,6 +134,8 @@ protected void initHttpClient(List interceptors) { for (Interceptor interceptor : interceptors) { builder.addInterceptor(interceptor); } + // Adds the Authorization header to requests + builder.addInterceptor(authenticationInterceptor.getAuthHandler()); httpClient = builder.build(); } @@ -162,8 +147,6 @@ protected void init() { // Set default User-Agent. setUserAgent("stackit-sdk-java/resourcemanager"); - - authentications = new HashMap(); } /** @@ -214,27 +197,6 @@ public ApiClient setServerVariables(Map serverVariables) { return this; } - /** - * Get HTTP client - * - * @return An instance of OkHttpClient - */ - public OkHttpClient getHttpClient() { - return httpClient; - } - - /** - * Set HTTP client, which must never be null. - * - * @param newHttpClient An instance of OkHttpClient - * @return Api Client - * @throws java.lang.NullPointerException when newHttpClient is null - */ - public ApiClient setHttpClient(OkHttpClient newHttpClient) { - this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!"); - return this; - } - /** * Get JSON * @@ -386,125 +348,6 @@ public ApiClient setLenientOnJson(boolean lenientOnJson) { return this; } - /** - * Get authentications (key: authentication name, value: authentication). - * - * @return Map of authentication objects - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - * - * @param username Username - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - * - * @param password Password - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - * - * @param apiKey API key - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - * - * @param apiKeyPrefix API key prefix - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set access token for the first OAuth2 authentication. - * - * @param accessToken Access token - */ - public void setAccessToken(String accessToken) { - throw new RuntimeException("No OAuth2 authentication configured!"); - } - - /** - * Helper method to set credentials for AWSV4 Signature - * - * @param accessKey Access Key - * @param secretKey Secret Key - * @param region Region - * @param service Service to access to - */ - public void setAWS4Configuration( - String accessKey, String secretKey, String region, String service) { - throw new RuntimeException("No AWS4 authentication configured!"); - } - - /** - * Helper method to set credentials for AWSV4 Signature - * - * @param accessKey Access Key - * @param secretKey Secret Key - * @param sessionToken Session Token - * @param region Region - * @param service Service to access to - */ - public void setAWS4Configuration( - String accessKey, - String secretKey, - String sessionToken, - String region, - String service) { - throw new RuntimeException("No AWS4 authentication configured!"); - } - /** * Set the User-Agent header's value (by adding to the default header map). * @@ -914,7 +757,7 @@ public String escapeString(String str) { * @param response HTTP response * @param returnType The type of the Java object * @return The deserialized Java object - * @throws cloud.stackit.sdk.resourcemanager.ApiException If fail to deserialize response body, + * @throws cloud.stackit.sdk.core.exception.ApiException If fail to deserialize response body, * i.e. cannot read response body or the Content-Type of the response is not supported. */ @SuppressWarnings("unchecked") @@ -977,7 +820,7 @@ public T deserialize(Response response, Type returnType) throws ApiException * @param obj The Java object * @param contentType The request Content-Type * @return The serialized request body - * @throws cloud.stackit.sdk.resourcemanager.ApiException If fail to serialize the given object + * @throws cloud.stackit.sdk.core.exception.ApiException If fail to serialize the given object */ public RequestBody serialize(Object obj, String contentType) throws ApiException { if (obj instanceof byte[]) { @@ -1007,7 +850,7 @@ public RequestBody serialize(Object obj, String contentType) throws ApiException * Download file from the given response. * * @param response An instance of the Response object - * @throws cloud.stackit.sdk.resourcemanager.ApiException If fail to read file content from + * @throws cloud.stackit.sdk.core.exception.ApiException If fail to read file content from * response and write to disk * @return Downloaded file */ @@ -1069,7 +912,7 @@ public File prepareDownloadFile(Response response) throws IOException { * @param Type * @param call An instance of the Call object * @return ApiResponse<T> - * @throws cloud.stackit.sdk.resourcemanager.ApiException If fail to execute the call + * @throws cloud.stackit.sdk.core.exception.ApiException If fail to execute the call */ public ApiResponse execute(Call call) throws ApiException { return execute(call, null); @@ -1083,7 +926,7 @@ public ApiResponse execute(Call call) throws ApiException { * @param call Call * @return ApiResponse object containing response status, headers and data, which is a Java * object deserialized from response body and would be null when returnType is null. - * @throws cloud.stackit.sdk.resourcemanager.ApiException If fail to execute the call + * @throws cloud.stackit.sdk.core.exception.ApiException If fail to execute the call */ public ApiResponse execute(Call call, Type returnType) throws ApiException { try { @@ -1152,7 +995,7 @@ public void onResponse(Call call, Response response) throws IOException { * @param response Response * @param returnType Return type * @return Type - * @throws cloud.stackit.sdk.resourcemanager.ApiException If the response has an unsuccessful + * @throws cloud.stackit.sdk.core.exception.ApiException If the response has an unsuccessful * status code or fail to deserialize the response body */ public T handleResponse(Response response, Type returnType) throws ApiException { @@ -1209,7 +1052,7 @@ public T handleResponse(Response response, Type returnType) throws ApiExcept * @param authNames The authentications to apply * @param callback Callback for upload/download progress * @return The HTTP call - * @throws cloud.stackit.sdk.resourcemanager.ApiException If fail to serialize the request body + * @throws cloud.stackit.sdk.core.exception.ApiException If fail to serialize the request body * object */ public Call buildCall( @@ -1258,7 +1101,7 @@ public Call buildCall( * @param authNames The authentications to apply * @param callback Callback for upload/download progress * @return The HTTP request - * @throws cloud.stackit.sdk.resourcemanager.ApiException If fail to serialize the request body + * @throws cloud.stackit.sdk.core.exception.ApiException If fail to serialize the request body * object */ public Request buildRequest( @@ -1305,16 +1148,6 @@ public Request buildRequest( List updatedQueryParams = new ArrayList<>(queryParams); - // update parameters with authentication settings - updateParamsForAuth( - authNames, - updatedQueryParams, - headerParams, - cookieParams, - requestBodyToString(reqBody), - method, - URI.create(url)); - final Request.Builder reqBuilder = new Request.Builder() .url(buildUrl(baseUrl, path, updatedQueryParams, collectionQueryParams)); @@ -1442,36 +1275,6 @@ public void processCookieParams(Map cookieParams, Request.Builde } } - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - * @param cookieParams Map of cookie parameters - * @param payload HTTP request body - * @param method HTTP method - * @param uri URI - * @throws cloud.stackit.sdk.resourcemanager.ApiException If fails to update the parameters - */ - public void updateParamsForAuth( - String[] authNames, - List queryParams, - Map headerParams, - Map cookieParams, - String payload, - String method, - URI uri) - throws ApiException { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) { - throw new RuntimeException("Authentication undefined: " + authName); - } - auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); - } - } - /** * Build a form-encoding request body with the given form parameters. * @@ -1688,7 +1491,7 @@ protected KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityExcep * * @param requestBody The HTTP request object * @return The string representation of the HTTP request body - * @throws cloud.stackit.sdk.resourcemanager.ApiException If fail to serialize the request body + * @throws cloud.stackit.sdk.core.exception.ApiException If fail to serialize the request body * object into a string */ protected String requestBodyToString(RequestBody requestBody) throws ApiException { diff --git a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/ApiException.java b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/ApiException.java deleted file mode 100644 index cb9a69f..0000000 --- a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/ApiException.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Resource Manager API - * API v2 to manage resource containers - organizations, folders, projects incl. labels ### Resource Management STACKIT resource management handles the terms _Organization_, _Folder_, _Project_, _Label_, and the hierarchical structure between them. Technically, organizations, folders, and projects are _Resource Containers_ to which a _Label_ can be attached to. The STACKIT _Resource Manager_ provides CRUD endpoints to query and to modify the state. ### Organizations STACKIT organizations are the base element to create and to use cloud-resources. An organization is bound to one customer account. Organizations have a lifecycle. - Organizations are always the root node in resource hierarchy and do not have a parent ### Projects STACKIT projects are needed to use cloud-resources. Projects serve as wrapper for underlying technical structures and processes. Projects have a lifecycle. Projects compared to folders may have different policies. - Projects are optional, but mandatory for cloud-resource usage - A project can be created having either an organization, or a folder as parent - A project must not have a project as parent - Project names under the same parent must not be unique - Root organization cannot be changed ### Label STACKIT labels are key-value pairs including a resource container reference. Labels can be defined and attached freely to resource containers by which resources can be organized and queried. - Policy-based, immutable labels may exists - * - * The version of the OpenAPI document: 2.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package cloud.stackit.sdk.resourcemanager; - -import java.util.List; -import java.util.Map; - -/** ApiException class. */ -@SuppressWarnings("serial") -@javax.annotation.Generated( - value = "org.openapitools.codegen.languages.JavaClientCodegen", - comments = "Generator version: 7.14.0") -public class ApiException extends Exception { - private static final long serialVersionUID = 1L; - - private int code = 0; - private Map> responseHeaders = null; - private String responseBody = null; - - /** Constructor for ApiException. */ - public ApiException() {} - - /** - * Constructor for ApiException. - * - * @param throwable a {@link java.lang.Throwable} object - */ - public ApiException(Throwable throwable) { - super(throwable); - } - - /** - * Constructor for ApiException. - * - * @param message the error message - */ - public ApiException(String message) { - super(message); - } - - /** - * Constructor for ApiException. - * - * @param message the error message - * @param throwable a {@link java.lang.Throwable} object - * @param code HTTP status code - * @param responseHeaders a {@link java.util.Map} of HTTP response headers - * @param responseBody the response body - */ - public ApiException( - String message, - Throwable throwable, - int code, - Map> responseHeaders, - String responseBody) { - super(message, throwable); - this.code = code; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - /** - * Constructor for ApiException. - * - * @param message the error message - * @param code HTTP status code - * @param responseHeaders a {@link java.util.Map} of HTTP response headers - * @param responseBody the response body - */ - public ApiException( - String message, - int code, - Map> responseHeaders, - String responseBody) { - this(message, (Throwable) null, code, responseHeaders, responseBody); - } - - /** - * Constructor for ApiException. - * - * @param message the error message - * @param throwable a {@link java.lang.Throwable} object - * @param code HTTP status code - * @param responseHeaders a {@link java.util.Map} of HTTP response headers - */ - public ApiException( - String message, - Throwable throwable, - int code, - Map> responseHeaders) { - this(message, throwable, code, responseHeaders, null); - } - - /** - * Constructor for ApiException. - * - * @param code HTTP status code - * @param responseHeaders a {@link java.util.Map} of HTTP response headers - * @param responseBody the response body - */ - public ApiException(int code, Map> responseHeaders, String responseBody) { - this( - "Response Code: " + code + " Response Body: " + responseBody, - (Throwable) null, - code, - responseHeaders, - responseBody); - } - - /** - * Constructor for ApiException. - * - * @param code HTTP status code - * @param message a {@link java.lang.String} object - */ - public ApiException(int code, String message) { - super(message); - this.code = code; - } - - /** - * Constructor for ApiException. - * - * @param code HTTP status code - * @param message the error message - * @param responseHeaders a {@link java.util.Map} of HTTP response headers - * @param responseBody the response body - */ - public ApiException( - int code, - String message, - Map> responseHeaders, - String responseBody) { - this(code, message); - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - /** - * Get the HTTP status code. - * - * @return HTTP status code - */ - public int getCode() { - return code; - } - - /** - * Get the HTTP response headers. - * - * @return A map of list of string - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - - /** - * Get the HTTP response body. - * - * @return Response body in the form of string - */ - public String getResponseBody() { - return responseBody; - } - - /** - * Get the exception message including HTTP response data. - * - * @return The exception message - */ - public String getMessage() { - return String.format( - "Message: %s%nHTTP response code: %s%nHTTP response body: %s%nHTTP response headers: %s", - super.getMessage(), - this.getCode(), - this.getResponseBody(), - this.getResponseHeaders()); - } -} diff --git a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/Configuration.java b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/Configuration.java deleted file mode 100644 index 2656d56..0000000 --- a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/Configuration.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Resource Manager API - * API v2 to manage resource containers - organizations, folders, projects incl. labels ### Resource Management STACKIT resource management handles the terms _Organization_, _Folder_, _Project_, _Label_, and the hierarchical structure between them. Technically, organizations, folders, and projects are _Resource Containers_ to which a _Label_ can be attached to. The STACKIT _Resource Manager_ provides CRUD endpoints to query and to modify the state. ### Organizations STACKIT organizations are the base element to create and to use cloud-resources. An organization is bound to one customer account. Organizations have a lifecycle. - Organizations are always the root node in resource hierarchy and do not have a parent ### Projects STACKIT projects are needed to use cloud-resources. Projects serve as wrapper for underlying technical structures and processes. Projects have a lifecycle. Projects compared to folders may have different policies. - Projects are optional, but mandatory for cloud-resource usage - A project can be created having either an organization, or a folder as parent - A project must not have a project as parent - Project names under the same parent must not be unique - Root organization cannot be changed ### Label STACKIT labels are key-value pairs including a resource container reference. Labels can be defined and attached freely to resource containers by which resources can be organized and queried. - Policy-based, immutable labels may exists - * - * The version of the OpenAPI document: 2.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package cloud.stackit.sdk.resourcemanager; - -import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Supplier; - -@javax.annotation.Generated( - value = "org.openapitools.codegen.languages.JavaClientCodegen", - comments = "Generator version: 7.14.0") -public class Configuration { - public static final String VERSION = "2.0"; - - private static final AtomicReference defaultApiClient = new AtomicReference<>(); - private static volatile Supplier apiClientFactory = ApiClient::new; - - /** - * Get the default API client, which would be used when creating API instances without providing - * an API client. - * - * @return Default API client - */ - public static ApiClient getDefaultApiClient() { - ApiClient client = defaultApiClient.get(); - if (client == null) { - client = - defaultApiClient.updateAndGet( - val -> { - if (val != null) { // changed by another thread - return val; - } - return apiClientFactory.get(); - }); - } - return client; - } - - /** - * Set the default API client, which would be used when creating API instances without providing - * an API client. - * - * @param apiClient API client - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient.set(apiClient); - } - - /** set the callback used to create new ApiClient objects */ - public static void setApiClientFactory(Supplier factory) { - apiClientFactory = Objects.requireNonNull(factory); - } - - private Configuration() {} -} diff --git a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/api/DefaultApi.java b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/api/DefaultApi.java index 3a78097..19e9bda 100644 --- a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/api/DefaultApi.java +++ b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/api/DefaultApi.java @@ -13,11 +13,10 @@ package cloud.stackit.sdk.resourcemanager.api; import cloud.stackit.sdk.core.config.CoreConfiguration; +import cloud.stackit.sdk.core.exception.ApiException; import cloud.stackit.sdk.resourcemanager.ApiCallback; import cloud.stackit.sdk.resourcemanager.ApiClient; -import cloud.stackit.sdk.resourcemanager.ApiException; import cloud.stackit.sdk.resourcemanager.ApiResponse; -import cloud.stackit.sdk.resourcemanager.Configuration; import cloud.stackit.sdk.resourcemanager.Pair; import cloud.stackit.sdk.resourcemanager.model.CreateFolderPayload; import cloud.stackit.sdk.resourcemanager.model.CreateProjectPayload; @@ -36,7 +35,6 @@ import java.io.IOException; import java.lang.reflect.Type; import java.math.BigDecimal; -import java.security.spec.InvalidKeySpecException; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.HashMap; @@ -48,20 +46,11 @@ public class DefaultApi { private int localHostIndex; private String localCustomBaseUrl; - public DefaultApi() { - this(Configuration.getDefaultApiClient()); + public DefaultApi() throws IOException { + this(new CoreConfiguration()); } - public DefaultApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - // TODO: remove in follow up story the service specific ApiException and use instead the - // ApiException of core - public DefaultApi(CoreConfiguration config) - throws InvalidKeySpecException, - cloud.stackit.sdk.core.exception.ApiException, - IOException { + public DefaultApi(CoreConfiguration config) throws IOException { if (config.getCustomEndpoint() != null && !config.getCustomEndpoint().trim().isEmpty()) { localCustomBaseUrl = config.getCustomEndpoint(); } diff --git a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/auth/ApiKeyAuth.java b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/auth/ApiKeyAuth.java deleted file mode 100644 index 12c7d3e..0000000 --- a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/auth/ApiKeyAuth.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Resource Manager API - * API v2 to manage resource containers - organizations, folders, projects incl. labels ### Resource Management STACKIT resource management handles the terms _Organization_, _Folder_, _Project_, _Label_, and the hierarchical structure between them. Technically, organizations, folders, and projects are _Resource Containers_ to which a _Label_ can be attached to. The STACKIT _Resource Manager_ provides CRUD endpoints to query and to modify the state. ### Organizations STACKIT organizations are the base element to create and to use cloud-resources. An organization is bound to one customer account. Organizations have a lifecycle. - Organizations are always the root node in resource hierarchy and do not have a parent ### Projects STACKIT projects are needed to use cloud-resources. Projects serve as wrapper for underlying technical structures and processes. Projects have a lifecycle. Projects compared to folders may have different policies. - Projects are optional, but mandatory for cloud-resource usage - A project can be created having either an organization, or a folder as parent - A project must not have a project as parent - Project names under the same parent must not be unique - Root organization cannot be changed ### Label STACKIT labels are key-value pairs including a resource container reference. Labels can be defined and attached freely to resource containers by which resources can be organized and queried. - Policy-based, immutable labels may exists - * - * The version of the OpenAPI document: 2.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package cloud.stackit.sdk.resourcemanager.auth; - -import cloud.stackit.sdk.resourcemanager.ApiException; -import cloud.stackit.sdk.resourcemanager.Pair; -import java.net.URI; -import java.util.List; -import java.util.Map; - -@javax.annotation.Generated( - value = "org.openapitools.codegen.languages.JavaClientCodegen", - comments = "Generator version: 7.14.0") -public class ApiKeyAuth implements Authentication { - private final String location; - private final String paramName; - - private String apiKey; - private String apiKeyPrefix; - - public ApiKeyAuth(String location, String paramName) { - this.location = location; - this.paramName = paramName; - } - - public String getLocation() { - return location; - } - - public String getParamName() { - return paramName; - } - - public String getApiKey() { - return apiKey; - } - - public void setApiKey(String apiKey) { - this.apiKey = apiKey; - } - - public String getApiKeyPrefix() { - return apiKeyPrefix; - } - - public void setApiKeyPrefix(String apiKeyPrefix) { - this.apiKeyPrefix = apiKeyPrefix; - } - - @Override - public void applyToParams( - List queryParams, - Map headerParams, - Map cookieParams, - String payload, - String method, - URI uri) - throws ApiException { - if (apiKey == null) { - return; - } - String value; - if (apiKeyPrefix != null) { - value = apiKeyPrefix + " " + apiKey; - } else { - value = apiKey; - } - if ("query".equals(location)) { - queryParams.add(new Pair(paramName, value)); - } else if ("header".equals(location)) { - headerParams.put(paramName, value); - } else if ("cookie".equals(location)) { - cookieParams.put(paramName, value); - } - } -} diff --git a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/auth/Authentication.java b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/auth/Authentication.java deleted file mode 100644 index c990cff..0000000 --- a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/auth/Authentication.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Resource Manager API - * API v2 to manage resource containers - organizations, folders, projects incl. labels ### Resource Management STACKIT resource management handles the terms _Organization_, _Folder_, _Project_, _Label_, and the hierarchical structure between them. Technically, organizations, folders, and projects are _Resource Containers_ to which a _Label_ can be attached to. The STACKIT _Resource Manager_ provides CRUD endpoints to query and to modify the state. ### Organizations STACKIT organizations are the base element to create and to use cloud-resources. An organization is bound to one customer account. Organizations have a lifecycle. - Organizations are always the root node in resource hierarchy and do not have a parent ### Projects STACKIT projects are needed to use cloud-resources. Projects serve as wrapper for underlying technical structures and processes. Projects have a lifecycle. Projects compared to folders may have different policies. - Projects are optional, but mandatory for cloud-resource usage - A project can be created having either an organization, or a folder as parent - A project must not have a project as parent - Project names under the same parent must not be unique - Root organization cannot be changed ### Label STACKIT labels are key-value pairs including a resource container reference. Labels can be defined and attached freely to resource containers by which resources can be organized and queried. - Policy-based, immutable labels may exists - * - * The version of the OpenAPI document: 2.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package cloud.stackit.sdk.resourcemanager.auth; - -import cloud.stackit.sdk.resourcemanager.ApiException; -import cloud.stackit.sdk.resourcemanager.Pair; -import java.net.URI; -import java.util.List; -import java.util.Map; - -@javax.annotation.Generated( - value = "org.openapitools.codegen.languages.JavaClientCodegen", - comments = "Generator version: 7.14.0") -public interface Authentication { - /** - * Apply authentication settings to header and query params. - * - * @param queryParams List of query parameters - * @param headerParams Map of header parameters - * @param cookieParams Map of cookie parameters - * @param payload HTTP request body - * @param method HTTP method - * @param uri URI - * @throws ApiException if failed to update the parameters - */ - void applyToParams( - List queryParams, - Map headerParams, - Map cookieParams, - String payload, - String method, - URI uri) - throws ApiException; -} diff --git a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/auth/HttpBasicAuth.java b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/auth/HttpBasicAuth.java deleted file mode 100644 index 8f64bd2..0000000 --- a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/auth/HttpBasicAuth.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Resource Manager API - * API v2 to manage resource containers - organizations, folders, projects incl. labels ### Resource Management STACKIT resource management handles the terms _Organization_, _Folder_, _Project_, _Label_, and the hierarchical structure between them. Technically, organizations, folders, and projects are _Resource Containers_ to which a _Label_ can be attached to. The STACKIT _Resource Manager_ provides CRUD endpoints to query and to modify the state. ### Organizations STACKIT organizations are the base element to create and to use cloud-resources. An organization is bound to one customer account. Organizations have a lifecycle. - Organizations are always the root node in resource hierarchy and do not have a parent ### Projects STACKIT projects are needed to use cloud-resources. Projects serve as wrapper for underlying technical structures and processes. Projects have a lifecycle. Projects compared to folders may have different policies. - Projects are optional, but mandatory for cloud-resource usage - A project can be created having either an organization, or a folder as parent - A project must not have a project as parent - Project names under the same parent must not be unique - Root organization cannot be changed ### Label STACKIT labels are key-value pairs including a resource container reference. Labels can be defined and attached freely to resource containers by which resources can be organized and queried. - Policy-based, immutable labels may exists - * - * The version of the OpenAPI document: 2.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package cloud.stackit.sdk.resourcemanager.auth; - -import cloud.stackit.sdk.resourcemanager.ApiException; -import cloud.stackit.sdk.resourcemanager.Pair; -import java.net.URI; -import java.util.List; -import java.util.Map; -import okhttp3.Credentials; - -public class HttpBasicAuth implements Authentication { - private String username; - private String password; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public void applyToParams( - List queryParams, - Map headerParams, - Map cookieParams, - String payload, - String method, - URI uri) - throws ApiException { - if (username == null && password == null) { - return; - } - headerParams.put( - "Authorization", - Credentials.basic( - username == null ? "" : username, password == null ? "" : password)); - } -} diff --git a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/auth/HttpBearerAuth.java b/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/auth/HttpBearerAuth.java deleted file mode 100644 index 3922811..0000000 --- a/services/resourcemanager/src/main/java/cloud/stackit/sdk/resourcemanager/auth/HttpBearerAuth.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Resource Manager API - * API v2 to manage resource containers - organizations, folders, projects incl. labels ### Resource Management STACKIT resource management handles the terms _Organization_, _Folder_, _Project_, _Label_, and the hierarchical structure between them. Technically, organizations, folders, and projects are _Resource Containers_ to which a _Label_ can be attached to. The STACKIT _Resource Manager_ provides CRUD endpoints to query and to modify the state. ### Organizations STACKIT organizations are the base element to create and to use cloud-resources. An organization is bound to one customer account. Organizations have a lifecycle. - Organizations are always the root node in resource hierarchy and do not have a parent ### Projects STACKIT projects are needed to use cloud-resources. Projects serve as wrapper for underlying technical structures and processes. Projects have a lifecycle. Projects compared to folders may have different policies. - Projects are optional, but mandatory for cloud-resource usage - A project can be created having either an organization, or a folder as parent - A project must not have a project as parent - Project names under the same parent must not be unique - Root organization cannot be changed ### Label STACKIT labels are key-value pairs including a resource container reference. Labels can be defined and attached freely to resource containers by which resources can be organized and queried. - Policy-based, immutable labels may exists - * - * The version of the OpenAPI document: 2.0 - * - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -package cloud.stackit.sdk.resourcemanager.auth; - -import cloud.stackit.sdk.resourcemanager.ApiException; -import cloud.stackit.sdk.resourcemanager.Pair; -import java.net.URI; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Supplier; - -@javax.annotation.Generated( - value = "org.openapitools.codegen.languages.JavaClientCodegen", - comments = "Generator version: 7.14.0") -public class HttpBearerAuth implements Authentication { - private final String scheme; - private Supplier tokenSupplier; - - public HttpBearerAuth(String scheme) { - this.scheme = scheme; - } - - /** - * Gets the token, which together with the scheme, will be sent as the value of the - * Authorization header. - * - * @return The bearer token - */ - public String getBearerToken() { - return tokenSupplier.get(); - } - - /** - * Sets the token, which together with the scheme, will be sent as the value of the - * Authorization header. - * - * @param bearerToken The bearer token to send in the Authorization header - */ - public void setBearerToken(String bearerToken) { - this.tokenSupplier = () -> bearerToken; - } - - /** - * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the - * Authorization header. - * - * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header - */ - public void setBearerToken(Supplier tokenSupplier) { - this.tokenSupplier = tokenSupplier; - } - - @Override - public void applyToParams( - List queryParams, - Map headerParams, - Map cookieParams, - String payload, - String method, - URI uri) - throws ApiException { - String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); - if (bearerToken == null) { - return; - } - - headerParams.put( - "Authorization", - (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); - } - - private static String upperCaseBearer(String scheme) { - return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; - } -}