From caa3b1ccb3fbbcf2221497b509f325eaac9c2538 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 17 Sep 2024 10:51:57 +0530 Subject: [PATCH 001/126] SK-1663 Basic scaffolding and project structure for v2 --- v1/src/main/java/DetokenizeExample.java | 71 +++++++++++ v1/src/main/java/InsertExample.java | 84 +++++++++++++ .../main/java/com/skyflow/Configuration.java | 0 .../com/skyflow/common/utils/Constants.java | 0 .../com/skyflow/common/utils/Helpers.java | 0 .../com/skyflow/common/utils/HttpUtility.java | 0 .../com/skyflow/common/utils/LogUtil.java | 0 .../com/skyflow/common/utils/TokenUtils.java | 0 .../com/skyflow/common/utils/Validators.java | 0 .../com/skyflow/entities/DeleteInput.java | 0 .../com/skyflow/entities/DeleteOptions.java | 0 .../skyflow/entities/DeleteRecordInput.java | 0 .../com/skyflow/entities/DetokenizeInput.java | 0 .../skyflow/entities/DetokenizeRecord.java | 0 .../com/skyflow/entities/GetByIdInput.java | 0 .../skyflow/entities/GetByIdRecordInput.java | 0 .../java/com/skyflow/entities/GetInput.java | 0 .../java/com/skyflow/entities/GetOptions.java | 0 .../com/skyflow/entities/GetRecordInput.java | 0 .../skyflow/entities/InsertBulkOptions.java | 0 .../com/skyflow/entities/InsertInput.java | 0 .../com/skyflow/entities/InsertOptions.java | 0 .../skyflow/entities/InsertRecordInput.java | 0 .../java/com/skyflow/entities/LogLevel.java | 0 .../java/com/skyflow/entities/QueryInput.java | 0 .../com/skyflow/entities/QueryOptions.java | 0 .../skyflow/entities/QueryRecordInput.java | 0 .../com/skyflow/entities/RedactionType.java | 0 .../com/skyflow/entities/RequestMethod.java | 0 .../com/skyflow/entities/ResponseToken.java | 0 .../entities/SkyflowConfiguration.java | 0 .../com/skyflow/entities/TokenProvider.java | 0 .../com/skyflow/entities/UpdateInput.java | 0 .../com/skyflow/entities/UpdateOptions.java | 0 .../skyflow/entities/UpdateRecordInput.java | 0 .../com/skyflow/entities/UpsertOption.java | 0 .../java/com/skyflow/errors/ErrorCode.java | 0 .../com/skyflow/errors/SkyflowException.java | 0 .../main/java/com/skyflow/logs/DebugLogs.java | 0 .../main/java/com/skyflow/logs/ErrorLogs.java | 0 .../main/java/com/skyflow/logs/InfoLogs.java | 0 .../main/java/com/skyflow/logs/WarnLogs.java | 0 .../serviceaccount/util/BearerToken.java | 0 .../util/SignedDataTokenResponse.java | 0 .../serviceaccount/util/SignedDataTokens.java | 0 .../skyflow/serviceaccount/util/Token.java | 0 .../com/skyflow/vault/DeleteBySkyflowId.java | 0 .../java/com/skyflow/vault/Detokenize.java | 0 .../src}/main/java/com/skyflow/vault/Get.java | 0 .../com/skyflow/vault/GetBySkyflowId.java | 0 .../main/java/com/skyflow/vault/Insert.java | 0 .../main/java/com/skyflow/vault/Skyflow.java | 0 .../com/skyflow/vault/UpdateBySkyflowId.java | 0 .../com/skyflow/common/utils/HelpersTest.java | 0 .../skyflow/common/utils/HttpUtilityTest.java | 0 .../skyflow/common/utils/TokenUtilsTest.java | 0 .../utils/TokenUtilsValidTokenTest.java | 0 .../skyflow/common/utils/ValidatorsTest.java | 0 .../serviceaccount/util/BearerTokenTest.java | 0 .../util/SignedDataTokenResponseTest.java | 0 .../util/SignedDataTokensTest.java | 0 .../serviceaccount/util/TokenTest.java | 0 .../com/skyflow/vault/DeleteMethodTest.java | 0 .../java/com/skyflow/vault/GetMethodTest.java | 0 .../skyflow/vault/InvokeConnectionTest.java | 0 .../java/com/skyflow/vault/SkyflowTest.java | 0 .../test/resources/invalidCredentials.json | 0 {src => v1/src}/test/resources/notJson.txt | 0 .../com/skyflow/client/SkyflowClient.java | 117 ++++++++++++++++++ .../com/skyflow/config/ConnectionConfig.java | 11 ++ .../java/com/skyflow/config/Credentials.java | 11 ++ .../com/skyflow/config/ManagementConfig.java | 11 ++ .../java/com/skyflow/config/VaultConfig.java | 11 ++ .../java/com/skyflow/errors/SkyflowError.java | 10 ++ .../management/controller/policy/Policy.java | 23 ++++ .../management/controller/role/Role.java | 23 ++++ .../management/controller/vault/Vault.java | 23 ++++ .../createVault/CreateVaultRequest.java | 10 ++ .../deletePolicy/DeletePolicyRequest.java | 10 ++ .../createVault/CreateVaultResponse.java | 10 ++ .../deletePolicy/DeletePolicyResponse.java | 10 ++ .../management/service/ManagementService.java | 46 +++++++ v2/main/java/com/skyflow/utils/Builder.java | 4 + v2/main/java/com/skyflow/utils/LogLevel.java | 9 ++ .../utils/validations/Validations.java | 10 ++ .../controller/audit/AuditController.java | 18 +++ .../binlookup/BinLookupController.java | 18 +++ .../connections/ConnectionsController.java | 18 +++ .../controller/detect/DetectController.java | 28 +++++ .../vault/model/request/AuditRequest.java | 11 ++ .../model/request/DetokenizeRequest.java | 11 ++ .../vault/model/request/InsertRequest.java | 11 ++ .../vault/model/response/AuditResponse.java | 10 ++ .../model/response/BinLookupResponse.java | 10 ++ .../model/response/ConnectionResponse.java | 10 ++ .../vault/model/response/DetectResponse.java | 10 ++ .../model/response/DetokenizeResponse.java | 10 ++ .../vault/model/response/InsertResponse.java | 10 ++ .../skyflow/vault/service/VaultService.java | 61 +++++++++ 99 files changed, 740 insertions(+) create mode 100644 v1/src/main/java/DetokenizeExample.java create mode 100644 v1/src/main/java/InsertExample.java rename {src => v1/src}/main/java/com/skyflow/Configuration.java (100%) rename {src => v1/src}/main/java/com/skyflow/common/utils/Constants.java (100%) rename {src => v1/src}/main/java/com/skyflow/common/utils/Helpers.java (100%) rename {src => v1/src}/main/java/com/skyflow/common/utils/HttpUtility.java (100%) rename {src => v1/src}/main/java/com/skyflow/common/utils/LogUtil.java (100%) rename {src => v1/src}/main/java/com/skyflow/common/utils/TokenUtils.java (100%) rename {src => v1/src}/main/java/com/skyflow/common/utils/Validators.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/DeleteInput.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/DeleteOptions.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/DeleteRecordInput.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/DetokenizeInput.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/DetokenizeRecord.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/GetByIdInput.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/GetByIdRecordInput.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/GetInput.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/GetOptions.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/GetRecordInput.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/InsertBulkOptions.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/InsertInput.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/InsertOptions.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/InsertRecordInput.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/LogLevel.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/QueryInput.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/QueryOptions.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/QueryRecordInput.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/RedactionType.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/RequestMethod.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/ResponseToken.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/SkyflowConfiguration.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/TokenProvider.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/UpdateInput.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/UpdateOptions.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/UpdateRecordInput.java (100%) rename {src => v1/src}/main/java/com/skyflow/entities/UpsertOption.java (100%) rename {src => v1/src}/main/java/com/skyflow/errors/ErrorCode.java (100%) rename {src => v1/src}/main/java/com/skyflow/errors/SkyflowException.java (100%) rename {src => v1/src}/main/java/com/skyflow/logs/DebugLogs.java (100%) rename {src => v1/src}/main/java/com/skyflow/logs/ErrorLogs.java (100%) rename {src => v1/src}/main/java/com/skyflow/logs/InfoLogs.java (100%) rename {src => v1/src}/main/java/com/skyflow/logs/WarnLogs.java (100%) rename {src => v1/src}/main/java/com/skyflow/serviceaccount/util/BearerToken.java (100%) rename {src => v1/src}/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java (100%) rename {src => v1/src}/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java (100%) rename {src => v1/src}/main/java/com/skyflow/serviceaccount/util/Token.java (100%) rename {src => v1/src}/main/java/com/skyflow/vault/DeleteBySkyflowId.java (100%) rename {src => v1/src}/main/java/com/skyflow/vault/Detokenize.java (100%) rename {src => v1/src}/main/java/com/skyflow/vault/Get.java (100%) rename {src => v1/src}/main/java/com/skyflow/vault/GetBySkyflowId.java (100%) rename {src => v1/src}/main/java/com/skyflow/vault/Insert.java (100%) rename {src => v1/src}/main/java/com/skyflow/vault/Skyflow.java (100%) rename {src => v1/src}/main/java/com/skyflow/vault/UpdateBySkyflowId.java (100%) rename {src => v1/src}/test/java/com/skyflow/common/utils/HelpersTest.java (100%) rename {src => v1/src}/test/java/com/skyflow/common/utils/HttpUtilityTest.java (100%) rename {src => v1/src}/test/java/com/skyflow/common/utils/TokenUtilsTest.java (100%) rename {src => v1/src}/test/java/com/skyflow/common/utils/TokenUtilsValidTokenTest.java (100%) rename {src => v1/src}/test/java/com/skyflow/common/utils/ValidatorsTest.java (100%) rename {src => v1/src}/test/java/com/skyflow/serviceaccount/util/BearerTokenTest.java (100%) rename {src => v1/src}/test/java/com/skyflow/serviceaccount/util/SignedDataTokenResponseTest.java (100%) rename {src => v1/src}/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTest.java (100%) rename {src => v1/src}/test/java/com/skyflow/serviceaccount/util/TokenTest.java (100%) rename {src => v1/src}/test/java/com/skyflow/vault/DeleteMethodTest.java (100%) rename {src => v1/src}/test/java/com/skyflow/vault/GetMethodTest.java (100%) rename {src => v1/src}/test/java/com/skyflow/vault/InvokeConnectionTest.java (100%) rename {src => v1/src}/test/java/com/skyflow/vault/SkyflowTest.java (100%) rename {src => v1/src}/test/resources/invalidCredentials.json (100%) rename {src => v1/src}/test/resources/notJson.txt (100%) create mode 100644 v2/main/java/com/skyflow/client/SkyflowClient.java create mode 100644 v2/main/java/com/skyflow/config/ConnectionConfig.java create mode 100644 v2/main/java/com/skyflow/config/Credentials.java create mode 100644 v2/main/java/com/skyflow/config/ManagementConfig.java create mode 100644 v2/main/java/com/skyflow/config/VaultConfig.java create mode 100644 v2/main/java/com/skyflow/errors/SkyflowError.java create mode 100644 v2/main/java/com/skyflow/management/controller/policy/Policy.java create mode 100644 v2/main/java/com/skyflow/management/controller/role/Role.java create mode 100644 v2/main/java/com/skyflow/management/controller/vault/Vault.java create mode 100644 v2/main/java/com/skyflow/management/model/request/createVault/CreateVaultRequest.java create mode 100644 v2/main/java/com/skyflow/management/model/request/deletePolicy/DeletePolicyRequest.java create mode 100644 v2/main/java/com/skyflow/management/model/response/createVault/CreateVaultResponse.java create mode 100644 v2/main/java/com/skyflow/management/model/response/deletePolicy/DeletePolicyResponse.java create mode 100644 v2/main/java/com/skyflow/management/service/ManagementService.java create mode 100644 v2/main/java/com/skyflow/utils/Builder.java create mode 100644 v2/main/java/com/skyflow/utils/LogLevel.java create mode 100644 v2/main/java/com/skyflow/utils/validations/Validations.java create mode 100644 v2/main/java/com/skyflow/vault/controller/audit/AuditController.java create mode 100644 v2/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java create mode 100644 v2/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java create mode 100644 v2/main/java/com/skyflow/vault/controller/detect/DetectController.java create mode 100644 v2/main/java/com/skyflow/vault/model/request/AuditRequest.java create mode 100644 v2/main/java/com/skyflow/vault/model/request/DetokenizeRequest.java create mode 100644 v2/main/java/com/skyflow/vault/model/request/InsertRequest.java create mode 100644 v2/main/java/com/skyflow/vault/model/response/AuditResponse.java create mode 100644 v2/main/java/com/skyflow/vault/model/response/BinLookupResponse.java create mode 100644 v2/main/java/com/skyflow/vault/model/response/ConnectionResponse.java create mode 100644 v2/main/java/com/skyflow/vault/model/response/DetectResponse.java create mode 100644 v2/main/java/com/skyflow/vault/model/response/DetokenizeResponse.java create mode 100644 v2/main/java/com/skyflow/vault/model/response/InsertResponse.java create mode 100644 v2/main/java/com/skyflow/vault/service/VaultService.java diff --git a/v1/src/main/java/DetokenizeExample.java b/v1/src/main/java/DetokenizeExample.java new file mode 100644 index 00000000..8b2a657f --- /dev/null +++ b/v1/src/main/java/DetokenizeExample.java @@ -0,0 +1,71 @@ +/* + Copyright (c) 2022 Skyflow, Inc. +*/ + +import com.skyflow.Configuration; +import com.skyflow.entities.*; +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.vault.Skyflow; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + + +public class DetokenizeExample { + + public static void main(String[] args) { + + try { + SkyflowConfiguration config = new SkyflowConfiguration( + "l906001b0b4e4843a69b091f278f7017", + "https://sb.area51.vault.skyflowapis.dev", + new DemoTokenProvider() + ); + + Configuration.setLogLevel(LogLevel.DEBUG); + + Skyflow skyflowClient = Skyflow.init(config); + JSONObject records = new JSONObject(); + JSONArray recordsArray = new JSONArray(); + + JSONObject record = new JSONObject(); + record.put("token", "4304-0207-2378-9259"); + record.put("redaction", RedactionType.PLAIN_TEXT.toString()); + JSONObject record1 = new JSONObject(); + record1.put("token", "3809-9467-7122-3994"); + record1.put("redaction", RedactionType.PLAIN_TEXT.toString()); + recordsArray.add(record); + recordsArray.add(record1); + records.put("records", recordsArray); + + JSONObject response = skyflowClient.detokenize(records); + System.out.println(response); + + } catch (SkyflowException e) { + e.printStackTrace(); + System.out.println(e.getData()); + } + + } + + static class DemoTokenProvider implements TokenProvider { + + private String bearerToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwczovL21hbmFnZS5za3lmbG93YXBpcy5kZXYiLCJjbGkiOiJ2OGY0NTE1OWYxNjA0NzViYTk4MjAxOGJkMmFiMmVlZSIsImV4cCI6MTcxMTA5NDYwMSwiaWF0IjoxNzExMDkxMDAyLCJpc3MiOiJzYS1hdXRoQG1hbmFnZS5za3lmbG93YXBpcy5kZXYiLCJqdGkiOiJuMzk0OGI1ODIxOGQ0NWQ2OWQyYTExZjMwYjk2YmRiMiIsImtleSI6Imc0NDRmZTQxMmEzZTQ5ZTA5YjJlN2E4ZGE2ZDhkZWNlIiwic2NwIjpudWxsLCJzdWIiOiJzZGstZTJlLWJsaXR6LW5ldyJ9.D1bkgk8U5yC7Ped-eC8W4zc7CSImRdMbH2jvx9o_ADGYLmRsUJg3Jm004RtmCz6Vqy1hfgBobje4SgccavlYQTO3JUdtwx9SLJVwMGSEYnM_LvTAKqTVInJkvkKgJThHfh6na4iKWZlzUjNjhIFVjLcEhJuikRO68dpw8YFo84mc8iAjzW4BiKIyfAPzEUqIYq6VNUtz80ZsIhkfMz99_93NFf_KKzIR_a-MVYa7LzJfCrO6EQ-1fXLrTeJkusuco4MFSOf3-x55TimJygcQJjJC34lEtDK0OhFJWbM65gJRpRv6ftaknXRcp8caVE6xkqXI320O6GcBZK933aHw8w"; + + @Override + public String getBearerToken() throws Exception { +// ResponseToken response = null; +// try { +// String filePath = "/home/vivekj/SKYFLOW/SDKs/skyflow-java/samples/credentials.json"; +// if (Token.isExpired(bearerToken)) { +// response = Token.generateBearerToken(filePath); +// bearerToken = response.getAccessToken(); +// } +// } catch (SkyflowException e) { +// e.printStackTrace(); +// } + + return bearerToken; + } + } +} diff --git a/v1/src/main/java/InsertExample.java b/v1/src/main/java/InsertExample.java new file mode 100644 index 00000000..1cdd0900 --- /dev/null +++ b/v1/src/main/java/InsertExample.java @@ -0,0 +1,84 @@ +/* + Copyright (c) 2022 Skyflow, Inc. +*/ + +import com.skyflow.Configuration; +import com.skyflow.entities.*; +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.vault.Skyflow; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +public class InsertExample { + + public static void main(String[] args) { + // blitz +// String vaultID = ""; +// String vaultURL = ""; + + // stage + String vaultID = "aef438f3be974c8f897795ab02248f78"; + String vaultURL = "https://cf5643204594.vault.skyflowapis.tech"; + + try { + SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); + + Configuration.setLogLevel(LogLevel.DEBUG); + Skyflow skyflowClient = Skyflow.init(config); + JSONObject records = new JSONObject(); + JSONArray recordsArray = new JSONArray(); + + JSONObject record = new JSONObject(); + record.put("table", "customers"); + JSONObject fields = new JSONObject(); + fields.put("name", "chandragupta maurya"); + fields.put("card_number", "4111111111111111"); + fields.put("email", "chandragupta.maurya@test.com"); + record.put("fields", fields); + + JSONObject record2 = new JSONObject(); + record2.put("table", "pii_fields_upsert"); + JSONObject fields2 = new JSONObject(); + fields2.put("name", "java coe"); + fields2.put("card_number", "4111111111111111"); + fields2.put("expiration_year", "2025"); + fields2.put("expiration_month", "11"); + fields2.put("expiration_date", "11/25"); + fields2.put("cvv", "123"); + record2.put("fields", fields2); + + recordsArray.add(record); +// recordsArray.add(record2); + records.put("records", recordsArray); + + InsertOptions insertOptions = new InsertOptions(false); + JSONObject res = skyflowClient.insert(records, insertOptions); + + System.out.println("final response " + res); + } catch (SkyflowException e) { + System.out.println(e); + e.printStackTrace(); + } + } + + static class DemoTokenProvider implements TokenProvider { + private String bearerToken; + + @Override + public String getBearerToken() throws Exception { + ResponseToken response = null; + String env = "stage"; + try { + String filePath = "/home/vivekj/Documents/credentials/sdk-integration-tests/" + env + "-credentials.json"; + if (Token.isExpired(bearerToken)) { + response = Token.generateBearerToken(filePath); + bearerToken = response.getAccessToken(); + } + } catch (SkyflowException e) { + e.printStackTrace(); + } + return bearerToken; + } + } +} diff --git a/src/main/java/com/skyflow/Configuration.java b/v1/src/main/java/com/skyflow/Configuration.java similarity index 100% rename from src/main/java/com/skyflow/Configuration.java rename to v1/src/main/java/com/skyflow/Configuration.java diff --git a/src/main/java/com/skyflow/common/utils/Constants.java b/v1/src/main/java/com/skyflow/common/utils/Constants.java similarity index 100% rename from src/main/java/com/skyflow/common/utils/Constants.java rename to v1/src/main/java/com/skyflow/common/utils/Constants.java diff --git a/src/main/java/com/skyflow/common/utils/Helpers.java b/v1/src/main/java/com/skyflow/common/utils/Helpers.java similarity index 100% rename from src/main/java/com/skyflow/common/utils/Helpers.java rename to v1/src/main/java/com/skyflow/common/utils/Helpers.java diff --git a/src/main/java/com/skyflow/common/utils/HttpUtility.java b/v1/src/main/java/com/skyflow/common/utils/HttpUtility.java similarity index 100% rename from src/main/java/com/skyflow/common/utils/HttpUtility.java rename to v1/src/main/java/com/skyflow/common/utils/HttpUtility.java diff --git a/src/main/java/com/skyflow/common/utils/LogUtil.java b/v1/src/main/java/com/skyflow/common/utils/LogUtil.java similarity index 100% rename from src/main/java/com/skyflow/common/utils/LogUtil.java rename to v1/src/main/java/com/skyflow/common/utils/LogUtil.java diff --git a/src/main/java/com/skyflow/common/utils/TokenUtils.java b/v1/src/main/java/com/skyflow/common/utils/TokenUtils.java similarity index 100% rename from src/main/java/com/skyflow/common/utils/TokenUtils.java rename to v1/src/main/java/com/skyflow/common/utils/TokenUtils.java diff --git a/src/main/java/com/skyflow/common/utils/Validators.java b/v1/src/main/java/com/skyflow/common/utils/Validators.java similarity index 100% rename from src/main/java/com/skyflow/common/utils/Validators.java rename to v1/src/main/java/com/skyflow/common/utils/Validators.java diff --git a/src/main/java/com/skyflow/entities/DeleteInput.java b/v1/src/main/java/com/skyflow/entities/DeleteInput.java similarity index 100% rename from src/main/java/com/skyflow/entities/DeleteInput.java rename to v1/src/main/java/com/skyflow/entities/DeleteInput.java diff --git a/src/main/java/com/skyflow/entities/DeleteOptions.java b/v1/src/main/java/com/skyflow/entities/DeleteOptions.java similarity index 100% rename from src/main/java/com/skyflow/entities/DeleteOptions.java rename to v1/src/main/java/com/skyflow/entities/DeleteOptions.java diff --git a/src/main/java/com/skyflow/entities/DeleteRecordInput.java b/v1/src/main/java/com/skyflow/entities/DeleteRecordInput.java similarity index 100% rename from src/main/java/com/skyflow/entities/DeleteRecordInput.java rename to v1/src/main/java/com/skyflow/entities/DeleteRecordInput.java diff --git a/src/main/java/com/skyflow/entities/DetokenizeInput.java b/v1/src/main/java/com/skyflow/entities/DetokenizeInput.java similarity index 100% rename from src/main/java/com/skyflow/entities/DetokenizeInput.java rename to v1/src/main/java/com/skyflow/entities/DetokenizeInput.java diff --git a/src/main/java/com/skyflow/entities/DetokenizeRecord.java b/v1/src/main/java/com/skyflow/entities/DetokenizeRecord.java similarity index 100% rename from src/main/java/com/skyflow/entities/DetokenizeRecord.java rename to v1/src/main/java/com/skyflow/entities/DetokenizeRecord.java diff --git a/src/main/java/com/skyflow/entities/GetByIdInput.java b/v1/src/main/java/com/skyflow/entities/GetByIdInput.java similarity index 100% rename from src/main/java/com/skyflow/entities/GetByIdInput.java rename to v1/src/main/java/com/skyflow/entities/GetByIdInput.java diff --git a/src/main/java/com/skyflow/entities/GetByIdRecordInput.java b/v1/src/main/java/com/skyflow/entities/GetByIdRecordInput.java similarity index 100% rename from src/main/java/com/skyflow/entities/GetByIdRecordInput.java rename to v1/src/main/java/com/skyflow/entities/GetByIdRecordInput.java diff --git a/src/main/java/com/skyflow/entities/GetInput.java b/v1/src/main/java/com/skyflow/entities/GetInput.java similarity index 100% rename from src/main/java/com/skyflow/entities/GetInput.java rename to v1/src/main/java/com/skyflow/entities/GetInput.java diff --git a/src/main/java/com/skyflow/entities/GetOptions.java b/v1/src/main/java/com/skyflow/entities/GetOptions.java similarity index 100% rename from src/main/java/com/skyflow/entities/GetOptions.java rename to v1/src/main/java/com/skyflow/entities/GetOptions.java diff --git a/src/main/java/com/skyflow/entities/GetRecordInput.java b/v1/src/main/java/com/skyflow/entities/GetRecordInput.java similarity index 100% rename from src/main/java/com/skyflow/entities/GetRecordInput.java rename to v1/src/main/java/com/skyflow/entities/GetRecordInput.java diff --git a/src/main/java/com/skyflow/entities/InsertBulkOptions.java b/v1/src/main/java/com/skyflow/entities/InsertBulkOptions.java similarity index 100% rename from src/main/java/com/skyflow/entities/InsertBulkOptions.java rename to v1/src/main/java/com/skyflow/entities/InsertBulkOptions.java diff --git a/src/main/java/com/skyflow/entities/InsertInput.java b/v1/src/main/java/com/skyflow/entities/InsertInput.java similarity index 100% rename from src/main/java/com/skyflow/entities/InsertInput.java rename to v1/src/main/java/com/skyflow/entities/InsertInput.java diff --git a/src/main/java/com/skyflow/entities/InsertOptions.java b/v1/src/main/java/com/skyflow/entities/InsertOptions.java similarity index 100% rename from src/main/java/com/skyflow/entities/InsertOptions.java rename to v1/src/main/java/com/skyflow/entities/InsertOptions.java diff --git a/src/main/java/com/skyflow/entities/InsertRecordInput.java b/v1/src/main/java/com/skyflow/entities/InsertRecordInput.java similarity index 100% rename from src/main/java/com/skyflow/entities/InsertRecordInput.java rename to v1/src/main/java/com/skyflow/entities/InsertRecordInput.java diff --git a/src/main/java/com/skyflow/entities/LogLevel.java b/v1/src/main/java/com/skyflow/entities/LogLevel.java similarity index 100% rename from src/main/java/com/skyflow/entities/LogLevel.java rename to v1/src/main/java/com/skyflow/entities/LogLevel.java diff --git a/src/main/java/com/skyflow/entities/QueryInput.java b/v1/src/main/java/com/skyflow/entities/QueryInput.java similarity index 100% rename from src/main/java/com/skyflow/entities/QueryInput.java rename to v1/src/main/java/com/skyflow/entities/QueryInput.java diff --git a/src/main/java/com/skyflow/entities/QueryOptions.java b/v1/src/main/java/com/skyflow/entities/QueryOptions.java similarity index 100% rename from src/main/java/com/skyflow/entities/QueryOptions.java rename to v1/src/main/java/com/skyflow/entities/QueryOptions.java diff --git a/src/main/java/com/skyflow/entities/QueryRecordInput.java b/v1/src/main/java/com/skyflow/entities/QueryRecordInput.java similarity index 100% rename from src/main/java/com/skyflow/entities/QueryRecordInput.java rename to v1/src/main/java/com/skyflow/entities/QueryRecordInput.java diff --git a/src/main/java/com/skyflow/entities/RedactionType.java b/v1/src/main/java/com/skyflow/entities/RedactionType.java similarity index 100% rename from src/main/java/com/skyflow/entities/RedactionType.java rename to v1/src/main/java/com/skyflow/entities/RedactionType.java diff --git a/src/main/java/com/skyflow/entities/RequestMethod.java b/v1/src/main/java/com/skyflow/entities/RequestMethod.java similarity index 100% rename from src/main/java/com/skyflow/entities/RequestMethod.java rename to v1/src/main/java/com/skyflow/entities/RequestMethod.java diff --git a/src/main/java/com/skyflow/entities/ResponseToken.java b/v1/src/main/java/com/skyflow/entities/ResponseToken.java similarity index 100% rename from src/main/java/com/skyflow/entities/ResponseToken.java rename to v1/src/main/java/com/skyflow/entities/ResponseToken.java diff --git a/src/main/java/com/skyflow/entities/SkyflowConfiguration.java b/v1/src/main/java/com/skyflow/entities/SkyflowConfiguration.java similarity index 100% rename from src/main/java/com/skyflow/entities/SkyflowConfiguration.java rename to v1/src/main/java/com/skyflow/entities/SkyflowConfiguration.java diff --git a/src/main/java/com/skyflow/entities/TokenProvider.java b/v1/src/main/java/com/skyflow/entities/TokenProvider.java similarity index 100% rename from src/main/java/com/skyflow/entities/TokenProvider.java rename to v1/src/main/java/com/skyflow/entities/TokenProvider.java diff --git a/src/main/java/com/skyflow/entities/UpdateInput.java b/v1/src/main/java/com/skyflow/entities/UpdateInput.java similarity index 100% rename from src/main/java/com/skyflow/entities/UpdateInput.java rename to v1/src/main/java/com/skyflow/entities/UpdateInput.java diff --git a/src/main/java/com/skyflow/entities/UpdateOptions.java b/v1/src/main/java/com/skyflow/entities/UpdateOptions.java similarity index 100% rename from src/main/java/com/skyflow/entities/UpdateOptions.java rename to v1/src/main/java/com/skyflow/entities/UpdateOptions.java diff --git a/src/main/java/com/skyflow/entities/UpdateRecordInput.java b/v1/src/main/java/com/skyflow/entities/UpdateRecordInput.java similarity index 100% rename from src/main/java/com/skyflow/entities/UpdateRecordInput.java rename to v1/src/main/java/com/skyflow/entities/UpdateRecordInput.java diff --git a/src/main/java/com/skyflow/entities/UpsertOption.java b/v1/src/main/java/com/skyflow/entities/UpsertOption.java similarity index 100% rename from src/main/java/com/skyflow/entities/UpsertOption.java rename to v1/src/main/java/com/skyflow/entities/UpsertOption.java diff --git a/src/main/java/com/skyflow/errors/ErrorCode.java b/v1/src/main/java/com/skyflow/errors/ErrorCode.java similarity index 100% rename from src/main/java/com/skyflow/errors/ErrorCode.java rename to v1/src/main/java/com/skyflow/errors/ErrorCode.java diff --git a/src/main/java/com/skyflow/errors/SkyflowException.java b/v1/src/main/java/com/skyflow/errors/SkyflowException.java similarity index 100% rename from src/main/java/com/skyflow/errors/SkyflowException.java rename to v1/src/main/java/com/skyflow/errors/SkyflowException.java diff --git a/src/main/java/com/skyflow/logs/DebugLogs.java b/v1/src/main/java/com/skyflow/logs/DebugLogs.java similarity index 100% rename from src/main/java/com/skyflow/logs/DebugLogs.java rename to v1/src/main/java/com/skyflow/logs/DebugLogs.java diff --git a/src/main/java/com/skyflow/logs/ErrorLogs.java b/v1/src/main/java/com/skyflow/logs/ErrorLogs.java similarity index 100% rename from src/main/java/com/skyflow/logs/ErrorLogs.java rename to v1/src/main/java/com/skyflow/logs/ErrorLogs.java diff --git a/src/main/java/com/skyflow/logs/InfoLogs.java b/v1/src/main/java/com/skyflow/logs/InfoLogs.java similarity index 100% rename from src/main/java/com/skyflow/logs/InfoLogs.java rename to v1/src/main/java/com/skyflow/logs/InfoLogs.java diff --git a/src/main/java/com/skyflow/logs/WarnLogs.java b/v1/src/main/java/com/skyflow/logs/WarnLogs.java similarity index 100% rename from src/main/java/com/skyflow/logs/WarnLogs.java rename to v1/src/main/java/com/skyflow/logs/WarnLogs.java diff --git a/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java b/v1/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java similarity index 100% rename from src/main/java/com/skyflow/serviceaccount/util/BearerToken.java rename to v1/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java diff --git a/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java b/v1/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java similarity index 100% rename from src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java rename to v1/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java diff --git a/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java b/v1/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java similarity index 100% rename from src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java rename to v1/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java diff --git a/src/main/java/com/skyflow/serviceaccount/util/Token.java b/v1/src/main/java/com/skyflow/serviceaccount/util/Token.java similarity index 100% rename from src/main/java/com/skyflow/serviceaccount/util/Token.java rename to v1/src/main/java/com/skyflow/serviceaccount/util/Token.java diff --git a/src/main/java/com/skyflow/vault/DeleteBySkyflowId.java b/v1/src/main/java/com/skyflow/vault/DeleteBySkyflowId.java similarity index 100% rename from src/main/java/com/skyflow/vault/DeleteBySkyflowId.java rename to v1/src/main/java/com/skyflow/vault/DeleteBySkyflowId.java diff --git a/src/main/java/com/skyflow/vault/Detokenize.java b/v1/src/main/java/com/skyflow/vault/Detokenize.java similarity index 100% rename from src/main/java/com/skyflow/vault/Detokenize.java rename to v1/src/main/java/com/skyflow/vault/Detokenize.java diff --git a/src/main/java/com/skyflow/vault/Get.java b/v1/src/main/java/com/skyflow/vault/Get.java similarity index 100% rename from src/main/java/com/skyflow/vault/Get.java rename to v1/src/main/java/com/skyflow/vault/Get.java diff --git a/src/main/java/com/skyflow/vault/GetBySkyflowId.java b/v1/src/main/java/com/skyflow/vault/GetBySkyflowId.java similarity index 100% rename from src/main/java/com/skyflow/vault/GetBySkyflowId.java rename to v1/src/main/java/com/skyflow/vault/GetBySkyflowId.java diff --git a/src/main/java/com/skyflow/vault/Insert.java b/v1/src/main/java/com/skyflow/vault/Insert.java similarity index 100% rename from src/main/java/com/skyflow/vault/Insert.java rename to v1/src/main/java/com/skyflow/vault/Insert.java diff --git a/src/main/java/com/skyflow/vault/Skyflow.java b/v1/src/main/java/com/skyflow/vault/Skyflow.java similarity index 100% rename from src/main/java/com/skyflow/vault/Skyflow.java rename to v1/src/main/java/com/skyflow/vault/Skyflow.java diff --git a/src/main/java/com/skyflow/vault/UpdateBySkyflowId.java b/v1/src/main/java/com/skyflow/vault/UpdateBySkyflowId.java similarity index 100% rename from src/main/java/com/skyflow/vault/UpdateBySkyflowId.java rename to v1/src/main/java/com/skyflow/vault/UpdateBySkyflowId.java diff --git a/src/test/java/com/skyflow/common/utils/HelpersTest.java b/v1/src/test/java/com/skyflow/common/utils/HelpersTest.java similarity index 100% rename from src/test/java/com/skyflow/common/utils/HelpersTest.java rename to v1/src/test/java/com/skyflow/common/utils/HelpersTest.java diff --git a/src/test/java/com/skyflow/common/utils/HttpUtilityTest.java b/v1/src/test/java/com/skyflow/common/utils/HttpUtilityTest.java similarity index 100% rename from src/test/java/com/skyflow/common/utils/HttpUtilityTest.java rename to v1/src/test/java/com/skyflow/common/utils/HttpUtilityTest.java diff --git a/src/test/java/com/skyflow/common/utils/TokenUtilsTest.java b/v1/src/test/java/com/skyflow/common/utils/TokenUtilsTest.java similarity index 100% rename from src/test/java/com/skyflow/common/utils/TokenUtilsTest.java rename to v1/src/test/java/com/skyflow/common/utils/TokenUtilsTest.java diff --git a/src/test/java/com/skyflow/common/utils/TokenUtilsValidTokenTest.java b/v1/src/test/java/com/skyflow/common/utils/TokenUtilsValidTokenTest.java similarity index 100% rename from src/test/java/com/skyflow/common/utils/TokenUtilsValidTokenTest.java rename to v1/src/test/java/com/skyflow/common/utils/TokenUtilsValidTokenTest.java diff --git a/src/test/java/com/skyflow/common/utils/ValidatorsTest.java b/v1/src/test/java/com/skyflow/common/utils/ValidatorsTest.java similarity index 100% rename from src/test/java/com/skyflow/common/utils/ValidatorsTest.java rename to v1/src/test/java/com/skyflow/common/utils/ValidatorsTest.java diff --git a/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTest.java b/v1/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTest.java similarity index 100% rename from src/test/java/com/skyflow/serviceaccount/util/BearerTokenTest.java rename to v1/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTest.java diff --git a/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokenResponseTest.java b/v1/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokenResponseTest.java similarity index 100% rename from src/test/java/com/skyflow/serviceaccount/util/SignedDataTokenResponseTest.java rename to v1/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokenResponseTest.java diff --git a/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTest.java b/v1/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTest.java similarity index 100% rename from src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTest.java rename to v1/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTest.java diff --git a/src/test/java/com/skyflow/serviceaccount/util/TokenTest.java b/v1/src/test/java/com/skyflow/serviceaccount/util/TokenTest.java similarity index 100% rename from src/test/java/com/skyflow/serviceaccount/util/TokenTest.java rename to v1/src/test/java/com/skyflow/serviceaccount/util/TokenTest.java diff --git a/src/test/java/com/skyflow/vault/DeleteMethodTest.java b/v1/src/test/java/com/skyflow/vault/DeleteMethodTest.java similarity index 100% rename from src/test/java/com/skyflow/vault/DeleteMethodTest.java rename to v1/src/test/java/com/skyflow/vault/DeleteMethodTest.java diff --git a/src/test/java/com/skyflow/vault/GetMethodTest.java b/v1/src/test/java/com/skyflow/vault/GetMethodTest.java similarity index 100% rename from src/test/java/com/skyflow/vault/GetMethodTest.java rename to v1/src/test/java/com/skyflow/vault/GetMethodTest.java diff --git a/src/test/java/com/skyflow/vault/InvokeConnectionTest.java b/v1/src/test/java/com/skyflow/vault/InvokeConnectionTest.java similarity index 100% rename from src/test/java/com/skyflow/vault/InvokeConnectionTest.java rename to v1/src/test/java/com/skyflow/vault/InvokeConnectionTest.java diff --git a/src/test/java/com/skyflow/vault/SkyflowTest.java b/v1/src/test/java/com/skyflow/vault/SkyflowTest.java similarity index 100% rename from src/test/java/com/skyflow/vault/SkyflowTest.java rename to v1/src/test/java/com/skyflow/vault/SkyflowTest.java diff --git a/src/test/resources/invalidCredentials.json b/v1/src/test/resources/invalidCredentials.json similarity index 100% rename from src/test/resources/invalidCredentials.json rename to v1/src/test/resources/invalidCredentials.json diff --git a/src/test/resources/notJson.txt b/v1/src/test/resources/notJson.txt similarity index 100% rename from src/test/resources/notJson.txt rename to v1/src/test/resources/notJson.txt diff --git a/v2/main/java/com/skyflow/client/SkyflowClient.java b/v2/main/java/com/skyflow/client/SkyflowClient.java new file mode 100644 index 00000000..70101e2d --- /dev/null +++ b/v2/main/java/com/skyflow/client/SkyflowClient.java @@ -0,0 +1,117 @@ +package com.skyflow.client; + +import com.skyflow.config.ConnectionConfig; +import com.skyflow.config.Credentials; +import com.skyflow.config.ManagementConfig; +import com.skyflow.config.VaultConfig; +import com.skyflow.management.service.ManagementService; +import com.skyflow.utils.Builder; +import com.skyflow.utils.LogLevel; +import com.skyflow.vault.controller.connections.ConnectionsController; +import com.skyflow.vault.service.VaultService; + +import java.util.ArrayList; + +public class SkyflowClient { + ArrayList vaultConfigs = new ArrayList<>(); + ArrayList connectionConfigs = new ArrayList<>(); + ArrayList managementConfigs = new ArrayList<>(); + Credentials credentials; + Builder builder; + // other members + + public SkyflowClient(VaultConfig vaultConfig, ConnectionConfig connectionConfig, ManagementConfig managementConfig, Credentials credentials) { + this.vaultConfigs.add(vaultConfig); + this.connectionConfigs.add(connectionConfig); + this.managementConfigs.add(managementConfig); + this.credentials = credentials; + } + + public Builder Builder() { + builder = new Builder(); + return builder; + } + + public Builder addVaultConfig(VaultConfig vaultConfig) { + // add vault config + return builder; + } + + public Builder removeVaultConfig(String vaultId) { + // remove vault config with vault id + return builder; + } + + public Builder updateVaultConfig(String vaultId, VaultConfig vaultConfig) { + // update vault config with vault id + return builder; + } + + public Builder addConnectionConfig(ConnectionConfig connectionConfig) { + // add connection config + return builder; + } + + public Builder removeConnectionConfig(String connectionId, ConnectionConfig connectionConfig) { + // remove connection config with connection id + return builder; + } + + public Builder updateConnectionConfig(String connectionId, ConnectionConfig connectionConfig) { + // update connection config with connection id + return builder; + } + + public Builder addManagementConfig(ManagementConfig managementConfig) { + // add management config + return builder; + } + + public Builder removeManagementConfig(String managementId, ManagementConfig managementConfig) { + // remove management config with management id + return builder; + } + + public Builder updateManagementConfig(String managementId, ManagementConfig managementConfig) { + // update management config with management id + return builder; + } + + public Builder setCredentials(Credentials credentials) { + // set credentials + return builder; + } + + public Builder logLevel(LogLevel logLevel) { + // set log level + return builder; + } + + public Builder updateLogLevel(LogLevel logLevel) { + // update log level + return builder; + } + + public SkyflowClient build() { + // return built skyflow client instance + return this; + } + + public VaultService vault(String vaultId) { + // (cache) - store the vault object in a list, don't create object if object already exits + // return vault Object using static func + return null; + } + + public ConnectionsController connection(String connectionId) { + // (cache) - store the connection object in a list, don't create object if object already exits + // return connection Object static func + return null; + } + + public ManagementService management() { + // cache management object if created + // return management object using static func + return null; + } +} diff --git a/v2/main/java/com/skyflow/config/ConnectionConfig.java b/v2/main/java/com/skyflow/config/ConnectionConfig.java new file mode 100644 index 00000000..5369b81b --- /dev/null +++ b/v2/main/java/com/skyflow/config/ConnectionConfig.java @@ -0,0 +1,11 @@ +package com.skyflow.config; + +public class ConnectionConfig { + // members + + // constructor + ConnectionConfig() { + } + + // getters ans setters +} diff --git a/v2/main/java/com/skyflow/config/Credentials.java b/v2/main/java/com/skyflow/config/Credentials.java new file mode 100644 index 00000000..44fd58fc --- /dev/null +++ b/v2/main/java/com/skyflow/config/Credentials.java @@ -0,0 +1,11 @@ +package com.skyflow.config; + +public class Credentials { + // members + + // constructor + Credentials() { + } + + // getters ans setters +} diff --git a/v2/main/java/com/skyflow/config/ManagementConfig.java b/v2/main/java/com/skyflow/config/ManagementConfig.java new file mode 100644 index 00000000..a054c8ea --- /dev/null +++ b/v2/main/java/com/skyflow/config/ManagementConfig.java @@ -0,0 +1,11 @@ +package com.skyflow.config; + +public class ManagementConfig { + // members + + // constructor + ManagementConfig() { + } + + // getters and setters +} diff --git a/v2/main/java/com/skyflow/config/VaultConfig.java b/v2/main/java/com/skyflow/config/VaultConfig.java new file mode 100644 index 00000000..c70c9850 --- /dev/null +++ b/v2/main/java/com/skyflow/config/VaultConfig.java @@ -0,0 +1,11 @@ +package com.skyflow.config; + +public class VaultConfig { + // members + + // constructor + VaultConfig() { + } + + // getters ans setters +} diff --git a/v2/main/java/com/skyflow/errors/SkyflowError.java b/v2/main/java/com/skyflow/errors/SkyflowError.java new file mode 100644 index 00000000..4b6f29a6 --- /dev/null +++ b/v2/main/java/com/skyflow/errors/SkyflowError.java @@ -0,0 +1,10 @@ +package com.skyflow.errors; + +// skyflow error class +public class SkyflowError { + // members + + // constructor + SkyflowError() { + } +} diff --git a/v2/main/java/com/skyflow/management/controller/policy/Policy.java b/v2/main/java/com/skyflow/management/controller/policy/Policy.java new file mode 100644 index 00000000..e7b27f1d --- /dev/null +++ b/v2/main/java/com/skyflow/management/controller/policy/Policy.java @@ -0,0 +1,23 @@ +package com.skyflow.management.controller.policy; + +public class Policy { + public Policy() { + } + + public static Policy initialize() { + // return policy object + return null; + } + + public Policy update() { + return null; + } + + public Policy delete() { + return null; + } + + public Policy get() { + return null; + } +} diff --git a/v2/main/java/com/skyflow/management/controller/role/Role.java b/v2/main/java/com/skyflow/management/controller/role/Role.java new file mode 100644 index 00000000..5da98b56 --- /dev/null +++ b/v2/main/java/com/skyflow/management/controller/role/Role.java @@ -0,0 +1,23 @@ +package com.skyflow.management.controller.role; + +public class Role { + public Role() { + } + + public static Role initialize() { + // return policy object + return null; + } + + public Role update() { + return null; + } + + public Role delete() { + return null; + } + + public Role get() { + return null; + } +} diff --git a/v2/main/java/com/skyflow/management/controller/vault/Vault.java b/v2/main/java/com/skyflow/management/controller/vault/Vault.java new file mode 100644 index 00000000..f1a9fea9 --- /dev/null +++ b/v2/main/java/com/skyflow/management/controller/vault/Vault.java @@ -0,0 +1,23 @@ +package com.skyflow.management.controller.vault; + +public class Vault { + public Vault() { + } + + public static Vault initialize() { + // return policy object + return null; + } + + public Vault update() { + return null; + } + + public Vault delete() { + return null; + } + + public Vault get() { + return null; + } +} diff --git a/v2/main/java/com/skyflow/management/model/request/createVault/CreateVaultRequest.java b/v2/main/java/com/skyflow/management/model/request/createVault/CreateVaultRequest.java new file mode 100644 index 00000000..dee4b447 --- /dev/null +++ b/v2/main/java/com/skyflow/management/model/request/createVault/CreateVaultRequest.java @@ -0,0 +1,10 @@ +package com.skyflow.management.model.request.createVault; + +public class CreateVaultRequest { + // members + + public CreateVaultRequest() { + } + + // getters and setters +} diff --git a/v2/main/java/com/skyflow/management/model/request/deletePolicy/DeletePolicyRequest.java b/v2/main/java/com/skyflow/management/model/request/deletePolicy/DeletePolicyRequest.java new file mode 100644 index 00000000..9a97af88 --- /dev/null +++ b/v2/main/java/com/skyflow/management/model/request/deletePolicy/DeletePolicyRequest.java @@ -0,0 +1,10 @@ +package com.skyflow.management.model.request.deletePolicy; + +public class DeletePolicyRequest { + // members + + public DeletePolicyRequest() { + } + + // getters and setters +} diff --git a/v2/main/java/com/skyflow/management/model/response/createVault/CreateVaultResponse.java b/v2/main/java/com/skyflow/management/model/response/createVault/CreateVaultResponse.java new file mode 100644 index 00000000..6d797241 --- /dev/null +++ b/v2/main/java/com/skyflow/management/model/response/createVault/CreateVaultResponse.java @@ -0,0 +1,10 @@ +package com.skyflow.management.model.response.createVault; + +public class CreateVaultResponse { + // members + + public CreateVaultResponse() { + } + + // getters and setters +} diff --git a/v2/main/java/com/skyflow/management/model/response/deletePolicy/DeletePolicyResponse.java b/v2/main/java/com/skyflow/management/model/response/deletePolicy/DeletePolicyResponse.java new file mode 100644 index 00000000..17795308 --- /dev/null +++ b/v2/main/java/com/skyflow/management/model/response/deletePolicy/DeletePolicyResponse.java @@ -0,0 +1,10 @@ +package com.skyflow.management.model.response.deletePolicy; + +public class DeletePolicyResponse { + // members + + public DeletePolicyResponse() { + } + + // getters and setters +} diff --git a/v2/main/java/com/skyflow/management/service/ManagementService.java b/v2/main/java/com/skyflow/management/service/ManagementService.java new file mode 100644 index 00000000..827eb686 --- /dev/null +++ b/v2/main/java/com/skyflow/management/service/ManagementService.java @@ -0,0 +1,46 @@ +package com.skyflow.management.service; + +public class ManagementService { + // members + + public ManagementService() { + } + + public static ManagementService initialize() { + // return management object + return null; + } + + public T createVault() { + // return vault object using static func + // cache - store the vault object in a list + return null; + } + + public T createRole() { + // return role object using static func + // cache - store the role object in a list + return null; + } + + public T createPolicy() { + // return policy object using static func + // cache - store the policy object in a list + return null; + } + + public T vault(String vaultId) { + // return vault object from the cached list + return null; + } + + public T role(String roleId) { + // return role object from the cached list + return null; + } + + public T policy(String policyId) { + // return policy object from the cached list + return null; + } +} diff --git a/v2/main/java/com/skyflow/utils/Builder.java b/v2/main/java/com/skyflow/utils/Builder.java new file mode 100644 index 00000000..5641555c --- /dev/null +++ b/v2/main/java/com/skyflow/utils/Builder.java @@ -0,0 +1,4 @@ +package com.skyflow.utils; + +public class Builder { +} diff --git a/v2/main/java/com/skyflow/utils/LogLevel.java b/v2/main/java/com/skyflow/utils/LogLevel.java new file mode 100644 index 00000000..873f8264 --- /dev/null +++ b/v2/main/java/com/skyflow/utils/LogLevel.java @@ -0,0 +1,9 @@ +package com.skyflow.utils; + +public enum LogLevel { + ERROR, + WARNING, + INFO, + DEBUG, + OFF +} diff --git a/v2/main/java/com/skyflow/utils/validations/Validations.java b/v2/main/java/com/skyflow/utils/validations/Validations.java new file mode 100644 index 00000000..600aeb10 --- /dev/null +++ b/v2/main/java/com/skyflow/utils/validations/Validations.java @@ -0,0 +1,10 @@ +package com.skyflow.utils.validations; + +// Add config and request validations +public class Validations { + public static void vaultValidations() { + } + + public static void insertValidation() { + } +} diff --git a/v2/main/java/com/skyflow/vault/controller/audit/AuditController.java b/v2/main/java/com/skyflow/vault/controller/audit/AuditController.java new file mode 100644 index 00000000..2e3af01e --- /dev/null +++ b/v2/main/java/com/skyflow/vault/controller/audit/AuditController.java @@ -0,0 +1,18 @@ +package com.skyflow.vault.controller.audit; + +import com.skyflow.vault.model.response.AuditResponse; + +public class AuditController { + public AuditController() { + } + + // return audit controller object + public static AuditController initialize() { + return null; + } + + public AuditResponse list() { + // return audit events + return null; + } +} diff --git a/v2/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java b/v2/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java new file mode 100644 index 00000000..82cbe83f --- /dev/null +++ b/v2/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java @@ -0,0 +1,18 @@ +package com.skyflow.vault.controller.binlookup; + +import com.skyflow.vault.model.response.BinLookupResponse; + +public class BinLookupController { + public BinLookupController() { + } + + // return bin lookup controller object + public static BinLookupController initialize() { + return null; + } + + public BinLookupResponse get() { + // return bin lookup response (card metadata associated with BIN) + return null; + } +} diff --git a/v2/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java b/v2/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java new file mode 100644 index 00000000..40824383 --- /dev/null +++ b/v2/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java @@ -0,0 +1,18 @@ +package com.skyflow.vault.controller.connections; + +import com.skyflow.vault.model.response.ConnectionResponse; + +public class ConnectionsController { + public ConnectionsController() { + } + + // return connections controller object + public static ConnectionsController initialize() { + return null; + } + + public ConnectionResponse invoke() { + // invoke the connection + return null; + } +} diff --git a/v2/main/java/com/skyflow/vault/controller/detect/DetectController.java b/v2/main/java/com/skyflow/vault/controller/detect/DetectController.java new file mode 100644 index 00000000..02e7920c --- /dev/null +++ b/v2/main/java/com/skyflow/vault/controller/detect/DetectController.java @@ -0,0 +1,28 @@ +package com.skyflow.vault.controller.detect; + +import com.skyflow.vault.model.response.DetectResponse; + +public class DetectController { + public DetectController() { + } + + // return detect controller object + public static DetectController initialize() { + return null; + } + + public DetectResponse deIdentify() { + // return detect response + return null; + } + + public DetectResponse text() { + // return detect response + return null; + } + + public DetectResponse file() { + // return detect response + return null; + } +} diff --git a/v2/main/java/com/skyflow/vault/model/request/AuditRequest.java b/v2/main/java/com/skyflow/vault/model/request/AuditRequest.java new file mode 100644 index 00000000..d3b8ccff --- /dev/null +++ b/v2/main/java/com/skyflow/vault/model/request/AuditRequest.java @@ -0,0 +1,11 @@ +package com.skyflow.vault.model.request; + +public class AuditRequest { + // members + + // constructor + public AuditRequest() { + } + + // getters ans setters +} diff --git a/v2/main/java/com/skyflow/vault/model/request/DetokenizeRequest.java b/v2/main/java/com/skyflow/vault/model/request/DetokenizeRequest.java new file mode 100644 index 00000000..ae440ed9 --- /dev/null +++ b/v2/main/java/com/skyflow/vault/model/request/DetokenizeRequest.java @@ -0,0 +1,11 @@ +package com.skyflow.vault.model.request; + +public class DetokenizeRequest { + // members + + // constructor + public DetokenizeRequest() { + } + + // getters ans setters +} diff --git a/v2/main/java/com/skyflow/vault/model/request/InsertRequest.java b/v2/main/java/com/skyflow/vault/model/request/InsertRequest.java new file mode 100644 index 00000000..77380111 --- /dev/null +++ b/v2/main/java/com/skyflow/vault/model/request/InsertRequest.java @@ -0,0 +1,11 @@ +package com.skyflow.vault.model.request; + +public class InsertRequest { + // members + + // constructor + public InsertRequest() { + } + + // getters ans setters +} diff --git a/v2/main/java/com/skyflow/vault/model/response/AuditResponse.java b/v2/main/java/com/skyflow/vault/model/response/AuditResponse.java new file mode 100644 index 00000000..83da593b --- /dev/null +++ b/v2/main/java/com/skyflow/vault/model/response/AuditResponse.java @@ -0,0 +1,10 @@ +package com.skyflow.vault.model.response; + +public class AuditResponse { + // members + + public AuditResponse() { + } + + // getters ans setters +} diff --git a/v2/main/java/com/skyflow/vault/model/response/BinLookupResponse.java b/v2/main/java/com/skyflow/vault/model/response/BinLookupResponse.java new file mode 100644 index 00000000..81a0b515 --- /dev/null +++ b/v2/main/java/com/skyflow/vault/model/response/BinLookupResponse.java @@ -0,0 +1,10 @@ +package com.skyflow.vault.model.response; + +public class BinLookupResponse { + // members + + public BinLookupResponse() { + } + + // getters ans setters +} diff --git a/v2/main/java/com/skyflow/vault/model/response/ConnectionResponse.java b/v2/main/java/com/skyflow/vault/model/response/ConnectionResponse.java new file mode 100644 index 00000000..283f6da8 --- /dev/null +++ b/v2/main/java/com/skyflow/vault/model/response/ConnectionResponse.java @@ -0,0 +1,10 @@ +package com.skyflow.vault.model.response; + +public class ConnectionResponse { + // members + + public ConnectionResponse() { + } + + // getters ans setters +} diff --git a/v2/main/java/com/skyflow/vault/model/response/DetectResponse.java b/v2/main/java/com/skyflow/vault/model/response/DetectResponse.java new file mode 100644 index 00000000..995a852f --- /dev/null +++ b/v2/main/java/com/skyflow/vault/model/response/DetectResponse.java @@ -0,0 +1,10 @@ +package com.skyflow.vault.model.response; + +public class DetectResponse { + // members + + public DetectResponse() { + } + + // getters ans setters +} diff --git a/v2/main/java/com/skyflow/vault/model/response/DetokenizeResponse.java b/v2/main/java/com/skyflow/vault/model/response/DetokenizeResponse.java new file mode 100644 index 00000000..517dc9a6 --- /dev/null +++ b/v2/main/java/com/skyflow/vault/model/response/DetokenizeResponse.java @@ -0,0 +1,10 @@ +package com.skyflow.vault.model.response; + +public class DetokenizeResponse { + // members + + public DetokenizeResponse() { + } + + // getters ans setters +} diff --git a/v2/main/java/com/skyflow/vault/model/response/InsertResponse.java b/v2/main/java/com/skyflow/vault/model/response/InsertResponse.java new file mode 100644 index 00000000..04fff389 --- /dev/null +++ b/v2/main/java/com/skyflow/vault/model/response/InsertResponse.java @@ -0,0 +1,10 @@ +package com.skyflow.vault.model.response; + +public class InsertResponse { + // members + + public InsertResponse() { + } + + // getters ans setters +} diff --git a/v2/main/java/com/skyflow/vault/service/VaultService.java b/v2/main/java/com/skyflow/vault/service/VaultService.java new file mode 100644 index 00000000..8b867f47 --- /dev/null +++ b/v2/main/java/com/skyflow/vault/service/VaultService.java @@ -0,0 +1,61 @@ +package com.skyflow.vault.service; + +public class VaultService { + // members + + public VaultService() { + } + + public static T initialize() { + // return vault service object + return T; + } + + + public T insert() { + return T; + } + + public T detokenize() { + return T; + } + + public T get() { + return T; + } + + public T update() { + return T; + } + + public T delete() { + return T; + } + + public T uploadFile() { + return T; + + } + + public T query() { + return T; + } + + public T lookUpBin() { + // cache bin lookup object if created + // return bin lookup object using static func + return T; + } + + public T audit() { + // cache audit object if created + // return audit object using static func + return T; + } + + public T detect() { + // cache detect object if created + // return detect object using static func + return T; + } +} From f44be854b1a454003918661ae7e955bb0dcc86ba Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 17 Sep 2024 21:31:51 +0530 Subject: [PATCH 002/126] SK-1663 Worked on feedback for scaffolding --- .../{SkyflowClient.java => Skyflow.java} | 76 +++++++++++-------- .../management/ManagementController.java | 46 +++++++++++ .../controller/audit/AuditController.java | 5 +- .../binlookup/BinLookupController.java | 4 +- .../connections/ConnectionsController.java | 5 +- .../controller/detect/DetectController.java | 11 +-- .../controller/vault/VaultController.java | 64 ++++++++++++++++ ...uditRequest.java => ListEventRequest.java} | 4 +- ...nResponse.java => DeIdentifyResponse.java} | 4 +- ...etectResponse.java => GetBinResponse.java} | 4 +- ...nse.java => InvokeConnectionResponse.java} | 4 +- ...itResponse.java => ListEventResponse.java} | 4 +- .../skyflow/vault/service/VaultService.java | 7 +- 13 files changed, 185 insertions(+), 53 deletions(-) rename v2/main/java/com/skyflow/client/{SkyflowClient.java => Skyflow.java} (59%) create mode 100644 v2/main/java/com/skyflow/management/controller/management/ManagementController.java create mode 100644 v2/main/java/com/skyflow/vault/controller/vault/VaultController.java rename v2/main/java/com/skyflow/vault/model/request/{AuditRequest.java => ListEventRequest.java} (65%) rename v2/main/java/com/skyflow/vault/model/response/{ConnectionResponse.java => DeIdentifyResponse.java} (59%) rename v2/main/java/com/skyflow/vault/model/response/{DetectResponse.java => GetBinResponse.java} (62%) rename v2/main/java/com/skyflow/vault/model/response/{BinLookupResponse.java => InvokeConnectionResponse.java} (55%) rename v2/main/java/com/skyflow/vault/model/response/{AuditResponse.java => ListEventResponse.java} (60%) diff --git a/v2/main/java/com/skyflow/client/SkyflowClient.java b/v2/main/java/com/skyflow/client/Skyflow.java similarity index 59% rename from v2/main/java/com/skyflow/client/SkyflowClient.java rename to v2/main/java/com/skyflow/client/Skyflow.java index 70101e2d..abc0504d 100644 --- a/v2/main/java/com/skyflow/client/SkyflowClient.java +++ b/v2/main/java/com/skyflow/client/Skyflow.java @@ -4,27 +4,18 @@ import com.skyflow.config.Credentials; import com.skyflow.config.ManagementConfig; import com.skyflow.config.VaultConfig; -import com.skyflow.management.service.ManagementService; +import com.skyflow.management.controller.management.ManagementController; import com.skyflow.utils.Builder; import com.skyflow.utils.LogLevel; import com.skyflow.vault.controller.connections.ConnectionsController; -import com.skyflow.vault.service.VaultService; +import com.skyflow.vault.controller.vault.VaultController; -import java.util.ArrayList; - -public class SkyflowClient { - ArrayList vaultConfigs = new ArrayList<>(); - ArrayList connectionConfigs = new ArrayList<>(); - ArrayList managementConfigs = new ArrayList<>(); - Credentials credentials; +public class Skyflow { Builder builder; // other members - public SkyflowClient(VaultConfig vaultConfig, ConnectionConfig connectionConfig, ManagementConfig managementConfig, Credentials credentials) { - this.vaultConfigs.add(vaultConfig); - this.connectionConfigs.add(connectionConfig); - this.managementConfigs.add(managementConfig); - this.credentials = credentials; + public Skyflow(VaultConfig vaultConfig, ConnectionConfig connectionConfig, ManagementConfig managementConfig, Credentials credentials) { + // set members accordingly } public Builder Builder() { @@ -37,67 +28,92 @@ public Builder addVaultConfig(VaultConfig vaultConfig) { return builder; } - public Builder removeVaultConfig(String vaultId) { - // remove vault config with vault id - return builder; + public VaultConfig getVaultConfig(String vaultId) { + // get vault config with vault id + return null; } - public Builder updateVaultConfig(String vaultId, VaultConfig vaultConfig) { + public Builder updateVaultConfig(VaultConfig vaultConfig) { // update vault config with vault id return builder; } + public Builder removeVaultConfig(String vaultId) { + // remove vault config with vault id + return builder; + } + public Builder addConnectionConfig(ConnectionConfig connectionConfig) { // add connection config return builder; } - public Builder removeConnectionConfig(String connectionId, ConnectionConfig connectionConfig) { - // remove connection config with connection id - return builder; + public ConnectionConfig getConnectionConfig(String connectionId) { + // get connection config with connection id + return null; } - public Builder updateConnectionConfig(String connectionId, ConnectionConfig connectionConfig) { + public Builder updateConnectionConfig(ConnectionConfig connectionConfig) { // update connection config with connection id return builder; } + public Builder removeConnectionConfig(String connectionId) { + // remove connection config with connection id + return builder; + } + public Builder addManagementConfig(ManagementConfig managementConfig) { // add management config return builder; } - public Builder removeManagementConfig(String managementId, ManagementConfig managementConfig) { + public ManagementConfig getManagementConfig(String managementId) { + // get management config with management id + return null; + } + + public Builder updateManagementConfig(ManagementConfig managementConfig) { + // update management config with management id + return builder; + } + + public Builder removeManagementConfig(String managementId) { // remove management config with management id return builder; } - public Builder updateManagementConfig(String managementId, ManagementConfig managementConfig) { - // update management config with management id + public Builder addSkyflowCredentials(Credentials credentials) { + // set credentials return builder; } - public Builder setCredentials(Credentials credentials) { + public Builder updateSkyflowCredentials(Credentials credentials) { // set credentials return builder; } - public Builder logLevel(LogLevel logLevel) { + public Builder setLogLevel(LogLevel logLevel) { // set log level return builder; } + public LogLevel getLogLevel() { + // get log level + return null; + } + public Builder updateLogLevel(LogLevel logLevel) { // update log level return builder; } - public SkyflowClient build() { + public Skyflow build() { // return built skyflow client instance return this; } - public VaultService vault(String vaultId) { + public VaultController vault(String vaultId) { // (cache) - store the vault object in a list, don't create object if object already exits // return vault Object using static func return null; @@ -109,7 +125,7 @@ public ConnectionsController connection(String connectionId) { return null; } - public ManagementService management() { + public ManagementController management() { // cache management object if created // return management object using static func return null; diff --git a/v2/main/java/com/skyflow/management/controller/management/ManagementController.java b/v2/main/java/com/skyflow/management/controller/management/ManagementController.java new file mode 100644 index 00000000..d397954f --- /dev/null +++ b/v2/main/java/com/skyflow/management/controller/management/ManagementController.java @@ -0,0 +1,46 @@ +package com.skyflow.management.controller.management; + +public class ManagementController { + // members + + public ManagementController() { + } + + public static ManagementController initialize() { + // return management object + return null; + } + + public T createVault() { + // return vault object using static func + // cache - store the vault object in a list + return null; + } + + public T createRole() { + // return role object using static func + // cache - store the role object in a list + return null; + } + + public T createPolicy() { + // return policy object using static func + // cache - store the policy object in a list + return null; + } + + public T vault(String vaultId) { + // return vault object from the cached list + return null; + } + + public T role(String roleId) { + // return role object from the cached list + return null; + } + + public T policy(String policyId) { + // return policy object from the cached list + return null; + } +} diff --git a/v2/main/java/com/skyflow/vault/controller/audit/AuditController.java b/v2/main/java/com/skyflow/vault/controller/audit/AuditController.java index 2e3af01e..0c2165e8 100644 --- a/v2/main/java/com/skyflow/vault/controller/audit/AuditController.java +++ b/v2/main/java/com/skyflow/vault/controller/audit/AuditController.java @@ -1,6 +1,6 @@ package com.skyflow.vault.controller.audit; -import com.skyflow.vault.model.response.AuditResponse; +import com.skyflow.vault.model.response.ListEventResponse; public class AuditController { public AuditController() { @@ -11,7 +11,8 @@ public static AuditController initialize() { return null; } - public AuditResponse list() { + // Check for correct return type in python interfaces + public ListEventResponse list() { // return audit events return null; } diff --git a/v2/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java b/v2/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java index 82cbe83f..2a3c2df6 100644 --- a/v2/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java +++ b/v2/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java @@ -1,6 +1,6 @@ package com.skyflow.vault.controller.binlookup; -import com.skyflow.vault.model.response.BinLookupResponse; +import com.skyflow.vault.model.response.GetBinResponse; public class BinLookupController { public BinLookupController() { @@ -11,7 +11,7 @@ public static BinLookupController initialize() { return null; } - public BinLookupResponse get() { + public GetBinResponse get() { // return bin lookup response (card metadata associated with BIN) return null; } diff --git a/v2/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java b/v2/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java index 40824383..bfece96d 100644 --- a/v2/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java +++ b/v2/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java @@ -1,6 +1,6 @@ package com.skyflow.vault.controller.connections; -import com.skyflow.vault.model.response.ConnectionResponse; +import com.skyflow.vault.model.response.InvokeConnectionResponse; public class ConnectionsController { public ConnectionsController() { @@ -11,7 +11,8 @@ public static ConnectionsController initialize() { return null; } - public ConnectionResponse invoke() { + // check in python interfaces + public InvokeConnectionResponse invoke() { // invoke the connection return null; } diff --git a/v2/main/java/com/skyflow/vault/controller/detect/DetectController.java b/v2/main/java/com/skyflow/vault/controller/detect/DetectController.java index 02e7920c..6e02be62 100644 --- a/v2/main/java/com/skyflow/vault/controller/detect/DetectController.java +++ b/v2/main/java/com/skyflow/vault/controller/detect/DetectController.java @@ -1,6 +1,6 @@ package com.skyflow.vault.controller.detect; -import com.skyflow.vault.model.response.DetectResponse; +import com.skyflow.vault.model.response.DeIdentifyResponse; public class DetectController { public DetectController() { @@ -11,17 +11,18 @@ public static DetectController initialize() { return null; } - public DetectResponse deIdentify() { - // return detect response + // should return detect controller + public DetectController deIdentify() { + // return detect controller return null; } - public DetectResponse text() { + public DeIdentifyResponse text() { // return detect response return null; } - public DetectResponse file() { + public DeIdentifyResponse file() { // return detect response return null; } diff --git a/v2/main/java/com/skyflow/vault/controller/vault/VaultController.java b/v2/main/java/com/skyflow/vault/controller/vault/VaultController.java new file mode 100644 index 00000000..0f5389fd --- /dev/null +++ b/v2/main/java/com/skyflow/vault/controller/vault/VaultController.java @@ -0,0 +1,64 @@ +package com.skyflow.vault.controller.vault; + +public class VaultController { + // members + + public VaultController() { + } + + public static T initialize() { + // return vault service object + return T; + } + + public T insert() { + return T; + } + + public T detokenize() { + return T; + } + + public T get() { + return T; + } + + public T update() { + return T; + } + + public T delete() { + return T; + } + + public T uploadFile() { + return T; + + } + + public T query() { + return T; + } + + public T tokenize() { + return T; + } + + public T lookUpBin() { + // cache bin lookup object if created + // return bin lookup object using static func + return T; + } + + public T audit() { + // cache audit object if created + // return audit object using static func + return T; + } + + public T detect() { + // cache detect object if created + // return detect object using static func + return T; + } +} diff --git a/v2/main/java/com/skyflow/vault/model/request/AuditRequest.java b/v2/main/java/com/skyflow/vault/model/request/ListEventRequest.java similarity index 65% rename from v2/main/java/com/skyflow/vault/model/request/AuditRequest.java rename to v2/main/java/com/skyflow/vault/model/request/ListEventRequest.java index d3b8ccff..3f0f7349 100644 --- a/v2/main/java/com/skyflow/vault/model/request/AuditRequest.java +++ b/v2/main/java/com/skyflow/vault/model/request/ListEventRequest.java @@ -1,10 +1,10 @@ package com.skyflow.vault.model.request; -public class AuditRequest { +public class ListEventRequest { // members // constructor - public AuditRequest() { + public ListEventRequest() { } // getters ans setters diff --git a/v2/main/java/com/skyflow/vault/model/response/ConnectionResponse.java b/v2/main/java/com/skyflow/vault/model/response/DeIdentifyResponse.java similarity index 59% rename from v2/main/java/com/skyflow/vault/model/response/ConnectionResponse.java rename to v2/main/java/com/skyflow/vault/model/response/DeIdentifyResponse.java index 283f6da8..4e8c2c58 100644 --- a/v2/main/java/com/skyflow/vault/model/response/ConnectionResponse.java +++ b/v2/main/java/com/skyflow/vault/model/response/DeIdentifyResponse.java @@ -1,9 +1,9 @@ package com.skyflow.vault.model.response; -public class ConnectionResponse { +public class DeIdentifyResponse { // members - public ConnectionResponse() { + public DeIdentifyResponse() { } // getters ans setters diff --git a/v2/main/java/com/skyflow/vault/model/response/DetectResponse.java b/v2/main/java/com/skyflow/vault/model/response/GetBinResponse.java similarity index 62% rename from v2/main/java/com/skyflow/vault/model/response/DetectResponse.java rename to v2/main/java/com/skyflow/vault/model/response/GetBinResponse.java index 995a852f..000280c7 100644 --- a/v2/main/java/com/skyflow/vault/model/response/DetectResponse.java +++ b/v2/main/java/com/skyflow/vault/model/response/GetBinResponse.java @@ -1,9 +1,9 @@ package com.skyflow.vault.model.response; -public class DetectResponse { +public class GetBinResponse { // members - public DetectResponse() { + public GetBinResponse() { } // getters ans setters diff --git a/v2/main/java/com/skyflow/vault/model/response/BinLookupResponse.java b/v2/main/java/com/skyflow/vault/model/response/InvokeConnectionResponse.java similarity index 55% rename from v2/main/java/com/skyflow/vault/model/response/BinLookupResponse.java rename to v2/main/java/com/skyflow/vault/model/response/InvokeConnectionResponse.java index 81a0b515..155cff66 100644 --- a/v2/main/java/com/skyflow/vault/model/response/BinLookupResponse.java +++ b/v2/main/java/com/skyflow/vault/model/response/InvokeConnectionResponse.java @@ -1,9 +1,9 @@ package com.skyflow.vault.model.response; -public class BinLookupResponse { +public class InvokeConnectionResponse { // members - public BinLookupResponse() { + public InvokeConnectionResponse() { } // getters ans setters diff --git a/v2/main/java/com/skyflow/vault/model/response/AuditResponse.java b/v2/main/java/com/skyflow/vault/model/response/ListEventResponse.java similarity index 60% rename from v2/main/java/com/skyflow/vault/model/response/AuditResponse.java rename to v2/main/java/com/skyflow/vault/model/response/ListEventResponse.java index 83da593b..5bb7d631 100644 --- a/v2/main/java/com/skyflow/vault/model/response/AuditResponse.java +++ b/v2/main/java/com/skyflow/vault/model/response/ListEventResponse.java @@ -1,9 +1,9 @@ package com.skyflow.vault.model.response; -public class AuditResponse { +public class ListEventResponse { // members - public AuditResponse() { + public ListEventResponse() { } // getters ans setters diff --git a/v2/main/java/com/skyflow/vault/service/VaultService.java b/v2/main/java/com/skyflow/vault/service/VaultService.java index 8b867f47..88ba344b 100644 --- a/v2/main/java/com/skyflow/vault/service/VaultService.java +++ b/v2/main/java/com/skyflow/vault/service/VaultService.java @@ -2,7 +2,7 @@ public class VaultService { // members - + public VaultService() { } @@ -11,7 +11,6 @@ public static T initialize() { return T; } - public T insert() { return T; } @@ -41,6 +40,10 @@ public T query() { return T; } + public T tokenize() { + return T; + } + public T lookUpBin() { // cache bin lookup object if created // return bin lookup object using static func From f9df247a058a14acfe191b73a44aeebcb05bba2a Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 18 Sep 2024 11:10:37 +0530 Subject: [PATCH 003/126] SK-1663 Moved main dir to src dir --- v2/{ => src}/main/java/com/skyflow/client/Skyflow.java | 0 v2/{ => src}/main/java/com/skyflow/config/ConnectionConfig.java | 0 v2/{ => src}/main/java/com/skyflow/config/Credentials.java | 0 v2/{ => src}/main/java/com/skyflow/config/ManagementConfig.java | 0 v2/{ => src}/main/java/com/skyflow/config/VaultConfig.java | 0 v2/{ => src}/main/java/com/skyflow/errors/SkyflowError.java | 0 .../management/controller/management/ManagementController.java | 0 .../java/com/skyflow/management/controller/policy/Policy.java | 0 .../main/java/com/skyflow/management/controller/role/Role.java | 0 .../main/java/com/skyflow/management/controller/vault/Vault.java | 0 .../management/model/request/createVault/CreateVaultRequest.java | 0 .../model/request/deletePolicy/DeletePolicyRequest.java | 0 .../model/response/createVault/CreateVaultResponse.java | 0 .../model/response/deletePolicy/DeletePolicyResponse.java | 0 .../java/com/skyflow/management/service/ManagementService.java | 0 v2/{ => src}/main/java/com/skyflow/utils/Builder.java | 0 v2/{ => src}/main/java/com/skyflow/utils/LogLevel.java | 0 .../main/java/com/skyflow/utils/validations/Validations.java | 0 .../java/com/skyflow/vault/controller/audit/AuditController.java | 0 .../skyflow/vault/controller/binlookup/BinLookupController.java | 0 .../vault/controller/connections/ConnectionsController.java | 0 .../com/skyflow/vault/controller/detect/DetectController.java | 0 .../java/com/skyflow/vault/controller/vault/VaultController.java | 0 .../java/com/skyflow/vault/model/request/DetokenizeRequest.java | 0 .../main/java/com/skyflow/vault/model/request/InsertRequest.java | 0 .../java/com/skyflow/vault/model/request/ListEventRequest.java | 0 .../java/com/skyflow/vault/model/response/DeIdentifyResponse.java | 0 .../java/com/skyflow/vault/model/response/DetokenizeResponse.java | 0 .../java/com/skyflow/vault/model/response/GetBinResponse.java | 0 .../java/com/skyflow/vault/model/response/InsertResponse.java | 0 .../skyflow/vault/model/response/InvokeConnectionResponse.java | 0 .../java/com/skyflow/vault/model/response/ListEventResponse.java | 0 .../main/java/com/skyflow/vault/service/VaultService.java | 0 33 files changed, 0 insertions(+), 0 deletions(-) rename v2/{ => src}/main/java/com/skyflow/client/Skyflow.java (100%) rename v2/{ => src}/main/java/com/skyflow/config/ConnectionConfig.java (100%) rename v2/{ => src}/main/java/com/skyflow/config/Credentials.java (100%) rename v2/{ => src}/main/java/com/skyflow/config/ManagementConfig.java (100%) rename v2/{ => src}/main/java/com/skyflow/config/VaultConfig.java (100%) rename v2/{ => src}/main/java/com/skyflow/errors/SkyflowError.java (100%) rename v2/{ => src}/main/java/com/skyflow/management/controller/management/ManagementController.java (100%) rename v2/{ => src}/main/java/com/skyflow/management/controller/policy/Policy.java (100%) rename v2/{ => src}/main/java/com/skyflow/management/controller/role/Role.java (100%) rename v2/{ => src}/main/java/com/skyflow/management/controller/vault/Vault.java (100%) rename v2/{ => src}/main/java/com/skyflow/management/model/request/createVault/CreateVaultRequest.java (100%) rename v2/{ => src}/main/java/com/skyflow/management/model/request/deletePolicy/DeletePolicyRequest.java (100%) rename v2/{ => src}/main/java/com/skyflow/management/model/response/createVault/CreateVaultResponse.java (100%) rename v2/{ => src}/main/java/com/skyflow/management/model/response/deletePolicy/DeletePolicyResponse.java (100%) rename v2/{ => src}/main/java/com/skyflow/management/service/ManagementService.java (100%) rename v2/{ => src}/main/java/com/skyflow/utils/Builder.java (100%) rename v2/{ => src}/main/java/com/skyflow/utils/LogLevel.java (100%) rename v2/{ => src}/main/java/com/skyflow/utils/validations/Validations.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/controller/audit/AuditController.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/controller/detect/DetectController.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/controller/vault/VaultController.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/model/request/DetokenizeRequest.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/model/request/InsertRequest.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/model/request/ListEventRequest.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/model/response/DeIdentifyResponse.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/model/response/DetokenizeResponse.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/model/response/GetBinResponse.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/model/response/InsertResponse.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/model/response/InvokeConnectionResponse.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/model/response/ListEventResponse.java (100%) rename v2/{ => src}/main/java/com/skyflow/vault/service/VaultService.java (100%) diff --git a/v2/main/java/com/skyflow/client/Skyflow.java b/v2/src/main/java/com/skyflow/client/Skyflow.java similarity index 100% rename from v2/main/java/com/skyflow/client/Skyflow.java rename to v2/src/main/java/com/skyflow/client/Skyflow.java diff --git a/v2/main/java/com/skyflow/config/ConnectionConfig.java b/v2/src/main/java/com/skyflow/config/ConnectionConfig.java similarity index 100% rename from v2/main/java/com/skyflow/config/ConnectionConfig.java rename to v2/src/main/java/com/skyflow/config/ConnectionConfig.java diff --git a/v2/main/java/com/skyflow/config/Credentials.java b/v2/src/main/java/com/skyflow/config/Credentials.java similarity index 100% rename from v2/main/java/com/skyflow/config/Credentials.java rename to v2/src/main/java/com/skyflow/config/Credentials.java diff --git a/v2/main/java/com/skyflow/config/ManagementConfig.java b/v2/src/main/java/com/skyflow/config/ManagementConfig.java similarity index 100% rename from v2/main/java/com/skyflow/config/ManagementConfig.java rename to v2/src/main/java/com/skyflow/config/ManagementConfig.java diff --git a/v2/main/java/com/skyflow/config/VaultConfig.java b/v2/src/main/java/com/skyflow/config/VaultConfig.java similarity index 100% rename from v2/main/java/com/skyflow/config/VaultConfig.java rename to v2/src/main/java/com/skyflow/config/VaultConfig.java diff --git a/v2/main/java/com/skyflow/errors/SkyflowError.java b/v2/src/main/java/com/skyflow/errors/SkyflowError.java similarity index 100% rename from v2/main/java/com/skyflow/errors/SkyflowError.java rename to v2/src/main/java/com/skyflow/errors/SkyflowError.java diff --git a/v2/main/java/com/skyflow/management/controller/management/ManagementController.java b/v2/src/main/java/com/skyflow/management/controller/management/ManagementController.java similarity index 100% rename from v2/main/java/com/skyflow/management/controller/management/ManagementController.java rename to v2/src/main/java/com/skyflow/management/controller/management/ManagementController.java diff --git a/v2/main/java/com/skyflow/management/controller/policy/Policy.java b/v2/src/main/java/com/skyflow/management/controller/policy/Policy.java similarity index 100% rename from v2/main/java/com/skyflow/management/controller/policy/Policy.java rename to v2/src/main/java/com/skyflow/management/controller/policy/Policy.java diff --git a/v2/main/java/com/skyflow/management/controller/role/Role.java b/v2/src/main/java/com/skyflow/management/controller/role/Role.java similarity index 100% rename from v2/main/java/com/skyflow/management/controller/role/Role.java rename to v2/src/main/java/com/skyflow/management/controller/role/Role.java diff --git a/v2/main/java/com/skyflow/management/controller/vault/Vault.java b/v2/src/main/java/com/skyflow/management/controller/vault/Vault.java similarity index 100% rename from v2/main/java/com/skyflow/management/controller/vault/Vault.java rename to v2/src/main/java/com/skyflow/management/controller/vault/Vault.java diff --git a/v2/main/java/com/skyflow/management/model/request/createVault/CreateVaultRequest.java b/v2/src/main/java/com/skyflow/management/model/request/createVault/CreateVaultRequest.java similarity index 100% rename from v2/main/java/com/skyflow/management/model/request/createVault/CreateVaultRequest.java rename to v2/src/main/java/com/skyflow/management/model/request/createVault/CreateVaultRequest.java diff --git a/v2/main/java/com/skyflow/management/model/request/deletePolicy/DeletePolicyRequest.java b/v2/src/main/java/com/skyflow/management/model/request/deletePolicy/DeletePolicyRequest.java similarity index 100% rename from v2/main/java/com/skyflow/management/model/request/deletePolicy/DeletePolicyRequest.java rename to v2/src/main/java/com/skyflow/management/model/request/deletePolicy/DeletePolicyRequest.java diff --git a/v2/main/java/com/skyflow/management/model/response/createVault/CreateVaultResponse.java b/v2/src/main/java/com/skyflow/management/model/response/createVault/CreateVaultResponse.java similarity index 100% rename from v2/main/java/com/skyflow/management/model/response/createVault/CreateVaultResponse.java rename to v2/src/main/java/com/skyflow/management/model/response/createVault/CreateVaultResponse.java diff --git a/v2/main/java/com/skyflow/management/model/response/deletePolicy/DeletePolicyResponse.java b/v2/src/main/java/com/skyflow/management/model/response/deletePolicy/DeletePolicyResponse.java similarity index 100% rename from v2/main/java/com/skyflow/management/model/response/deletePolicy/DeletePolicyResponse.java rename to v2/src/main/java/com/skyflow/management/model/response/deletePolicy/DeletePolicyResponse.java diff --git a/v2/main/java/com/skyflow/management/service/ManagementService.java b/v2/src/main/java/com/skyflow/management/service/ManagementService.java similarity index 100% rename from v2/main/java/com/skyflow/management/service/ManagementService.java rename to v2/src/main/java/com/skyflow/management/service/ManagementService.java diff --git a/v2/main/java/com/skyflow/utils/Builder.java b/v2/src/main/java/com/skyflow/utils/Builder.java similarity index 100% rename from v2/main/java/com/skyflow/utils/Builder.java rename to v2/src/main/java/com/skyflow/utils/Builder.java diff --git a/v2/main/java/com/skyflow/utils/LogLevel.java b/v2/src/main/java/com/skyflow/utils/LogLevel.java similarity index 100% rename from v2/main/java/com/skyflow/utils/LogLevel.java rename to v2/src/main/java/com/skyflow/utils/LogLevel.java diff --git a/v2/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java similarity index 100% rename from v2/main/java/com/skyflow/utils/validations/Validations.java rename to v2/src/main/java/com/skyflow/utils/validations/Validations.java diff --git a/v2/main/java/com/skyflow/vault/controller/audit/AuditController.java b/v2/src/main/java/com/skyflow/vault/controller/audit/AuditController.java similarity index 100% rename from v2/main/java/com/skyflow/vault/controller/audit/AuditController.java rename to v2/src/main/java/com/skyflow/vault/controller/audit/AuditController.java diff --git a/v2/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java b/v2/src/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java similarity index 100% rename from v2/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java rename to v2/src/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java diff --git a/v2/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java b/v2/src/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java similarity index 100% rename from v2/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java rename to v2/src/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java diff --git a/v2/main/java/com/skyflow/vault/controller/detect/DetectController.java b/v2/src/main/java/com/skyflow/vault/controller/detect/DetectController.java similarity index 100% rename from v2/main/java/com/skyflow/vault/controller/detect/DetectController.java rename to v2/src/main/java/com/skyflow/vault/controller/detect/DetectController.java diff --git a/v2/main/java/com/skyflow/vault/controller/vault/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/vault/VaultController.java similarity index 100% rename from v2/main/java/com/skyflow/vault/controller/vault/VaultController.java rename to v2/src/main/java/com/skyflow/vault/controller/vault/VaultController.java diff --git a/v2/main/java/com/skyflow/vault/model/request/DetokenizeRequest.java b/v2/src/main/java/com/skyflow/vault/model/request/DetokenizeRequest.java similarity index 100% rename from v2/main/java/com/skyflow/vault/model/request/DetokenizeRequest.java rename to v2/src/main/java/com/skyflow/vault/model/request/DetokenizeRequest.java diff --git a/v2/main/java/com/skyflow/vault/model/request/InsertRequest.java b/v2/src/main/java/com/skyflow/vault/model/request/InsertRequest.java similarity index 100% rename from v2/main/java/com/skyflow/vault/model/request/InsertRequest.java rename to v2/src/main/java/com/skyflow/vault/model/request/InsertRequest.java diff --git a/v2/main/java/com/skyflow/vault/model/request/ListEventRequest.java b/v2/src/main/java/com/skyflow/vault/model/request/ListEventRequest.java similarity index 100% rename from v2/main/java/com/skyflow/vault/model/request/ListEventRequest.java rename to v2/src/main/java/com/skyflow/vault/model/request/ListEventRequest.java diff --git a/v2/main/java/com/skyflow/vault/model/response/DeIdentifyResponse.java b/v2/src/main/java/com/skyflow/vault/model/response/DeIdentifyResponse.java similarity index 100% rename from v2/main/java/com/skyflow/vault/model/response/DeIdentifyResponse.java rename to v2/src/main/java/com/skyflow/vault/model/response/DeIdentifyResponse.java diff --git a/v2/main/java/com/skyflow/vault/model/response/DetokenizeResponse.java b/v2/src/main/java/com/skyflow/vault/model/response/DetokenizeResponse.java similarity index 100% rename from v2/main/java/com/skyflow/vault/model/response/DetokenizeResponse.java rename to v2/src/main/java/com/skyflow/vault/model/response/DetokenizeResponse.java diff --git a/v2/main/java/com/skyflow/vault/model/response/GetBinResponse.java b/v2/src/main/java/com/skyflow/vault/model/response/GetBinResponse.java similarity index 100% rename from v2/main/java/com/skyflow/vault/model/response/GetBinResponse.java rename to v2/src/main/java/com/skyflow/vault/model/response/GetBinResponse.java diff --git a/v2/main/java/com/skyflow/vault/model/response/InsertResponse.java b/v2/src/main/java/com/skyflow/vault/model/response/InsertResponse.java similarity index 100% rename from v2/main/java/com/skyflow/vault/model/response/InsertResponse.java rename to v2/src/main/java/com/skyflow/vault/model/response/InsertResponse.java diff --git a/v2/main/java/com/skyflow/vault/model/response/InvokeConnectionResponse.java b/v2/src/main/java/com/skyflow/vault/model/response/InvokeConnectionResponse.java similarity index 100% rename from v2/main/java/com/skyflow/vault/model/response/InvokeConnectionResponse.java rename to v2/src/main/java/com/skyflow/vault/model/response/InvokeConnectionResponse.java diff --git a/v2/main/java/com/skyflow/vault/model/response/ListEventResponse.java b/v2/src/main/java/com/skyflow/vault/model/response/ListEventResponse.java similarity index 100% rename from v2/main/java/com/skyflow/vault/model/response/ListEventResponse.java rename to v2/src/main/java/com/skyflow/vault/model/response/ListEventResponse.java diff --git a/v2/main/java/com/skyflow/vault/service/VaultService.java b/v2/src/main/java/com/skyflow/vault/service/VaultService.java similarity index 100% rename from v2/main/java/com/skyflow/vault/service/VaultService.java rename to v2/src/main/java/com/skyflow/vault/service/VaultService.java From 35762d2c984c63a3124990d01d7f1d02e5cd0440 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 19 Sep 2024 13:47:54 +0530 Subject: [PATCH 004/126] SK-1663 Scaffolding for java sdk v2 - Renamed packages according to design doc for sdk v2 --- v2/src/main/java/com/skyflow/Skyflow.java | 140 ++++++++++++++++++ .../main/java/com/skyflow/client/Skyflow.java | 133 ----------------- .../com/skyflow/config/ConnectionConfig.java | 19 ++- .../java/com/skyflow/config/Credentials.java | 27 +++- .../java/com/skyflow/config/VaultConfig.java | 54 ++++++- v2/src/main/java/com/skyflow/enums/ENV.java | 8 + .../skyflow/{utils => enums}/LogLevel.java | 2 +- .../management/ManagementController.java | 46 ------ .../management/controller/policy/Policy.java | 23 --- .../management/controller/role/Role.java | 23 --- .../management/controller/vault/Vault.java | 23 --- .../createVault/CreateVaultRequest.java | 10 -- .../deletePolicy/DeletePolicyRequest.java | 10 -- .../createVault/CreateVaultResponse.java | 10 -- .../deletePolicy/DeletePolicyResponse.java | 10 -- .../management/service/ManagementService.java | 46 ------ .../main/java/com/skyflow/utils/Builder.java | 4 - .../request => audit}/ListEventRequest.java | 2 +- .../response => audit}/ListEventResponse.java | 2 +- .../com/skyflow/vault/bin/GetBinRequest.java | 10 ++ .../response => bin}/GetBinResponse.java | 2 +- .../connection/InvokeConnectionRequest.java | 10 ++ .../InvokeConnectionResponse.java | 2 +- .../controller/audit/AuditController.java | 7 +- .../controller/bin/BinLookupController.java | 13 ++ .../binlookup/BinLookupController.java | 18 --- .../connections/ConnectionController.java | 14 ++ .../connections/ConnectionsController.java | 19 --- .../controller/detect/DetectController.java | 7 +- .../controller/vault/VaultController.java | 15 +- .../request => data}/InsertRequest.java | 2 +- .../response => data}/InsertResponse.java | 2 +- .../vault/detect/DeIdentifyRequest.java | 10 ++ .../DeIdentifyResponse.java | 2 +- .../skyflow/vault/service/VaultService.java | 5 - .../request => tokens}/DetokenizeRequest.java | 2 +- .../DetokenizeResponse.java | 2 +- 37 files changed, 321 insertions(+), 413 deletions(-) create mode 100644 v2/src/main/java/com/skyflow/Skyflow.java delete mode 100644 v2/src/main/java/com/skyflow/client/Skyflow.java create mode 100644 v2/src/main/java/com/skyflow/enums/ENV.java rename v2/src/main/java/com/skyflow/{utils => enums}/LogLevel.java (74%) delete mode 100644 v2/src/main/java/com/skyflow/management/controller/management/ManagementController.java delete mode 100644 v2/src/main/java/com/skyflow/management/controller/policy/Policy.java delete mode 100644 v2/src/main/java/com/skyflow/management/controller/role/Role.java delete mode 100644 v2/src/main/java/com/skyflow/management/controller/vault/Vault.java delete mode 100644 v2/src/main/java/com/skyflow/management/model/request/createVault/CreateVaultRequest.java delete mode 100644 v2/src/main/java/com/skyflow/management/model/request/deletePolicy/DeletePolicyRequest.java delete mode 100644 v2/src/main/java/com/skyflow/management/model/response/createVault/CreateVaultResponse.java delete mode 100644 v2/src/main/java/com/skyflow/management/model/response/deletePolicy/DeletePolicyResponse.java delete mode 100644 v2/src/main/java/com/skyflow/management/service/ManagementService.java delete mode 100644 v2/src/main/java/com/skyflow/utils/Builder.java rename v2/src/main/java/com/skyflow/vault/{model/request => audit}/ListEventRequest.java (77%) rename v2/src/main/java/com/skyflow/vault/{model/response => audit}/ListEventResponse.java (74%) create mode 100644 v2/src/main/java/com/skyflow/vault/bin/GetBinRequest.java rename v2/src/main/java/com/skyflow/vault/{model/response => bin}/GetBinResponse.java (73%) create mode 100644 v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java rename v2/src/main/java/com/skyflow/vault/{model/response => connection}/InvokeConnectionResponse.java (76%) create mode 100644 v2/src/main/java/com/skyflow/vault/controller/bin/BinLookupController.java delete mode 100644 v2/src/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java create mode 100644 v2/src/main/java/com/skyflow/vault/controller/connections/ConnectionController.java delete mode 100644 v2/src/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java rename v2/src/main/java/com/skyflow/vault/{model/request => data}/InsertRequest.java (77%) rename v2/src/main/java/com/skyflow/vault/{model/response => data}/InsertResponse.java (73%) create mode 100644 v2/src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java rename v2/src/main/java/com/skyflow/vault/{model/response => detect}/DeIdentifyResponse.java (75%) rename v2/src/main/java/com/skyflow/vault/{model/request => tokens}/DetokenizeRequest.java (78%) rename v2/src/main/java/com/skyflow/vault/{model/response => tokens}/DetokenizeResponse.java (75%) diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/v2/src/main/java/com/skyflow/Skyflow.java new file mode 100644 index 00000000..57a1f2da --- /dev/null +++ b/v2/src/main/java/com/skyflow/Skyflow.java @@ -0,0 +1,140 @@ +package com.skyflow; + +import com.skyflow.config.ConnectionConfig; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.LogLevel; +import com.skyflow.vault.controller.connections.ConnectionController; +import com.skyflow.vault.controller.vault.VaultController; + +import java.util.ArrayList; + +public class Skyflow { + private final ArrayList vaults; + private final ArrayList connections; + private Credentials skyflowCredentials; + private LogLevel logLevel; + + private Skyflow(SkyflowClientBuilder builder) { + this.vaults = builder.vaults; + this.connections = builder.connections; + this.logLevel = builder.logLevel; + this.skyflowCredentials = builder.skyflowCredentials; + } + + public static SkyflowClientBuilder builder() { + return new SkyflowClientBuilder(); + } + + public VaultConfig getVaultConfig(String vaultId) { + // get vault config with vault id + return null; + } + + public ConnectionConfig getConnectionConfig(String connectionId) { + // get connection config with connection id + return null; + } + + public LogLevel getLogLevel() { + // get log level + return this.logLevel; + } + + // in case no id is passed, return first vault controller + public VaultController vault() { + return this.vaults.get(0); + } + + public VaultController vault(String vaultId) { + // (cache) - store the vault object in a list, don't create object if object already exits + // return vault Object using static func + return null; + } + + // in case no id is passed, return first connection controller + public ConnectionController connection() { + return this.connections.get(0); + } + + public ConnectionController connection(String connectionId) { + // (cache) - store the connection object in a list, don't create object if object already exits + // return connection Object static func + return null; + } + + public static final class SkyflowClientBuilder { + private final ArrayList vaults; + private final ArrayList connections; + private Credentials skyflowCredentials; + private LogLevel logLevel; + + public SkyflowClientBuilder() { + this.vaults = new ArrayList<>(); + this.connections = new ArrayList<>(); + this.skyflowCredentials = null; + this.logLevel = LogLevel.ERROR; + } + + public SkyflowClientBuilder addVaultConfig(VaultConfig vaultConfig) { + // check if vaultConfig already exists + // display error log in case add was not successful, throw error, or both + return this; + } + + public SkyflowClientBuilder updateVaultConfig(VaultConfig vaultConfig) { + // update vault config with vault config + // display error log in case update was not successful, throw error, or both + return this; + } + + public SkyflowClientBuilder removeVaultConfig(String vaultId) { + // remove vault config with vault id + // display error log in case remove was not successful, throw error, or both + return this; + } + + + public SkyflowClientBuilder addConnectionConfig(ConnectionConfig connectionConfig) { + // add connection config + return this; + } + + public SkyflowClientBuilder updateConnectionConfig(ConnectionConfig connectionConfig) { + // update connection config with connection id + return this; + } + + public SkyflowClientBuilder removeConnectionConfig(String connectionId) { + // remove connection config with connection id + return this; + } + + public SkyflowClientBuilder addSkyflowCredentials(Credentials credentials) { + // set credentials + this.skyflowCredentials = credentials; + return this; + } + + public SkyflowClientBuilder updateSkyflowCredentials(Credentials credentials) { + // set credentials + this.skyflowCredentials = credentials; + return this; + } + + public SkyflowClientBuilder setLogLevel(LogLevel logLevel) { + this.logLevel = logLevel; + return this; + } + + public SkyflowClientBuilder updateLogLevel(LogLevel logLevel) { + this.logLevel = logLevel; + return this; + } + + public Skyflow build() { + // return built skyflow client instance + return new Skyflow(this); + } + } +} diff --git a/v2/src/main/java/com/skyflow/client/Skyflow.java b/v2/src/main/java/com/skyflow/client/Skyflow.java deleted file mode 100644 index abc0504d..00000000 --- a/v2/src/main/java/com/skyflow/client/Skyflow.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.skyflow.client; - -import com.skyflow.config.ConnectionConfig; -import com.skyflow.config.Credentials; -import com.skyflow.config.ManagementConfig; -import com.skyflow.config.VaultConfig; -import com.skyflow.management.controller.management.ManagementController; -import com.skyflow.utils.Builder; -import com.skyflow.utils.LogLevel; -import com.skyflow.vault.controller.connections.ConnectionsController; -import com.skyflow.vault.controller.vault.VaultController; - -public class Skyflow { - Builder builder; - // other members - - public Skyflow(VaultConfig vaultConfig, ConnectionConfig connectionConfig, ManagementConfig managementConfig, Credentials credentials) { - // set members accordingly - } - - public Builder Builder() { - builder = new Builder(); - return builder; - } - - public Builder addVaultConfig(VaultConfig vaultConfig) { - // add vault config - return builder; - } - - public VaultConfig getVaultConfig(String vaultId) { - // get vault config with vault id - return null; - } - - public Builder updateVaultConfig(VaultConfig vaultConfig) { - // update vault config with vault id - return builder; - } - - public Builder removeVaultConfig(String vaultId) { - // remove vault config with vault id - return builder; - } - - public Builder addConnectionConfig(ConnectionConfig connectionConfig) { - // add connection config - return builder; - } - - public ConnectionConfig getConnectionConfig(String connectionId) { - // get connection config with connection id - return null; - } - - public Builder updateConnectionConfig(ConnectionConfig connectionConfig) { - // update connection config with connection id - return builder; - } - - public Builder removeConnectionConfig(String connectionId) { - // remove connection config with connection id - return builder; - } - - public Builder addManagementConfig(ManagementConfig managementConfig) { - // add management config - return builder; - } - - public ManagementConfig getManagementConfig(String managementId) { - // get management config with management id - return null; - } - - public Builder updateManagementConfig(ManagementConfig managementConfig) { - // update management config with management id - return builder; - } - - public Builder removeManagementConfig(String managementId) { - // remove management config with management id - return builder; - } - - public Builder addSkyflowCredentials(Credentials credentials) { - // set credentials - return builder; - } - - public Builder updateSkyflowCredentials(Credentials credentials) { - // set credentials - return builder; - } - - public Builder setLogLevel(LogLevel logLevel) { - // set log level - return builder; - } - - public LogLevel getLogLevel() { - // get log level - return null; - } - - public Builder updateLogLevel(LogLevel logLevel) { - // update log level - return builder; - } - - public Skyflow build() { - // return built skyflow client instance - return this; - } - - public VaultController vault(String vaultId) { - // (cache) - store the vault object in a list, don't create object if object already exits - // return vault Object using static func - return null; - } - - public ConnectionsController connection(String connectionId) { - // (cache) - store the connection object in a list, don't create object if object already exits - // return connection Object static func - return null; - } - - public ManagementController management() { - // cache management object if created - // return management object using static func - return null; - } -} diff --git a/v2/src/main/java/com/skyflow/config/ConnectionConfig.java b/v2/src/main/java/com/skyflow/config/ConnectionConfig.java index 5369b81b..a462e878 100644 --- a/v2/src/main/java/com/skyflow/config/ConnectionConfig.java +++ b/v2/src/main/java/com/skyflow/config/ConnectionConfig.java @@ -1,11 +1,26 @@ package com.skyflow.config; public class ConnectionConfig { - // members + private String connectionId; + private String connectionUrl; + private Credentials credentials; // constructor ConnectionConfig() { + this.connectionId = null; + this.connectionUrl = null; + this.credentials = null; } - // getters ans setters + public void setConnectionId(String connectionId) { + this.connectionId = connectionId; + } + + public void setConnectionUrl(String connectionUrl) { + this.connectionUrl = connectionUrl; + } + + public void setCredentials(Credentials credentials) { + this.credentials = credentials; + } } diff --git a/v2/src/main/java/com/skyflow/config/Credentials.java b/v2/src/main/java/com/skyflow/config/Credentials.java index 44fd58fc..7293bbff 100644 --- a/v2/src/main/java/com/skyflow/config/Credentials.java +++ b/v2/src/main/java/com/skyflow/config/Credentials.java @@ -1,11 +1,34 @@ package com.skyflow.config; +import java.util.ArrayList; + public class Credentials { - // members + private String path; + private ArrayList roles; + private String context; + private String credentialsString; // constructor Credentials() { + this.path = null; + this.roles = new ArrayList<>(); + this.context = null; + this.credentialsString = null; + } + + public void setPath(String path) { + this.path = path; + } + + public void setRoles(ArrayList roles) { + this.roles = roles; + } + + public void setContext(String context) { + this.context = context; } - // getters ans setters + public void setCredentialsString(String credentialsString) { + this.credentialsString = credentialsString; + } } diff --git a/v2/src/main/java/com/skyflow/config/VaultConfig.java b/v2/src/main/java/com/skyflow/config/VaultConfig.java index c70c9850..9bbcf55b 100644 --- a/v2/src/main/java/com/skyflow/config/VaultConfig.java +++ b/v2/src/main/java/com/skyflow/config/VaultConfig.java @@ -1,11 +1,59 @@ package com.skyflow.config; +import com.skyflow.enums.ENV; + public class VaultConfig { // members + private String vaultId; + private String clusterId; + private ENV env; + private Credentials credentials; + + public VaultConfig() { + this.vaultId = null; + this.clusterId = null; + this.env = ENV.PROD; + this.credentials = null; + } + + public String getVaultId() { + return vaultId; + } + + public void setVaultId(String vaultId) { + this.vaultId = vaultId; + } + + public String getClusterId() { + return clusterId; + } - // constructor - VaultConfig() { + public void setClusterId(String clusterId) { + this.clusterId = clusterId; } - // getters ans setters + public ENV getEnv() { + return env; + } + + public void setEnv(ENV env) { + this.env = env; + } + + public Credentials getCredentials() { + return credentials; + } + + public void setCredentials(Credentials credentials) { + this.credentials = credentials; + } + + @Override + public String toString() { + return "VaultConfig{" + + "vaultId='" + vaultId + '\'' + + ", clusterId='" + clusterId + '\'' + + ", env=" + env + + '}'; + } } diff --git a/v2/src/main/java/com/skyflow/enums/ENV.java b/v2/src/main/java/com/skyflow/enums/ENV.java new file mode 100644 index 00000000..17c3e985 --- /dev/null +++ b/v2/src/main/java/com/skyflow/enums/ENV.java @@ -0,0 +1,8 @@ +package com.skyflow.enums; + +public enum ENV { + DEV, + STAGE, + SANDBOX, + PROD +} diff --git a/v2/src/main/java/com/skyflow/utils/LogLevel.java b/v2/src/main/java/com/skyflow/enums/LogLevel.java similarity index 74% rename from v2/src/main/java/com/skyflow/utils/LogLevel.java rename to v2/src/main/java/com/skyflow/enums/LogLevel.java index 873f8264..7b86db3a 100644 --- a/v2/src/main/java/com/skyflow/utils/LogLevel.java +++ b/v2/src/main/java/com/skyflow/enums/LogLevel.java @@ -1,4 +1,4 @@ -package com.skyflow.utils; +package com.skyflow.enums; public enum LogLevel { ERROR, diff --git a/v2/src/main/java/com/skyflow/management/controller/management/ManagementController.java b/v2/src/main/java/com/skyflow/management/controller/management/ManagementController.java deleted file mode 100644 index d397954f..00000000 --- a/v2/src/main/java/com/skyflow/management/controller/management/ManagementController.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.skyflow.management.controller.management; - -public class ManagementController { - // members - - public ManagementController() { - } - - public static ManagementController initialize() { - // return management object - return null; - } - - public T createVault() { - // return vault object using static func - // cache - store the vault object in a list - return null; - } - - public T createRole() { - // return role object using static func - // cache - store the role object in a list - return null; - } - - public T createPolicy() { - // return policy object using static func - // cache - store the policy object in a list - return null; - } - - public T vault(String vaultId) { - // return vault object from the cached list - return null; - } - - public T role(String roleId) { - // return role object from the cached list - return null; - } - - public T policy(String policyId) { - // return policy object from the cached list - return null; - } -} diff --git a/v2/src/main/java/com/skyflow/management/controller/policy/Policy.java b/v2/src/main/java/com/skyflow/management/controller/policy/Policy.java deleted file mode 100644 index e7b27f1d..00000000 --- a/v2/src/main/java/com/skyflow/management/controller/policy/Policy.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.skyflow.management.controller.policy; - -public class Policy { - public Policy() { - } - - public static Policy initialize() { - // return policy object - return null; - } - - public Policy update() { - return null; - } - - public Policy delete() { - return null; - } - - public Policy get() { - return null; - } -} diff --git a/v2/src/main/java/com/skyflow/management/controller/role/Role.java b/v2/src/main/java/com/skyflow/management/controller/role/Role.java deleted file mode 100644 index 5da98b56..00000000 --- a/v2/src/main/java/com/skyflow/management/controller/role/Role.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.skyflow.management.controller.role; - -public class Role { - public Role() { - } - - public static Role initialize() { - // return policy object - return null; - } - - public Role update() { - return null; - } - - public Role delete() { - return null; - } - - public Role get() { - return null; - } -} diff --git a/v2/src/main/java/com/skyflow/management/controller/vault/Vault.java b/v2/src/main/java/com/skyflow/management/controller/vault/Vault.java deleted file mode 100644 index f1a9fea9..00000000 --- a/v2/src/main/java/com/skyflow/management/controller/vault/Vault.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.skyflow.management.controller.vault; - -public class Vault { - public Vault() { - } - - public static Vault initialize() { - // return policy object - return null; - } - - public Vault update() { - return null; - } - - public Vault delete() { - return null; - } - - public Vault get() { - return null; - } -} diff --git a/v2/src/main/java/com/skyflow/management/model/request/createVault/CreateVaultRequest.java b/v2/src/main/java/com/skyflow/management/model/request/createVault/CreateVaultRequest.java deleted file mode 100644 index dee4b447..00000000 --- a/v2/src/main/java/com/skyflow/management/model/request/createVault/CreateVaultRequest.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.skyflow.management.model.request.createVault; - -public class CreateVaultRequest { - // members - - public CreateVaultRequest() { - } - - // getters and setters -} diff --git a/v2/src/main/java/com/skyflow/management/model/request/deletePolicy/DeletePolicyRequest.java b/v2/src/main/java/com/skyflow/management/model/request/deletePolicy/DeletePolicyRequest.java deleted file mode 100644 index 9a97af88..00000000 --- a/v2/src/main/java/com/skyflow/management/model/request/deletePolicy/DeletePolicyRequest.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.skyflow.management.model.request.deletePolicy; - -public class DeletePolicyRequest { - // members - - public DeletePolicyRequest() { - } - - // getters and setters -} diff --git a/v2/src/main/java/com/skyflow/management/model/response/createVault/CreateVaultResponse.java b/v2/src/main/java/com/skyflow/management/model/response/createVault/CreateVaultResponse.java deleted file mode 100644 index 6d797241..00000000 --- a/v2/src/main/java/com/skyflow/management/model/response/createVault/CreateVaultResponse.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.skyflow.management.model.response.createVault; - -public class CreateVaultResponse { - // members - - public CreateVaultResponse() { - } - - // getters and setters -} diff --git a/v2/src/main/java/com/skyflow/management/model/response/deletePolicy/DeletePolicyResponse.java b/v2/src/main/java/com/skyflow/management/model/response/deletePolicy/DeletePolicyResponse.java deleted file mode 100644 index 17795308..00000000 --- a/v2/src/main/java/com/skyflow/management/model/response/deletePolicy/DeletePolicyResponse.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.skyflow.management.model.response.deletePolicy; - -public class DeletePolicyResponse { - // members - - public DeletePolicyResponse() { - } - - // getters and setters -} diff --git a/v2/src/main/java/com/skyflow/management/service/ManagementService.java b/v2/src/main/java/com/skyflow/management/service/ManagementService.java deleted file mode 100644 index 827eb686..00000000 --- a/v2/src/main/java/com/skyflow/management/service/ManagementService.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.skyflow.management.service; - -public class ManagementService { - // members - - public ManagementService() { - } - - public static ManagementService initialize() { - // return management object - return null; - } - - public T createVault() { - // return vault object using static func - // cache - store the vault object in a list - return null; - } - - public T createRole() { - // return role object using static func - // cache - store the role object in a list - return null; - } - - public T createPolicy() { - // return policy object using static func - // cache - store the policy object in a list - return null; - } - - public T vault(String vaultId) { - // return vault object from the cached list - return null; - } - - public T role(String roleId) { - // return role object from the cached list - return null; - } - - public T policy(String policyId) { - // return policy object from the cached list - return null; - } -} diff --git a/v2/src/main/java/com/skyflow/utils/Builder.java b/v2/src/main/java/com/skyflow/utils/Builder.java deleted file mode 100644 index 5641555c..00000000 --- a/v2/src/main/java/com/skyflow/utils/Builder.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.skyflow.utils; - -public class Builder { -} diff --git a/v2/src/main/java/com/skyflow/vault/model/request/ListEventRequest.java b/v2/src/main/java/com/skyflow/vault/audit/ListEventRequest.java similarity index 77% rename from v2/src/main/java/com/skyflow/vault/model/request/ListEventRequest.java rename to v2/src/main/java/com/skyflow/vault/audit/ListEventRequest.java index 3f0f7349..b6c26b6d 100644 --- a/v2/src/main/java/com/skyflow/vault/model/request/ListEventRequest.java +++ b/v2/src/main/java/com/skyflow/vault/audit/ListEventRequest.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.model.request; +package com.skyflow.vault.audit; public class ListEventRequest { // members diff --git a/v2/src/main/java/com/skyflow/vault/model/response/ListEventResponse.java b/v2/src/main/java/com/skyflow/vault/audit/ListEventResponse.java similarity index 74% rename from v2/src/main/java/com/skyflow/vault/model/response/ListEventResponse.java rename to v2/src/main/java/com/skyflow/vault/audit/ListEventResponse.java index 5bb7d631..2647e617 100644 --- a/v2/src/main/java/com/skyflow/vault/model/response/ListEventResponse.java +++ b/v2/src/main/java/com/skyflow/vault/audit/ListEventResponse.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.model.response; +package com.skyflow.vault.audit; public class ListEventResponse { // members diff --git a/v2/src/main/java/com/skyflow/vault/bin/GetBinRequest.java b/v2/src/main/java/com/skyflow/vault/bin/GetBinRequest.java new file mode 100644 index 00000000..d059245f --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/bin/GetBinRequest.java @@ -0,0 +1,10 @@ +package com.skyflow.vault.bin; + +public class GetBinRequest { + // members + + public GetBinRequest() { + } + + // getters ans setters +} diff --git a/v2/src/main/java/com/skyflow/vault/model/response/GetBinResponse.java b/v2/src/main/java/com/skyflow/vault/bin/GetBinResponse.java similarity index 73% rename from v2/src/main/java/com/skyflow/vault/model/response/GetBinResponse.java rename to v2/src/main/java/com/skyflow/vault/bin/GetBinResponse.java index 000280c7..86210031 100644 --- a/v2/src/main/java/com/skyflow/vault/model/response/GetBinResponse.java +++ b/v2/src/main/java/com/skyflow/vault/bin/GetBinResponse.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.model.response; +package com.skyflow.vault.bin; public class GetBinResponse { // members diff --git a/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java b/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java new file mode 100644 index 00000000..886e2166 --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java @@ -0,0 +1,10 @@ +package com.skyflow.vault.connection; + +public class InvokeConnectionRequest { + // members + + public InvokeConnectionRequest() { + } + + // getters ans setters +} diff --git a/v2/src/main/java/com/skyflow/vault/model/response/InvokeConnectionResponse.java b/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java similarity index 76% rename from v2/src/main/java/com/skyflow/vault/model/response/InvokeConnectionResponse.java rename to v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java index 155cff66..4876cffd 100644 --- a/v2/src/main/java/com/skyflow/vault/model/response/InvokeConnectionResponse.java +++ b/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.model.response; +package com.skyflow.vault.connection; public class InvokeConnectionResponse { // members diff --git a/v2/src/main/java/com/skyflow/vault/controller/audit/AuditController.java b/v2/src/main/java/com/skyflow/vault/controller/audit/AuditController.java index 0c2165e8..049bfa67 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/audit/AuditController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/audit/AuditController.java @@ -1,16 +1,11 @@ package com.skyflow.vault.controller.audit; -import com.skyflow.vault.model.response.ListEventResponse; +import com.skyflow.vault.audit.ListEventResponse; public class AuditController { public AuditController() { } - // return audit controller object - public static AuditController initialize() { - return null; - } - // Check for correct return type in python interfaces public ListEventResponse list() { // return audit events diff --git a/v2/src/main/java/com/skyflow/vault/controller/bin/BinLookupController.java b/v2/src/main/java/com/skyflow/vault/controller/bin/BinLookupController.java new file mode 100644 index 00000000..e70fcefe --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/controller/bin/BinLookupController.java @@ -0,0 +1,13 @@ +package com.skyflow.vault.controller.bin; + +import com.skyflow.vault.bin.GetBinResponse; + +public class BinLookupController { + public BinLookupController() { + } + + public GetBinResponse get() { + // return bin lookup response (card metadata associated with BIN) + return null; + } +} diff --git a/v2/src/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java b/v2/src/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java deleted file mode 100644 index 2a3c2df6..00000000 --- a/v2/src/main/java/com/skyflow/vault/controller/binlookup/BinLookupController.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.skyflow.vault.controller.binlookup; - -import com.skyflow.vault.model.response.GetBinResponse; - -public class BinLookupController { - public BinLookupController() { - } - - // return bin lookup controller object - public static BinLookupController initialize() { - return null; - } - - public GetBinResponse get() { - // return bin lookup response (card metadata associated with BIN) - return null; - } -} diff --git a/v2/src/main/java/com/skyflow/vault/controller/connections/ConnectionController.java b/v2/src/main/java/com/skyflow/vault/controller/connections/ConnectionController.java new file mode 100644 index 00000000..139a6d49 --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/controller/connections/ConnectionController.java @@ -0,0 +1,14 @@ +package com.skyflow.vault.controller.connections; + +import com.skyflow.vault.connection.InvokeConnectionResponse; + +public class ConnectionController { + public ConnectionController() { + } + + // check in python interfaces + public InvokeConnectionResponse invoke() { + // invoke the connection + return null; + } +} diff --git a/v2/src/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java b/v2/src/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java deleted file mode 100644 index bfece96d..00000000 --- a/v2/src/main/java/com/skyflow/vault/controller/connections/ConnectionsController.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.skyflow.vault.controller.connections; - -import com.skyflow.vault.model.response.InvokeConnectionResponse; - -public class ConnectionsController { - public ConnectionsController() { - } - - // return connections controller object - public static ConnectionsController initialize() { - return null; - } - - // check in python interfaces - public InvokeConnectionResponse invoke() { - // invoke the connection - return null; - } -} diff --git a/v2/src/main/java/com/skyflow/vault/controller/detect/DetectController.java b/v2/src/main/java/com/skyflow/vault/controller/detect/DetectController.java index 6e02be62..a2605a5c 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/detect/DetectController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/detect/DetectController.java @@ -1,16 +1,11 @@ package com.skyflow.vault.controller.detect; -import com.skyflow.vault.model.response.DeIdentifyResponse; +import com.skyflow.vault.detect.DeIdentifyResponse; public class DetectController { public DetectController() { } - // return detect controller object - public static DetectController initialize() { - return null; - } - // should return detect controller public DetectController deIdentify() { // return detect controller diff --git a/v2/src/main/java/com/skyflow/vault/controller/vault/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/vault/VaultController.java index 0f5389fd..6954db83 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/vault/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/vault/VaultController.java @@ -1,14 +1,21 @@ package com.skyflow.vault.controller.vault; +import com.skyflow.config.VaultConfig; + public class VaultController { // members + private VaultConfig vaultConfig; - public VaultController() { + public VaultController(VaultConfig vaultConfig) { + this.vaultConfig = vaultConfig; } - public static T initialize() { - // return vault service object - return T; + public void setVaultConfig(VaultConfig vaultConfig) { + this.vaultConfig = vaultConfig; + } + + public VaultConfig getVaultConfig() { + return vaultConfig; } public T insert() { diff --git a/v2/src/main/java/com/skyflow/vault/model/request/InsertRequest.java b/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java similarity index 77% rename from v2/src/main/java/com/skyflow/vault/model/request/InsertRequest.java rename to v2/src/main/java/com/skyflow/vault/data/InsertRequest.java index 77380111..84971e0b 100644 --- a/v2/src/main/java/com/skyflow/vault/model/request/InsertRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.model.request; +package com.skyflow.vault.data; public class InsertRequest { // members diff --git a/v2/src/main/java/com/skyflow/vault/model/response/InsertResponse.java b/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java similarity index 73% rename from v2/src/main/java/com/skyflow/vault/model/response/InsertResponse.java rename to v2/src/main/java/com/skyflow/vault/data/InsertResponse.java index 04fff389..444418dd 100644 --- a/v2/src/main/java/com/skyflow/vault/model/response/InsertResponse.java +++ b/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.model.response; +package com.skyflow.vault.data; public class InsertResponse { // members diff --git a/v2/src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java b/v2/src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java new file mode 100644 index 00000000..92be4962 --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java @@ -0,0 +1,10 @@ +package com.skyflow.vault.detect; + +public class DeIdentifyRequest { + // members + + public DeIdentifyRequest() { + } + + // getters ans setters +} diff --git a/v2/src/main/java/com/skyflow/vault/model/response/DeIdentifyResponse.java b/v2/src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java similarity index 75% rename from v2/src/main/java/com/skyflow/vault/model/response/DeIdentifyResponse.java rename to v2/src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java index 4e8c2c58..05fe9a6e 100644 --- a/v2/src/main/java/com/skyflow/vault/model/response/DeIdentifyResponse.java +++ b/v2/src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.model.response; +package com.skyflow.vault.detect; public class DeIdentifyResponse { // members diff --git a/v2/src/main/java/com/skyflow/vault/service/VaultService.java b/v2/src/main/java/com/skyflow/vault/service/VaultService.java index 88ba344b..e699d9b6 100644 --- a/v2/src/main/java/com/skyflow/vault/service/VaultService.java +++ b/v2/src/main/java/com/skyflow/vault/service/VaultService.java @@ -6,11 +6,6 @@ public class VaultService { public VaultService() { } - public static T initialize() { - // return vault service object - return T; - } - public T insert() { return T; } diff --git a/v2/src/main/java/com/skyflow/vault/model/request/DetokenizeRequest.java b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java similarity index 78% rename from v2/src/main/java/com/skyflow/vault/model/request/DetokenizeRequest.java rename to v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java index ae440ed9..631353a7 100644 --- a/v2/src/main/java/com/skyflow/vault/model/request/DetokenizeRequest.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.model.request; +package com.skyflow.vault.tokens; public class DetokenizeRequest { // members diff --git a/v2/src/main/java/com/skyflow/vault/model/response/DetokenizeResponse.java b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java similarity index 75% rename from v2/src/main/java/com/skyflow/vault/model/response/DetokenizeResponse.java rename to v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java index 517dc9a6..e62cbf42 100644 --- a/v2/src/main/java/com/skyflow/vault/model/response/DetokenizeResponse.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.model.response; +package com.skyflow.vault.tokens; public class DetokenizeResponse { // members From 45d96f9acc94d5a22c671d8bd02c78d39bdfd02f Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 19 Sep 2024 17:26:44 +0530 Subject: [PATCH 005/126] SK-1663 Java sdk v2 scaffolding worked on feedback --- v2/src/main/java/com/skyflow/Skyflow.java | 4 +- .../java/com/skyflow/errors/SkyflowError.java | 10 --- .../com/skyflow/errors/SkyflowException.java | 11 +++ .../main/java/com/skyflow/utils/Messages.java | 17 ++++ .../{audit => }/AuditController.java | 2 +- .../{bin => }/BinLookupController.java | 2 +- .../ConnectionController.java | 2 +- .../{detect => }/DetectController.java | 2 +- .../vault/controller/VaultController.java | 82 +++++++++++++++++++ .../controller/vault/VaultController.java | 71 ---------------- .../skyflow/vault/service/VaultService.java | 59 ------------- 11 files changed, 116 insertions(+), 146 deletions(-) delete mode 100644 v2/src/main/java/com/skyflow/errors/SkyflowError.java create mode 100644 v2/src/main/java/com/skyflow/errors/SkyflowException.java create mode 100644 v2/src/main/java/com/skyflow/utils/Messages.java rename v2/src/main/java/com/skyflow/vault/controller/{audit => }/AuditController.java (86%) rename v2/src/main/java/com/skyflow/vault/controller/{bin => }/BinLookupController.java (86%) rename v2/src/main/java/com/skyflow/vault/controller/{connections => }/ConnectionController.java (85%) rename v2/src/main/java/com/skyflow/vault/controller/{detect => }/DetectController.java (91%) create mode 100644 v2/src/main/java/com/skyflow/vault/controller/VaultController.java delete mode 100644 v2/src/main/java/com/skyflow/vault/controller/vault/VaultController.java delete mode 100644 v2/src/main/java/com/skyflow/vault/service/VaultService.java diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/v2/src/main/java/com/skyflow/Skyflow.java index 57a1f2da..b884b40c 100644 --- a/v2/src/main/java/com/skyflow/Skyflow.java +++ b/v2/src/main/java/com/skyflow/Skyflow.java @@ -4,8 +4,8 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; import com.skyflow.enums.LogLevel; -import com.skyflow.vault.controller.connections.ConnectionController; -import com.skyflow.vault.controller.vault.VaultController; +import com.skyflow.vault.controller.ConnectionController; +import com.skyflow.vault.controller.VaultController; import java.util.ArrayList; diff --git a/v2/src/main/java/com/skyflow/errors/SkyflowError.java b/v2/src/main/java/com/skyflow/errors/SkyflowError.java deleted file mode 100644 index 4b6f29a6..00000000 --- a/v2/src/main/java/com/skyflow/errors/SkyflowError.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.skyflow.errors; - -// skyflow error class -public class SkyflowError { - // members - - // constructor - SkyflowError() { - } -} diff --git a/v2/src/main/java/com/skyflow/errors/SkyflowException.java b/v2/src/main/java/com/skyflow/errors/SkyflowException.java new file mode 100644 index 00000000..7cf96536 --- /dev/null +++ b/v2/src/main/java/com/skyflow/errors/SkyflowException.java @@ -0,0 +1,11 @@ +package com.skyflow.errors; + +public class SkyflowException extends Exception { + // members + + public SkyflowException(String message) { + super(message); + } + + // getters and setters +} diff --git a/v2/src/main/java/com/skyflow/utils/Messages.java b/v2/src/main/java/com/skyflow/utils/Messages.java new file mode 100644 index 00000000..28144e0a --- /dev/null +++ b/v2/src/main/java/com/skyflow/utils/Messages.java @@ -0,0 +1,17 @@ +package com.skyflow.utils; + +public final class Messages { + public final static String INVALID_BEARER_TOKEN = "Invalid bearer token"; + public final static String INVALID_VAULT_ID = "Invalid vault id"; + public final static String INVALID_VAULT_URL = "Invalid vault url"; + // other error messages + + public final static String WARNING_MESSAGE = "Some warning message"; + // other warning messages + + public final static String INFO_MESSAGE = "Some info message"; + // other info messages + + public final static String DEBUG_MESSAGE = "Some debug message"; + // other debug messages +} diff --git a/v2/src/main/java/com/skyflow/vault/controller/audit/AuditController.java b/v2/src/main/java/com/skyflow/vault/controller/AuditController.java similarity index 86% rename from v2/src/main/java/com/skyflow/vault/controller/audit/AuditController.java rename to v2/src/main/java/com/skyflow/vault/controller/AuditController.java index 049bfa67..c0b37a52 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/audit/AuditController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/AuditController.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.controller.audit; +package com.skyflow.vault.controller; import com.skyflow.vault.audit.ListEventResponse; diff --git a/v2/src/main/java/com/skyflow/vault/controller/bin/BinLookupController.java b/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java similarity index 86% rename from v2/src/main/java/com/skyflow/vault/controller/bin/BinLookupController.java rename to v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java index e70fcefe..c458aed2 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/bin/BinLookupController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.controller.bin; +package com.skyflow.vault.controller; import com.skyflow.vault.bin.GetBinResponse; diff --git a/v2/src/main/java/com/skyflow/vault/controller/connections/ConnectionController.java b/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java similarity index 85% rename from v2/src/main/java/com/skyflow/vault/controller/connections/ConnectionController.java rename to v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java index 139a6d49..881b2ad4 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/connections/ConnectionController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.controller.connections; +package com.skyflow.vault.controller; import com.skyflow.vault.connection.InvokeConnectionResponse; diff --git a/v2/src/main/java/com/skyflow/vault/controller/detect/DetectController.java b/v2/src/main/java/com/skyflow/vault/controller/DetectController.java similarity index 91% rename from v2/src/main/java/com/skyflow/vault/controller/detect/DetectController.java rename to v2/src/main/java/com/skyflow/vault/controller/DetectController.java index a2605a5c..df09434b 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/detect/DetectController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/DetectController.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.controller.detect; +package com.skyflow.vault.controller; import com.skyflow.vault.detect.DeIdentifyResponse; diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java new file mode 100644 index 00000000..3fbbe01d --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -0,0 +1,82 @@ +package com.skyflow.vault.controller; + +import com.skyflow.config.VaultConfig; +import com.skyflow.vault.audit.ListEventRequest; +import com.skyflow.vault.bin.GetBinRequest; +import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.InsertResponse; +import com.skyflow.vault.detect.DeIdentifyRequest; +import com.skyflow.vault.tokens.DetokenizeRequest; + +public class VaultController { + private final AuditController auditController; + private final BinLookupController binLookupController; + private final DetectController detectController; + // members + private VaultConfig vaultConfig; + + public VaultController(VaultConfig vaultConfig) { + this.vaultConfig = vaultConfig; + this.auditController = new AuditController(); + this.binLookupController = new BinLookupController(); + this.detectController = new DetectController(); + } + + public VaultConfig getVaultConfig() { + return vaultConfig; + } + + public void setVaultConfig(VaultConfig vaultConfig) { + this.vaultConfig = vaultConfig; + } + + public InsertResponse insert(InsertRequest insertRequest) { + return null; + } + + public Object detokenize(DetokenizeRequest detokenizeRequest) { + return null; + } + + public Object get(Object getRequest) { + return null; + } + + public Object update(Object updateRequest) { + return null; + } + + public Object delete(Object deleteRequest) { + return null; + } + + public Object uploadFile(Object uploadFileRequest) { + return null; + } + + public Object query(Object queryRequest) { + return null; + } + + public Object tokenize(Object tokenizeRequest) { + return null; + } + + public BinLookupController lookUpBin(GetBinRequest getBinRequest) { + // cache bin lookup object if created + // return bin lookup object + return this.binLookupController; + } + + public AuditController audit(ListEventRequest listEventRequest) { + // cache audit object if created + // return audit object + return this.auditController; + } + + public DetectController detect(DeIdentifyRequest deIdentifyRequest) { + // cache detect object if created + // return detect object + return this.detectController; + } +} diff --git a/v2/src/main/java/com/skyflow/vault/controller/vault/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/vault/VaultController.java deleted file mode 100644 index 6954db83..00000000 --- a/v2/src/main/java/com/skyflow/vault/controller/vault/VaultController.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.skyflow.vault.controller.vault; - -import com.skyflow.config.VaultConfig; - -public class VaultController { - // members - private VaultConfig vaultConfig; - - public VaultController(VaultConfig vaultConfig) { - this.vaultConfig = vaultConfig; - } - - public void setVaultConfig(VaultConfig vaultConfig) { - this.vaultConfig = vaultConfig; - } - - public VaultConfig getVaultConfig() { - return vaultConfig; - } - - public T insert() { - return T; - } - - public T detokenize() { - return T; - } - - public T get() { - return T; - } - - public T update() { - return T; - } - - public T delete() { - return T; - } - - public T uploadFile() { - return T; - - } - - public T query() { - return T; - } - - public T tokenize() { - return T; - } - - public T lookUpBin() { - // cache bin lookup object if created - // return bin lookup object using static func - return T; - } - - public T audit() { - // cache audit object if created - // return audit object using static func - return T; - } - - public T detect() { - // cache detect object if created - // return detect object using static func - return T; - } -} diff --git a/v2/src/main/java/com/skyflow/vault/service/VaultService.java b/v2/src/main/java/com/skyflow/vault/service/VaultService.java deleted file mode 100644 index e699d9b6..00000000 --- a/v2/src/main/java/com/skyflow/vault/service/VaultService.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.skyflow.vault.service; - -public class VaultService { - // members - - public VaultService() { - } - - public T insert() { - return T; - } - - public T detokenize() { - return T; - } - - public T get() { - return T; - } - - public T update() { - return T; - } - - public T delete() { - return T; - } - - public T uploadFile() { - return T; - - } - - public T query() { - return T; - } - - public T tokenize() { - return T; - } - - public T lookUpBin() { - // cache bin lookup object if created - // return bin lookup object using static func - return T; - } - - public T audit() { - // cache audit object if created - // return audit object using static func - return T; - } - - public T detect() { - // cache detect object if created - // return detect object using static func - return T; - } -} From ad543ad9b59462849d0c93edb034700cacc97392 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 19 Sep 2024 17:32:38 +0530 Subject: [PATCH 006/126] SK-1663 Update method signatures for all controllers --- .../java/com/skyflow/vault/controller/AuditController.java | 3 ++- .../com/skyflow/vault/controller/BinLookupController.java | 3 ++- .../com/skyflow/vault/controller/ConnectionController.java | 3 ++- .../java/com/skyflow/vault/controller/DetectController.java | 5 +++-- 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/v2/src/main/java/com/skyflow/vault/controller/AuditController.java b/v2/src/main/java/com/skyflow/vault/controller/AuditController.java index c0b37a52..4e685f85 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/AuditController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/AuditController.java @@ -1,5 +1,6 @@ package com.skyflow.vault.controller; +import com.skyflow.vault.audit.ListEventRequest; import com.skyflow.vault.audit.ListEventResponse; public class AuditController { @@ -7,7 +8,7 @@ public AuditController() { } // Check for correct return type in python interfaces - public ListEventResponse list() { + public ListEventResponse list(ListEventRequest listEventRequest) { // return audit events return null; } diff --git a/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java b/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java index c458aed2..1338ea8e 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java @@ -1,12 +1,13 @@ package com.skyflow.vault.controller; +import com.skyflow.vault.bin.GetBinRequest; import com.skyflow.vault.bin.GetBinResponse; public class BinLookupController { public BinLookupController() { } - public GetBinResponse get() { + public GetBinResponse get(GetBinRequest getBinRequest) { // return bin lookup response (card metadata associated with BIN) return null; } diff --git a/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java b/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java index 881b2ad4..7e1d9845 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -1,5 +1,6 @@ package com.skyflow.vault.controller; +import com.skyflow.vault.connection.InvokeConnectionRequest; import com.skyflow.vault.connection.InvokeConnectionResponse; public class ConnectionController { @@ -7,7 +8,7 @@ public ConnectionController() { } // check in python interfaces - public InvokeConnectionResponse invoke() { + public InvokeConnectionResponse invoke(InvokeConnectionRequest invokeConnectionRequest) { // invoke the connection return null; } diff --git a/v2/src/main/java/com/skyflow/vault/controller/DetectController.java b/v2/src/main/java/com/skyflow/vault/controller/DetectController.java index df09434b..d5aa7750 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/DetectController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/DetectController.java @@ -1,5 +1,6 @@ package com.skyflow.vault.controller; +import com.skyflow.vault.detect.DeIdentifyRequest; import com.skyflow.vault.detect.DeIdentifyResponse; public class DetectController { @@ -12,12 +13,12 @@ public DetectController deIdentify() { return null; } - public DeIdentifyResponse text() { + public DeIdentifyResponse text(DeIdentifyRequest deIdentifyRequest) { // return detect response return null; } - public DeIdentifyResponse file() { + public DeIdentifyResponse file(DeIdentifyRequest deIdentifyRequest) { // return detect response return null; } From f44c1f7e47e56afcb6ccc87b812c18b6c29478ff Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 25 Sep 2024 14:14:20 +0530 Subject: [PATCH 007/126] SK-1663 Worked on feedback for java sdk v2 scafolding - SK-1677 Worked on client intialisation for Java SDK v2 --- v2/src/main/java/com/skyflow/Skyflow.java | 117 ++++++++++++------ .../com/skyflow/config/ConnectionConfig.java | 7 +- .../java/com/skyflow/config/VaultConfig.java | 16 ++- .../java/com/skyflow/enums/RedactionType.java | 25 ++++ .../com/skyflow/serviceaccount/Utils.java | 5 + v2/src/main/java/com/skyflow/utils/Utils.java | 30 +++++ .../vault/controller/AuditController.java | 12 +- .../vault/controller/BinLookupController.java | 12 +- .../controller/ConnectionController.java | 23 +++- .../vault/controller/DetectController.java | 9 +- .../vault/controller/VaultController.java | 66 +++++++--- .../com/skyflow/vault/data/InsertRequest.java | 104 +++++++++++++++- .../vault/tokens/DetokenizeRequest.java | 71 ++++++++++- .../vault/tokens/DetokenizeResponse.java | 68 +++++++++- 14 files changed, 489 insertions(+), 76 deletions(-) create mode 100644 v2/src/main/java/com/skyflow/enums/RedactionType.java create mode 100644 v2/src/main/java/com/skyflow/serviceaccount/Utils.java create mode 100644 v2/src/main/java/com/skyflow/utils/Utils.java diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/v2/src/main/java/com/skyflow/Skyflow.java index b884b40c..3d1efd39 100644 --- a/v2/src/main/java/com/skyflow/Skyflow.java +++ b/v2/src/main/java/com/skyflow/Skyflow.java @@ -4,121 +4,166 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; import com.skyflow.vault.controller.ConnectionController; import com.skyflow.vault.controller.VaultController; -import java.util.ArrayList; +import java.util.LinkedHashMap; public class Skyflow { - private final ArrayList vaults; - private final ArrayList connections; - private Credentials skyflowCredentials; - private LogLevel logLevel; + private final SkyflowClientBuilder builder; private Skyflow(SkyflowClientBuilder builder) { - this.vaults = builder.vaults; - this.connections = builder.connections; - this.logLevel = builder.logLevel; - this.skyflowCredentials = builder.skyflowCredentials; + this.builder = builder; } public static SkyflowClientBuilder builder() { return new SkyflowClientBuilder(); } + public Skyflow addVaultConfig(VaultConfig vaultConfig) throws SkyflowException { + this.builder.addVaultConfig(vaultConfig); + return this; + } + public VaultConfig getVaultConfig(String vaultId) { // get vault config with vault id - return null; + return this.builder.vaultsMap.get(vaultId).getVaultConfig(); + } + + public Skyflow addConnectionConfig(ConnectionConfig connectionConfig) { + this.builder.addConnectionConfig(connectionConfig); + return this; } public ConnectionConfig getConnectionConfig(String connectionId) { // get connection config with connection id - return null; + return this.builder.connectionsMap.get(connectionId).getConnectionConfig(); + } + + public Skyflow addSkyflowCredentials(Credentials credentials) { + this.builder.addSkyflowCredentials(credentials); + return this; } public LogLevel getLogLevel() { - // get log level - return this.logLevel; + return this.builder.logLevel; } // in case no id is passed, return first vault controller public VaultController vault() { - return this.vaults.get(0); + String vaultId = (String) this.builder.vaultsMap.keySet().toArray()[0]; + return this.vault(vaultId); } public VaultController vault(String vaultId) { - // (cache) - store the vault object in a list, don't create object if object already exits - // return vault Object using static func - return null; + return this.builder.vaultsMap.get(vaultId); } // in case no id is passed, return first connection controller public ConnectionController connection() { - return this.connections.get(0); + String connectionId = (String) this.builder.connectionsMap.keySet().toArray()[0]; + return this.connection(connectionId); } public ConnectionController connection(String connectionId) { - // (cache) - store the connection object in a list, don't create object if object already exits - // return connection Object static func - return null; + return this.builder.connectionsMap.get(connectionId); } public static final class SkyflowClientBuilder { - private final ArrayList vaults; - private final ArrayList connections; + private final LinkedHashMap vaultsMap; + private final LinkedHashMap connectionsMap; private Credentials skyflowCredentials; private LogLevel logLevel; public SkyflowClientBuilder() { - this.vaults = new ArrayList<>(); - this.connections = new ArrayList<>(); + this.vaultsMap = new LinkedHashMap<>(); + this.connectionsMap = new LinkedHashMap<>(); this.skyflowCredentials = null; this.logLevel = LogLevel.ERROR; } public SkyflowClientBuilder addVaultConfig(VaultConfig vaultConfig) { // check if vaultConfig already exists - // display error log in case add was not successful, throw error, or both + if (this.vaultsMap.containsKey(vaultConfig.getVaultId())) { + // display error log, throw error, or both + } else { + this.vaultsMap.put(vaultConfig.getVaultId(), new VaultController(vaultConfig, this.skyflowCredentials)); + } return this; } - public SkyflowClientBuilder updateVaultConfig(VaultConfig vaultConfig) { - // update vault config with vault config - // display error log in case update was not successful, throw error, or both + public SkyflowClientBuilder updateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { + if (this.vaultsMap.containsKey(vaultConfig.getVaultId())) { + VaultController controller = this.vaultsMap.get(vaultConfig.getVaultId()); + controller.setVaultConfig(vaultConfig); + } else { + // display error log, throw error, or both + } return this; } public SkyflowClientBuilder removeVaultConfig(String vaultId) { - // remove vault config with vault id - // display error log in case remove was not successful, throw error, or both + if (this.vaultsMap.containsKey(vaultId)) { + this.vaultsMap.remove(vaultId); + } else { + // display error log, throw error, or both + } return this; } public SkyflowClientBuilder addConnectionConfig(ConnectionConfig connectionConfig) { - // add connection config + // check if connectionConfig already exists + if (this.connectionsMap.containsKey(connectionConfig.getConnectionId())) { + // display error log, throw error, or both + } else { + ConnectionController controller = new ConnectionController(connectionConfig, this.skyflowCredentials); + this.connectionsMap.put(connectionConfig.getConnectionId(), controller); + } return this; } public SkyflowClientBuilder updateConnectionConfig(ConnectionConfig connectionConfig) { - // update connection config with connection id + if (this.connectionsMap.containsKey(connectionConfig.getConnectionId())) { + ConnectionController controller = this.connectionsMap.get(connectionConfig.getConnectionId()); + controller.setConnectionConfig(connectionConfig); + } else { + // display error log, throw error, or both + } return this; } public SkyflowClientBuilder removeConnectionConfig(String connectionId) { - // remove connection config with connection id + if (this.connectionsMap.containsKey(connectionId)) { + this.connectionsMap.remove(connectionId); + } else { + // display error log, throw error, or both + } return this; } public SkyflowClientBuilder addSkyflowCredentials(Credentials credentials) { - // set credentials + // set credentials and update in vault controllers this.skyflowCredentials = credentials; + for (VaultController vault : this.vaultsMap.values()) { + vault.setCommonCredentials(this.skyflowCredentials); + } + for (ConnectionController controller : this.connectionsMap.values()) { + controller.setCommonCredentials(this.skyflowCredentials); + } return this; } public SkyflowClientBuilder updateSkyflowCredentials(Credentials credentials) { - // set credentials + // set credentials and update in vault and connection controllers this.skyflowCredentials = credentials; + for (VaultController vault : this.vaultsMap.values()) { + vault.setCommonCredentials(this.skyflowCredentials); + } + for (ConnectionController controller : this.connectionsMap.values()) { + controller.setCommonCredentials(this.skyflowCredentials); + } return this; } diff --git a/v2/src/main/java/com/skyflow/config/ConnectionConfig.java b/v2/src/main/java/com/skyflow/config/ConnectionConfig.java index a462e878..0c2c4320 100644 --- a/v2/src/main/java/com/skyflow/config/ConnectionConfig.java +++ b/v2/src/main/java/com/skyflow/config/ConnectionConfig.java @@ -5,13 +5,16 @@ public class ConnectionConfig { private String connectionUrl; private Credentials credentials; - // constructor - ConnectionConfig() { + public ConnectionConfig() { this.connectionId = null; this.connectionUrl = null; this.credentials = null; } + public String getConnectionId() { + return connectionId; + } + public void setConnectionId(String connectionId) { this.connectionId = connectionId; } diff --git a/v2/src/main/java/com/skyflow/config/VaultConfig.java b/v2/src/main/java/com/skyflow/config/VaultConfig.java index 9bbcf55b..7e06c391 100644 --- a/v2/src/main/java/com/skyflow/config/VaultConfig.java +++ b/v2/src/main/java/com/skyflow/config/VaultConfig.java @@ -1,9 +1,9 @@ package com.skyflow.config; import com.skyflow.enums.ENV; +import com.skyflow.utils.Utils; public class VaultConfig { - // members private String vaultId; private String clusterId; private ENV env; @@ -48,12 +48,16 @@ public void setCredentials(Credentials credentials) { this.credentials = credentials; } + public String getVaultURL() { + return Utils.getVaultURL(this.clusterId, this.env); + } + @Override public String toString() { - return "VaultConfig{" + - "vaultId='" + vaultId + '\'' + - ", clusterId='" + clusterId + '\'' + - ", env=" + env + - '}'; + return "VaultConfig {" + + "\tvaultId: '" + vaultId + "'," + + "\tclusterId: '" + clusterId + "'," + + "\tenv: " + env + + "\n}"; } } diff --git a/v2/src/main/java/com/skyflow/enums/RedactionType.java b/v2/src/main/java/com/skyflow/enums/RedactionType.java new file mode 100644 index 00000000..af86a560 --- /dev/null +++ b/v2/src/main/java/com/skyflow/enums/RedactionType.java @@ -0,0 +1,25 @@ +package com.skyflow.enums; + +import com.skyflow.generated.rest.models.RedactionEnumREDACTION; + +public enum RedactionType { + PLAIN_TEXT(RedactionEnumREDACTION.PLAIN_TEXT), + MASKED(RedactionEnumREDACTION.MASKED), + DEFAULT(RedactionEnumREDACTION.DEFAULT), + REDACTED(RedactionEnumREDACTION.REDACTED); + + private final RedactionEnumREDACTION redaction; + + RedactionType(RedactionEnumREDACTION redaction) { + this.redaction = redaction; + } + + public RedactionEnumREDACTION getRedaction() { + return redaction; + } + + @Override + public String toString() { + return String.valueOf(redaction); + } +} diff --git a/v2/src/main/java/com/skyflow/serviceaccount/Utils.java b/v2/src/main/java/com/skyflow/serviceaccount/Utils.java new file mode 100644 index 00000000..ea6ec67b --- /dev/null +++ b/v2/src/main/java/com/skyflow/serviceaccount/Utils.java @@ -0,0 +1,5 @@ +package com.skyflow.serviceaccount; + +public class Utils { + // Add service account related methods here +} diff --git a/v2/src/main/java/com/skyflow/utils/Utils.java b/v2/src/main/java/com/skyflow/utils/Utils.java new file mode 100644 index 00000000..5a804f2d --- /dev/null +++ b/v2/src/main/java/com/skyflow/utils/Utils.java @@ -0,0 +1,30 @@ +package com.skyflow.utils; + +import com.skyflow.config.Credentials; +import com.skyflow.enums.ENV; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.auth.HttpBearerAuth; + +public class Utils { + public static String getVaultURL(String clusterId, ENV env) { + switch (env) { + case DEV: + return "https://" + clusterId + ".vault.skyflowapis.dev"; + case STAGE: + return "https://" + clusterId + ".vault.skyflowapis.tech"; + case SANDBOX: + return "https://" + clusterId + ".vault.skyflowapis-preview.com"; + case PROD: + default: + return "https://" + clusterId + ".vault.skyflowapis.com"; + } + } + + public static void updateBearerTokenIfExpired(ApiClient apiClient, Credentials credentials) { + HttpBearerAuth Bearer = (HttpBearerAuth) apiClient.getAuthentication("Bearer"); + // check validity of bearer token + String token = Bearer.getBearerToken(); + // generate bearer token, set in ApiClient if expired or null + Bearer.setBearerToken("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwczovL21hbmFnZS5za3lmbG93YXBpcy50ZWNoIiwiY2xpIjoiYzFiMWZjODViYWEzNDk0NGJkZGNkMzQzMTA2YzIyOGQiLCJleHAiOjE3MjcyNTYyMzMsImlhdCI6MTcyNzI1MjYzNCwiaXNzIjoic2EtYXV0aEBtYW5hZ2Uuc2t5Zmxvd2FwaXMudGVjaCIsImp0aSI6Imc4ZDM3MGI2MmQ0NzQ0M2JhMjdjYWIxMzYxYmU1YjI3Iiwia2V5IjoiamI4ODgxZjRiYTM5NDg0YjkzYzY5MzVjMjhhODg5MDgiLCJzY3AiOm51bGwsInN1YiI6IlNES19FMkUifQ.kbWIbPvjqnawofNgBFwAvnBknaj5_Qo4Gpav9M9XCriOhJdBgPXP9Lc7o4rPrMmmxsI_Lsj3AIK4HGzBvKiA7jLeFOFgjNuHqBJLKzwdixURnYde3bk-7aMUmMWfkg7tzz5uxhcAfgQMrEfGhxdAIzJ_7xSBjaF_2Znz9fPY9_oDSmY1gf4NI-GWZVIx6fEdGxkEWE0W-QNl9EuEeGkGaw40il77Py0XmH8RarT8aNzsdXiTIWDqzW8McdHMiB0R99ceRPAm-a2V8HJC5FyNOEKb6uSeM4ZEz05HmAgxATTAROwL0SlRiFSDG8zh1ER4pO3QJIEIIFUkX9UNqncNuA"); + } +} diff --git a/v2/src/main/java/com/skyflow/vault/controller/AuditController.java b/v2/src/main/java/com/skyflow/vault/controller/AuditController.java index 4e685f85..82629789 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/AuditController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/AuditController.java @@ -1,10 +1,20 @@ package com.skyflow.vault.controller; +import com.skyflow.config.VaultConfig; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.api.AuditApi; import com.skyflow.vault.audit.ListEventRequest; import com.skyflow.vault.audit.ListEventResponse; public class AuditController { - public AuditController() { + private VaultConfig vaultConfig; + private ApiClient apiClient; + private AuditApi auditApi; + + public AuditController(VaultConfig vaultConfig, ApiClient apiClient) { + this.vaultConfig = vaultConfig; + this.apiClient = apiClient; + this.auditApi = new AuditApi(this.apiClient); } // Check for correct return type in python interfaces diff --git a/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java b/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java index 1338ea8e..a8dfc936 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java @@ -1,10 +1,20 @@ package com.skyflow.vault.controller; +import com.skyflow.config.VaultConfig; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.api.BinLookupApi; import com.skyflow.vault.bin.GetBinRequest; import com.skyflow.vault.bin.GetBinResponse; public class BinLookupController { - public BinLookupController() { + private VaultConfig vaultConfig; + private ApiClient apiClient; + private BinLookupApi binLookupApi; + + public BinLookupController(VaultConfig vaultConfig, ApiClient apiClient) { + this.vaultConfig = vaultConfig; + this.apiClient = apiClient; + this.binLookupApi = new BinLookupApi(this.apiClient); } public GetBinResponse get(GetBinRequest getBinRequest) { diff --git a/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java b/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java index 7e1d9845..3061ca3c 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -1,15 +1,34 @@ package com.skyflow.vault.controller; +import com.skyflow.config.ConnectionConfig; +import com.skyflow.config.Credentials; import com.skyflow.vault.connection.InvokeConnectionRequest; import com.skyflow.vault.connection.InvokeConnectionResponse; public class ConnectionController { - public ConnectionController() { + private ConnectionConfig connectionConfig; + private Credentials commonCredentials; + + public ConnectionController(ConnectionConfig connectionConfig, Credentials credentials) { + this.connectionConfig = connectionConfig; + this.commonCredentials = credentials; + } + + public void setCommonCredentials(Credentials commonCredentials) { + this.commonCredentials = commonCredentials; + } + + public ConnectionConfig getConnectionConfig() { + return connectionConfig; + } + + public void setConnectionConfig(ConnectionConfig connectionConfig) { + this.connectionConfig = connectionConfig; } // check in python interfaces public InvokeConnectionResponse invoke(InvokeConnectionRequest invokeConnectionRequest) { - // invoke the connection + // invoke the connection return null; } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/DetectController.java b/v2/src/main/java/com/skyflow/vault/controller/DetectController.java index d5aa7750..5cbf4f02 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/DetectController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/DetectController.java @@ -1,10 +1,17 @@ package com.skyflow.vault.controller; +import com.skyflow.config.VaultConfig; +import com.skyflow.generated.rest.ApiClient; import com.skyflow.vault.detect.DeIdentifyRequest; import com.skyflow.vault.detect.DeIdentifyResponse; public class DetectController { - public DetectController() { + private VaultConfig vaultConfig; + private ApiClient apiClient; + + public DetectController(VaultConfig vaultConfig, ApiClient apiClient) { + this.vaultConfig = vaultConfig; + this.apiClient = apiClient; } // should return detect controller diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index 3fbbe01d..a7100f13 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -1,25 +1,46 @@ package com.skyflow.vault.controller; +import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.api.RecordsApi; +import com.skyflow.generated.rest.api.TokensApi; +import com.skyflow.generated.rest.models.V1DetokenizePayload; +import com.skyflow.generated.rest.models.V1DetokenizeResponse; +import com.skyflow.utils.Utils; import com.skyflow.vault.audit.ListEventRequest; import com.skyflow.vault.bin.GetBinRequest; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.InsertResponse; import com.skyflow.vault.detect.DeIdentifyRequest; import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.DetokenizeResponse; public class VaultController { - private final AuditController auditController; - private final BinLookupController binLookupController; - private final DetectController detectController; - // members + private final RecordsApi recordsApi; + private final TokensApi tokensApi; + private final ApiClient apiClient; + private DetectController detectController; + private AuditController auditController; + private BinLookupController binLookupController; private VaultConfig vaultConfig; + private Credentials commonCredentials; - public VaultController(VaultConfig vaultConfig) { + public VaultController(VaultConfig vaultConfig, Credentials credentials) { this.vaultConfig = vaultConfig; - this.auditController = new AuditController(); - this.binLookupController = new BinLookupController(); - this.detectController = new DetectController(); + this.commonCredentials = credentials; + this.auditController = null; + this.binLookupController = null; + this.detectController = null; + + this.apiClient = new ApiClient(); + this.apiClient.setBasePath(this.vaultConfig.getVaultURL()); + this.tokensApi = new TokensApi(this.apiClient); + this.recordsApi = new RecordsApi(this.apiClient); + } + + public void setCommonCredentials(Credentials commonCredentials) { + this.commonCredentials = commonCredentials; } public VaultConfig getVaultConfig() { @@ -34,8 +55,18 @@ public InsertResponse insert(InsertRequest insertRequest) { return null; } - public Object detokenize(DetokenizeRequest detokenizeRequest) { - return null; + public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) { + V1DetokenizeResponse result = null; + try { + // prioritise credentials here + Utils.updateBearerTokenIfExpired(this.apiClient, this.commonCredentials); + V1DetokenizePayload payload = detokenizeRequest.getDetokenizePayload(); + result = this.tokensApi.recordServiceDetokenize(this.vaultConfig.getVaultId(), payload); + System.out.println(result); + } catch (Exception e) { + e.printStackTrace(); + } + return new DetokenizeResponse(result); } public Object get(Object getRequest) { @@ -63,20 +94,23 @@ public Object tokenize(Object tokenizeRequest) { } public BinLookupController lookUpBin(GetBinRequest getBinRequest) { - // cache bin lookup object if created - // return bin lookup object + if (this.binLookupController == null) { + this.binLookupController = new BinLookupController(this.vaultConfig, this.apiClient); + } return this.binLookupController; } public AuditController audit(ListEventRequest listEventRequest) { - // cache audit object if created - // return audit object + if (this.auditController == null) { + this.auditController = new AuditController(this.vaultConfig, this.apiClient); + } return this.auditController; } public DetectController detect(DeIdentifyRequest deIdentifyRequest) { - // cache detect object if created - // return detect object + if (this.detectController == null) { + this.detectController = new DetectController(this.vaultConfig, this.apiClient); + } return this.detectController; } } diff --git a/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java b/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java index 84971e0b..3cc4bbff 100644 --- a/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java @@ -1,11 +1,107 @@ package com.skyflow.vault.data; +import com.skyflow.enums.Byot; + +import java.util.ArrayList; +import java.util.HashMap; + public class InsertRequest { - // members + private final String table; + private final ArrayList> data; + private final Boolean returnTokens; + private final String upsert; + private final Boolean homogeneous; + private final Boolean tokenMode; + private final Byot tokenStrict; + + private InsertRequest(InsertRequestBuilder builder) { + this.table = builder.table; + this.data = builder.data; + this.returnTokens = builder.returnTokens; + this.upsert = builder.upsert; + this.homogeneous = builder.homogeneous; + this.tokenMode = builder.tokenMode; + this.tokenStrict = builder.tokenStrict; + } + + public static InsertRequestBuilder builder() { + return new InsertRequestBuilder(); + } + + public String getTable() { + return table; + } + + public ArrayList> getData() { + return this.data; + } + + public Boolean getReturnTokens() { + return returnTokens; + } + + public String getUpsert() { + return upsert; + } - // constructor - public InsertRequest() { + public Boolean getHomogeneous() { + return homogeneous; } - // getters ans setters + public Boolean getTokenMode() { + return tokenMode; + } + + public Byot getTokenStrict() { + return tokenStrict; + } + + public static final class InsertRequestBuilder { + private String table; + private ArrayList> data; + private Boolean returnTokens; + private String upsert; + private Boolean homogeneous; + private Boolean tokenMode; + private Byot tokenStrict; + + public InsertRequestBuilder table(String table) { + this.table = table; + return this; + } + + public InsertRequestBuilder data(ArrayList> data) { + this.data = data; + return this; + } + + public InsertRequestBuilder returnTokens(Boolean returnTokens) { + this.returnTokens = returnTokens; + return this; + } + + public InsertRequestBuilder upsert(String upsert) { + this.upsert = upsert; + return this; + } + + public InsertRequestBuilder homogeneous(Boolean homogeneous) { + this.homogeneous = homogeneous; + return this; + } + + public InsertRequestBuilder tokenMode(Boolean tokenMode) { + this.tokenMode = tokenMode; + return this; + } + + public InsertRequestBuilder tokenStrict(Byot tokenStrict) { + this.tokenStrict = tokenStrict; + return this; + } + + public InsertRequest build() { + return new InsertRequest(this); + } + } } diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java index 631353a7..d01cf76f 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java @@ -1,11 +1,74 @@ package com.skyflow.vault.tokens; +import com.skyflow.enums.RedactionType; +import com.skyflow.generated.rest.models.V1DetokenizePayload; +import com.skyflow.generated.rest.models.V1DetokenizeRecordRequest; + +import java.util.ArrayList; + public class DetokenizeRequest { - // members + private final DetokenizeRequestBuilder builder; + + private DetokenizeRequest(DetokenizeRequestBuilder builder) { + this.builder = builder; + } + + public static DetokenizeRequestBuilder builder() { + return new DetokenizeRequestBuilder(); + } + + public ArrayList getTokens() { + return this.builder.tokens; + } + + public RedactionType getRedactionType() { + return this.builder.redactionType; + } + + public Boolean getContinueOnError() { + return this.builder.continueOnError; + } - // constructor - public DetokenizeRequest() { + public V1DetokenizePayload getDetokenizePayload() { + V1DetokenizePayload payload = new V1DetokenizePayload(); + payload.setContinueOnError(this.getContinueOnError()); + for (String token : this.getTokens()) { + V1DetokenizeRecordRequest recordRequest = new V1DetokenizeRecordRequest(); + recordRequest.setToken(token); + recordRequest.setRedaction(this.getRedactionType().getRedaction()); + payload.addDetokenizationParametersItem(recordRequest); + } + return payload; } - // getters ans setters + public static final class DetokenizeRequestBuilder { + private ArrayList tokens; + private RedactionType redactionType; + private Boolean continueOnError; + + public DetokenizeRequestBuilder() { + this.tokens = new ArrayList<>(); + this.redactionType = RedactionType.PLAIN_TEXT; + this.continueOnError = true; + } + + public DetokenizeRequestBuilder tokens(ArrayList tokens) { + this.tokens = tokens; + return this; + } + + public DetokenizeRequestBuilder redactionType(RedactionType redactionType) { + this.redactionType = redactionType; + return this; + } + + public DetokenizeRequestBuilder continueOnError(Boolean continueOnError) { + this.continueOnError = continueOnError; + return this; + } + + public DetokenizeRequest build() { + return new DetokenizeRequest(this); + } + } } diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java index e62cbf42..3ec5eeee 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java @@ -1,10 +1,72 @@ package com.skyflow.vault.tokens; +import com.skyflow.generated.rest.models.V1DetokenizeRecordResponse; +import com.skyflow.generated.rest.models.V1DetokenizeResponse; + +import java.util.ArrayList; +import java.util.List; + public class DetokenizeResponse { - // members + private final V1DetokenizeResponse generatedResponse; + private final ArrayList records; + + public DetokenizeResponse(V1DetokenizeResponse response) { + this.generatedResponse = response; + this.records = new ArrayList<>(); + this.createResponse(); + } + + public ArrayList getRecords() { + return records; + } + + private void createResponse() { + List records = this.generatedResponse.getRecords(); + for (V1DetokenizeRecordResponse record : records) { + DetokenizeRecordResponse recordResponse = new DetokenizeRecordResponse(); + recordResponse.setValue(record.getValue()); + recordResponse.setType(record.getValueType().getValue()); + this.records.add(recordResponse); + } + } - public DetokenizeResponse() { + @Override + public String toString() { + return "DetokenizeResponse {" + + "\n\t" + toIndentedString(records) + + "\n}"; } - // getters ans setters + private String toIndentedString(Object o) { + return o.toString().replace("\n", "\n\t"); + } + + public class DetokenizeRecordResponse { + private String value; + private String type; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + @Override + public String toString() { + return "DetokenizeRecordResponse {" + + "\n\t" + "value: '" + value + "'," + + "\n\t" + "type: '" + type + "'," + + "\n}"; + } + } } From 9eba2dd2dfe0047bef5af65c2c442423b0f361d5 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 1 Oct 2024 16:52:17 +0530 Subject: [PATCH 008/126] SK-1677 Delete old vault controller implementation --- .../vault/controller/VaultController.java | 116 ------------------ 1 file changed, 116 deletions(-) delete mode 100644 v2/src/main/java/com/skyflow/vault/controller/VaultController.java diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java deleted file mode 100644 index a7100f13..00000000 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.skyflow.vault.controller; - -import com.skyflow.config.Credentials; -import com.skyflow.config.VaultConfig; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.api.RecordsApi; -import com.skyflow.generated.rest.api.TokensApi; -import com.skyflow.generated.rest.models.V1DetokenizePayload; -import com.skyflow.generated.rest.models.V1DetokenizeResponse; -import com.skyflow.utils.Utils; -import com.skyflow.vault.audit.ListEventRequest; -import com.skyflow.vault.bin.GetBinRequest; -import com.skyflow.vault.data.InsertRequest; -import com.skyflow.vault.data.InsertResponse; -import com.skyflow.vault.detect.DeIdentifyRequest; -import com.skyflow.vault.tokens.DetokenizeRequest; -import com.skyflow.vault.tokens.DetokenizeResponse; - -public class VaultController { - private final RecordsApi recordsApi; - private final TokensApi tokensApi; - private final ApiClient apiClient; - private DetectController detectController; - private AuditController auditController; - private BinLookupController binLookupController; - private VaultConfig vaultConfig; - private Credentials commonCredentials; - - public VaultController(VaultConfig vaultConfig, Credentials credentials) { - this.vaultConfig = vaultConfig; - this.commonCredentials = credentials; - this.auditController = null; - this.binLookupController = null; - this.detectController = null; - - this.apiClient = new ApiClient(); - this.apiClient.setBasePath(this.vaultConfig.getVaultURL()); - this.tokensApi = new TokensApi(this.apiClient); - this.recordsApi = new RecordsApi(this.apiClient); - } - - public void setCommonCredentials(Credentials commonCredentials) { - this.commonCredentials = commonCredentials; - } - - public VaultConfig getVaultConfig() { - return vaultConfig; - } - - public void setVaultConfig(VaultConfig vaultConfig) { - this.vaultConfig = vaultConfig; - } - - public InsertResponse insert(InsertRequest insertRequest) { - return null; - } - - public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) { - V1DetokenizeResponse result = null; - try { - // prioritise credentials here - Utils.updateBearerTokenIfExpired(this.apiClient, this.commonCredentials); - V1DetokenizePayload payload = detokenizeRequest.getDetokenizePayload(); - result = this.tokensApi.recordServiceDetokenize(this.vaultConfig.getVaultId(), payload); - System.out.println(result); - } catch (Exception e) { - e.printStackTrace(); - } - return new DetokenizeResponse(result); - } - - public Object get(Object getRequest) { - return null; - } - - public Object update(Object updateRequest) { - return null; - } - - public Object delete(Object deleteRequest) { - return null; - } - - public Object uploadFile(Object uploadFileRequest) { - return null; - } - - public Object query(Object queryRequest) { - return null; - } - - public Object tokenize(Object tokenizeRequest) { - return null; - } - - public BinLookupController lookUpBin(GetBinRequest getBinRequest) { - if (this.binLookupController == null) { - this.binLookupController = new BinLookupController(this.vaultConfig, this.apiClient); - } - return this.binLookupController; - } - - public AuditController audit(ListEventRequest listEventRequest) { - if (this.auditController == null) { - this.auditController = new AuditController(this.vaultConfig, this.apiClient); - } - return this.auditController; - } - - public DetectController detect(DeIdentifyRequest deIdentifyRequest) { - if (this.detectController == null) { - this.detectController = new DetectController(this.vaultConfig, this.apiClient); - } - return this.detectController; - } -} From f7ee304d48a8897400519a1cb9768eb5e01bd298 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 1 Oct 2024 20:43:30 +0530 Subject: [PATCH 009/126] SK-1677 Client Initilisation and Credentials priorotisation --- pom.xml | 58 +++++++++++- v2/src/main/java/com/skyflow/Skyflow.java | 89 ++++++++++-------- v2/src/main/java/com/skyflow/VaultClient.java | 91 +++++++++++++++++++ v2/src/main/java/com/skyflow/utils/Utils.java | 4 +- .../vault/controller/AuditController.java | 13 +-- .../vault/controller/BinLookupController.java | 11 +-- .../vault/controller/DetectController.java | 8 +- .../vault/controller/VaultController.java | 87 ++++++++++++++++++ 8 files changed, 295 insertions(+), 66 deletions(-) create mode 100644 v2/src/main/java/com/skyflow/VaultClient.java create mode 100644 v2/src/main/java/com/skyflow/vault/controller/VaultController.java diff --git a/pom.xml b/pom.xml index 1b5060b0..dc4fd6c4 100644 --- a/pom.xml +++ b/pom.xml @@ -32,8 +32,11 @@ - 7 - 7 + 8 + 8 + 4.12.0 + 2.10.1 + 1.9.0 @@ -48,6 +51,36 @@ + + io.github.cdimascio + dotenv-java + 3.0.0 + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + io.gsonfire + gson-fire + ${gson-fire-version} + + + com.google.code.gson + gson + ${gson-version} + + + com.squareup.okhttp3 + okhttp + ${okhttp-version} + + + com.squareup.okhttp3 + logging-interceptor + ${okhttp-version} + com.fasterxml.jackson.core jackson-core @@ -174,6 +207,20 @@ + + org.apache.maven.plugins + maven-jar-plugin + 3.3.0 + + + + test-jar + + + + + + org.apache.maven.plugins maven-gpg-plugin @@ -197,5 +244,12 @@ + + + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ + + \ No newline at end of file diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/v2/src/main/java/com/skyflow/Skyflow.java index 3d1efd39..f9d39d6d 100644 --- a/v2/src/main/java/com/skyflow/Skyflow.java +++ b/v2/src/main/java/com/skyflow/Skyflow.java @@ -3,6 +3,7 @@ import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; +import com.skyflow.enums.ENV; import com.skyflow.enums.LogLevel; import com.skyflow.errors.SkyflowException; import com.skyflow.vault.controller.ConnectionController; @@ -10,7 +11,7 @@ import java.util.LinkedHashMap; -public class Skyflow { +public final class Skyflow { private final SkyflowClientBuilder builder; private Skyflow(SkyflowClientBuilder builder) { @@ -28,7 +29,17 @@ public Skyflow addVaultConfig(VaultConfig vaultConfig) throws SkyflowException { public VaultConfig getVaultConfig(String vaultId) { // get vault config with vault id - return this.builder.vaultsMap.get(vaultId).getVaultConfig(); + return this.builder.vaultConfigMap.get(vaultId); + } + + public Skyflow updateVaultConfig(VaultConfig vaultConfig) throws Exception { + this.builder.updateVaultConfig(vaultConfig); + return this; + } + + public Skyflow removeVaultConfig(String vaultId) throws SkyflowException { + this.builder.removeVaultConfig(vaultId); + return this; } public Skyflow addConnectionConfig(ConnectionConfig connectionConfig) { @@ -41,23 +52,24 @@ public ConnectionConfig getConnectionConfig(String connectionId) { return this.builder.connectionsMap.get(connectionId).getConnectionConfig(); } - public Skyflow addSkyflowCredentials(Credentials credentials) { - this.builder.addSkyflowCredentials(credentials); + public Skyflow updateConnectionConfig(ConnectionConfig connectionConfig) { + this.builder.updateConnectionConfig(connectionConfig); return this; } - public LogLevel getLogLevel() { - return this.builder.logLevel; + public Skyflow removeConnectionConfig(String connectionId) { + this.builder.removeConnectionConfig(connectionId); + return this; } // in case no id is passed, return first vault controller public VaultController vault() { - String vaultId = (String) this.builder.vaultsMap.keySet().toArray()[0]; + String vaultId = (String) this.builder.vaultClientsMap.keySet().toArray()[0]; return this.vault(vaultId); } public VaultController vault(String vaultId) { - return this.builder.vaultsMap.get(vaultId); + return this.builder.vaultClientsMap.get(vaultId); } // in case no id is passed, return first connection controller @@ -71,48 +83,51 @@ public ConnectionController connection(String connectionId) { } public static final class SkyflowClientBuilder { - private final LinkedHashMap vaultsMap; private final LinkedHashMap connectionsMap; + private final LinkedHashMap vaultClientsMap; + private final LinkedHashMap vaultConfigMap; private Credentials skyflowCredentials; private LogLevel logLevel; public SkyflowClientBuilder() { - this.vaultsMap = new LinkedHashMap<>(); + this.vaultClientsMap = new LinkedHashMap<>(); + this.vaultConfigMap = new LinkedHashMap<>(); this.connectionsMap = new LinkedHashMap<>(); this.skyflowCredentials = null; this.logLevel = LogLevel.ERROR; } - public SkyflowClientBuilder addVaultConfig(VaultConfig vaultConfig) { + public SkyflowClientBuilder addVaultConfig(VaultConfig vaultConfig) throws SkyflowException { // check if vaultConfig already exists - if (this.vaultsMap.containsKey(vaultConfig.getVaultId())) { + if (this.vaultClientsMap.containsKey(vaultConfig.getVaultId())) { // display error log, throw error, or both } else { - this.vaultsMap.put(vaultConfig.getVaultId(), new VaultController(vaultConfig, this.skyflowCredentials)); + this.vaultConfigMap.put(vaultConfig.getVaultId(), vaultConfig); + this.vaultClientsMap.put(vaultConfig.getVaultId(), new VaultController(vaultConfig, this.skyflowCredentials)); } return this; } public SkyflowClientBuilder updateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { - if (this.vaultsMap.containsKey(vaultConfig.getVaultId())) { - VaultController controller = this.vaultsMap.get(vaultConfig.getVaultId()); - controller.setVaultConfig(vaultConfig); + if (this.vaultClientsMap.containsKey(vaultConfig.getVaultId())) { + VaultConfig updatedConfig = findAndUpdateVaultConfig(vaultConfig); + this.vaultClientsMap.get(updatedConfig.getVaultId()).updateVaultConfig(updatedConfig); } else { // display error log, throw error, or both } return this; } - public SkyflowClientBuilder removeVaultConfig(String vaultId) { - if (this.vaultsMap.containsKey(vaultId)) { - this.vaultsMap.remove(vaultId); + public SkyflowClientBuilder removeVaultConfig(String vaultId) throws SkyflowException { + if (this.vaultClientsMap.containsKey(vaultId)) { + this.vaultClientsMap.remove(vaultId); + this.vaultConfigMap.remove(vaultId); } else { // display error log, throw error, or both } return this; } - public SkyflowClientBuilder addConnectionConfig(ConnectionConfig connectionConfig) { // check if connectionConfig already exists if (this.connectionsMap.containsKey(connectionConfig.getConnectionId())) { @@ -146,19 +161,7 @@ public SkyflowClientBuilder removeConnectionConfig(String connectionId) { public SkyflowClientBuilder addSkyflowCredentials(Credentials credentials) { // set credentials and update in vault controllers this.skyflowCredentials = credentials; - for (VaultController vault : this.vaultsMap.values()) { - vault.setCommonCredentials(this.skyflowCredentials); - } - for (ConnectionController controller : this.connectionsMap.values()) { - controller.setCommonCredentials(this.skyflowCredentials); - } - return this; - } - - public SkyflowClientBuilder updateSkyflowCredentials(Credentials credentials) { - // set credentials and update in vault and connection controllers - this.skyflowCredentials = credentials; - for (VaultController vault : this.vaultsMap.values()) { + for (VaultController vault : this.vaultClientsMap.values()) { vault.setCommonCredentials(this.skyflowCredentials); } for (ConnectionController controller : this.connectionsMap.values()) { @@ -172,14 +175,24 @@ public SkyflowClientBuilder setLogLevel(LogLevel logLevel) { return this; } - public SkyflowClientBuilder updateLogLevel(LogLevel logLevel) { - this.logLevel = logLevel; - return this; - } - public Skyflow build() { // return built skyflow client instance return new Skyflow(this); } + + private VaultConfig findAndUpdateVaultConfig(VaultConfig vaultConfig) { + VaultConfig previousConfig = this.vaultConfigMap.get(vaultConfig.getVaultId()); + if (previousConfig == null) { + // display error log, throw error, or both + } else { + ENV env = vaultConfig.getEnv() != null ? vaultConfig.getEnv() : previousConfig.getEnv(); + String clusterId = vaultConfig.getClusterId() != null ? vaultConfig.getClusterId() : previousConfig.getClusterId(); + Credentials credentials = vaultConfig.getCredentials() != null ? vaultConfig.getCredentials() : previousConfig.getCredentials(); + previousConfig.setEnv(env); + previousConfig.setClusterId(clusterId); + previousConfig.setCredentials(credentials); + } + return previousConfig; + } } } diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/v2/src/main/java/com/skyflow/VaultClient.java new file mode 100644 index 00000000..11b31bc9 --- /dev/null +++ b/v2/src/main/java/com/skyflow/VaultClient.java @@ -0,0 +1,91 @@ +package com.skyflow; + +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.ENV; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.api.RecordsApi; +import com.skyflow.generated.rest.api.TokensApi; +import com.skyflow.utils.Utils; +import io.github.cdimascio.dotenv.Dotenv; + +public class VaultClient { + private final RecordsApi recordsApi; + private final TokensApi tokensApi; + private final ApiClient apiClient; + private final VaultConfig vaultConfig; + private Credentials commonCredentials; + private Credentials finalCredentials; + + protected VaultClient(VaultConfig vaultConfig, Credentials credentials) { + super(); + this.vaultConfig = vaultConfig; + this.commonCredentials = credentials; + this.apiClient = new ApiClient(); + this.tokensApi = new TokensApi(this.apiClient); + this.recordsApi = new RecordsApi(this.apiClient); + updateVaultURL(); + prioritiseCredentials(); + } + + protected Credentials getFinalCredentials() { + return finalCredentials; + } + + protected RecordsApi getRecordsApi() { + return recordsApi; + } + + protected TokensApi getTokensApi() { + return tokensApi; + } + + protected ApiClient getApiClient() { + return apiClient; + } + + protected VaultConfig getVaultConfig() { + return vaultConfig; + } + + protected void updateVaultConfig(VaultConfig vaultConfig) { + ENV env = vaultConfig.getEnv() != null ? vaultConfig.getEnv() : this.vaultConfig.getEnv(); + String clusterId = vaultConfig.getClusterId() != null ? vaultConfig.getClusterId() : this.vaultConfig.getClusterId(); + Credentials credentials = vaultConfig.getCredentials() != null ? vaultConfig.getCredentials() : this.vaultConfig.getCredentials(); + this.vaultConfig.setEnv(env); + this.vaultConfig.setClusterId(clusterId); + this.vaultConfig.setCredentials(credentials); + updateVaultURL(); + } + + protected void setCommonCredentials(Credentials commonCredentials) { + this.commonCredentials = commonCredentials; + prioritiseCredentials(); + } + + private void updateVaultURL() { + String vaultURL = Utils.getVaultURL(this.vaultConfig.getClusterId(), this.vaultConfig.getEnv()); + this.apiClient.setBasePath(vaultURL); + } + + private void prioritiseCredentials() { + try { + if (this.vaultConfig.getCredentials() != null) { + this.finalCredentials = this.vaultConfig.getCredentials(); + } else if (this.commonCredentials != null) { + this.finalCredentials = this.commonCredentials; + } else { + Dotenv dotenv = Dotenv.load(); + String sysCredentials = dotenv.get("SKYFLOW_CREDENTIALS"); + if (sysCredentials == null) { + // throw error for not passing any credentials + } else { + this.finalCredentials = new Credentials(); + this.finalCredentials.setCredentialsString(sysCredentials); + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/v2/src/main/java/com/skyflow/utils/Utils.java b/v2/src/main/java/com/skyflow/utils/Utils.java index 5a804f2d..90fb8a48 100644 --- a/v2/src/main/java/com/skyflow/utils/Utils.java +++ b/v2/src/main/java/com/skyflow/utils/Utils.java @@ -23,8 +23,8 @@ public static String getVaultURL(String clusterId, ENV env) { public static void updateBearerTokenIfExpired(ApiClient apiClient, Credentials credentials) { HttpBearerAuth Bearer = (HttpBearerAuth) apiClient.getAuthentication("Bearer"); // check validity of bearer token - String token = Bearer.getBearerToken(); + // String token = Bearer.getBearerToken(); // generate bearer token, set in ApiClient if expired or null - Bearer.setBearerToken("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwczovL21hbmFnZS5za3lmbG93YXBpcy50ZWNoIiwiY2xpIjoiYzFiMWZjODViYWEzNDk0NGJkZGNkMzQzMTA2YzIyOGQiLCJleHAiOjE3MjcyNTYyMzMsImlhdCI6MTcyNzI1MjYzNCwiaXNzIjoic2EtYXV0aEBtYW5hZ2Uuc2t5Zmxvd2FwaXMudGVjaCIsImp0aSI6Imc4ZDM3MGI2MmQ0NzQ0M2JhMjdjYWIxMzYxYmU1YjI3Iiwia2V5IjoiamI4ODgxZjRiYTM5NDg0YjkzYzY5MzVjMjhhODg5MDgiLCJzY3AiOm51bGwsInN1YiI6IlNES19FMkUifQ.kbWIbPvjqnawofNgBFwAvnBknaj5_Qo4Gpav9M9XCriOhJdBgPXP9Lc7o4rPrMmmxsI_Lsj3AIK4HGzBvKiA7jLeFOFgjNuHqBJLKzwdixURnYde3bk-7aMUmMWfkg7tzz5uxhcAfgQMrEfGhxdAIzJ_7xSBjaF_2Znz9fPY9_oDSmY1gf4NI-GWZVIx6fEdGxkEWE0W-QNl9EuEeGkGaw40il77Py0XmH8RarT8aNzsdXiTIWDqzW8McdHMiB0R99ceRPAm-a2V8HJC5FyNOEKb6uSeM4ZEz05HmAgxATTAROwL0SlRiFSDG8zh1ER4pO3QJIEIIFUkX9UNqncNuA"); + Bearer.setBearerToken("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwczovL21hbmFnZS5za3lmbG93YXBpcy50ZWNoIiwiY2xpIjoiYzFiMWZjODViYWEzNDk0NGJkZGNkMzQzMTA2YzIyOGQiLCJleHAiOjE3Mjc3ODk0OTUsImlhdCI6MTcyNzc4NTg5NiwiaXNzIjoic2EtYXV0aEBtYW5hZ2Uuc2t5Zmxvd2FwaXMudGVjaCIsImp0aSI6InQxNjhjNTlhYWIzNDRiZTZiMDE0ZWY3MzY4MDlhMjZhIiwia2V5IjoiamI4ODgxZjRiYTM5NDg0YjkzYzY5MzVjMjhhODg5MDgiLCJzY3AiOm51bGwsInN1YiI6IlNES19FMkUifQ.EmCYoR1ieDdseC4XTWOA9oBD7EJPSd5kz4Oka7mPFqLNW4Ms21GMhXll66Q3seKXZH-_DiLR8d3juGSx3nnZZDaAmNANiPfrvNCF66LU-587RDzzIowL-I5qhGigGG8dLh2FICf0eEoRAvdtiYSolWjErbhd-o5k1whxdCZ2cU_8JHiqq3hr48Gy1pVcFYycJ_oj0bxrOqn-r3vfdv_ChruLRQ2xh74qevkzEePg3XSkuniVDemhPp_fVOW4RE6TGYo6vEaWsY6NoPqx21CL49U8avqkIISZm7Uo5PO-sfaRDh3XCy-QFvvR7KoWiMTGj8cHcIkV5uusCV-S8CFIvQ"); } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/AuditController.java b/v2/src/main/java/com/skyflow/vault/controller/AuditController.java index 82629789..9d605e6c 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/AuditController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/AuditController.java @@ -1,25 +1,20 @@ package com.skyflow.vault.controller; -import com.skyflow.config.VaultConfig; import com.skyflow.generated.rest.ApiClient; import com.skyflow.generated.rest.api.AuditApi; import com.skyflow.vault.audit.ListEventRequest; import com.skyflow.vault.audit.ListEventResponse; public class AuditController { - private VaultConfig vaultConfig; - private ApiClient apiClient; - private AuditApi auditApi; + private final AuditApi auditApi; - public AuditController(VaultConfig vaultConfig, ApiClient apiClient) { - this.vaultConfig = vaultConfig; - this.apiClient = apiClient; - this.auditApi = new AuditApi(this.apiClient); + public AuditController(ApiClient apiClient) { + this.auditApi = new AuditApi(apiClient); } // Check for correct return type in python interfaces public ListEventResponse list(ListEventRequest listEventRequest) { - // return audit events + // return audit events return null; } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java b/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java index a8dfc936..e5d9cc62 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java @@ -1,24 +1,19 @@ package com.skyflow.vault.controller; -import com.skyflow.config.VaultConfig; import com.skyflow.generated.rest.ApiClient; import com.skyflow.generated.rest.api.BinLookupApi; import com.skyflow.vault.bin.GetBinRequest; import com.skyflow.vault.bin.GetBinResponse; public class BinLookupController { - private VaultConfig vaultConfig; - private ApiClient apiClient; private BinLookupApi binLookupApi; - public BinLookupController(VaultConfig vaultConfig, ApiClient apiClient) { - this.vaultConfig = vaultConfig; - this.apiClient = apiClient; - this.binLookupApi = new BinLookupApi(this.apiClient); + public BinLookupController(ApiClient apiClient) { + this.binLookupApi = new BinLookupApi(apiClient); } public GetBinResponse get(GetBinRequest getBinRequest) { - // return bin lookup response (card metadata associated with BIN) + // return bin lookup response (card metadata associated with BIN) return null; } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/DetectController.java b/v2/src/main/java/com/skyflow/vault/controller/DetectController.java index 5cbf4f02..5b507d89 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/DetectController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/DetectController.java @@ -1,17 +1,11 @@ package com.skyflow.vault.controller; -import com.skyflow.config.VaultConfig; import com.skyflow.generated.rest.ApiClient; import com.skyflow.vault.detect.DeIdentifyRequest; import com.skyflow.vault.detect.DeIdentifyResponse; public class DetectController { - private VaultConfig vaultConfig; - private ApiClient apiClient; - - public DetectController(VaultConfig vaultConfig, ApiClient apiClient) { - this.vaultConfig = vaultConfig; - this.apiClient = apiClient; + public DetectController(ApiClient apiClient) { } // should return detect controller diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java new file mode 100644 index 00000000..9810eeb7 --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -0,0 +1,87 @@ +package com.skyflow.vault.controller; + +import com.skyflow.VaultClient; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.generated.rest.models.V1DetokenizePayload; +import com.skyflow.generated.rest.models.V1DetokenizeResponse; +import com.skyflow.utils.Utils; +import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.InsertResponse; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.DetokenizeResponse; + +public final class VaultController extends VaultClient { + private DetectController detectController; + private AuditController auditController; + private BinLookupController binLookupController; + + public VaultController(VaultConfig vaultConfig, Credentials credentials) { + super(vaultConfig, credentials); + this.auditController = null; + this.binLookupController = null; + this.detectController = null; + } + + public InsertResponse insert(InsertRequest insertRequest) { + return null; + } + + public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) { + System.out.println(super.getVaultConfig()); + V1DetokenizeResponse result = null; + try { + Utils.updateBearerTokenIfExpired(super.getApiClient(), super.getFinalCredentials()); + V1DetokenizePayload payload = detokenizeRequest.getDetokenizePayload(); + result = super.getTokensApi().recordServiceDetokenize(super.getVaultConfig().getVaultId(), payload); + } catch (Exception e) { + e.printStackTrace(); + } + return new DetokenizeResponse(result); + } + + public Object get(Object getRequest) { + return null; + } + + public Object update(Object updateRequest) { + return null; + } + + public Object delete(Object deleteRequest) { + return null; + } + + public Object uploadFile(Object uploadFileRequest) { + return null; + } + + public Object query(Object queryRequest) { + return null; + } + + public Object tokenize(Object tokenizeRequest) { + return null; + } + + public BinLookupController lookUpBin() { + if (this.binLookupController == null) { + this.binLookupController = new BinLookupController(super.getApiClient()); + } + return this.binLookupController; + } + + public AuditController audit() { + if (this.auditController == null) { + this.auditController = new AuditController(super.getApiClient()); + } + return this.auditController; + } + + public DetectController detect() { + if (this.detectController == null) { + this.detectController = new DetectController(super.getApiClient()); + } + return this.detectController; + } +} From 786055ddc5944ed6a18ba747665532d202bbf174 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 3 Oct 2024 11:07:53 +0530 Subject: [PATCH 010/126] SK-1677 Client initilisation and credentials prioritisation --- v2/src/main/java/com/skyflow/VaultClient.java | 10 +++++----- v2/src/main/java/com/skyflow/config/Credentials.java | 8 ++++++-- v2/src/main/java/com/skyflow/config/VaultConfig.java | 6 +++--- v2/src/main/java/com/skyflow/serviceaccount/Utils.java | 5 ----- 4 files changed, 14 insertions(+), 15 deletions(-) delete mode 100644 v2/src/main/java/com/skyflow/serviceaccount/Utils.java diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/v2/src/main/java/com/skyflow/VaultClient.java index 11b31bc9..f725c510 100644 --- a/v2/src/main/java/com/skyflow/VaultClient.java +++ b/v2/src/main/java/com/skyflow/VaultClient.java @@ -48,6 +48,11 @@ protected VaultConfig getVaultConfig() { return vaultConfig; } + protected void setCommonCredentials(Credentials commonCredentials) { + this.commonCredentials = commonCredentials; + prioritiseCredentials(); + } + protected void updateVaultConfig(VaultConfig vaultConfig) { ENV env = vaultConfig.getEnv() != null ? vaultConfig.getEnv() : this.vaultConfig.getEnv(); String clusterId = vaultConfig.getClusterId() != null ? vaultConfig.getClusterId() : this.vaultConfig.getClusterId(); @@ -58,11 +63,6 @@ protected void updateVaultConfig(VaultConfig vaultConfig) { updateVaultURL(); } - protected void setCommonCredentials(Credentials commonCredentials) { - this.commonCredentials = commonCredentials; - prioritiseCredentials(); - } - private void updateVaultURL() { String vaultURL = Utils.getVaultURL(this.vaultConfig.getClusterId(), this.vaultConfig.getEnv()); this.apiClient.setBasePath(vaultURL); diff --git a/v2/src/main/java/com/skyflow/config/Credentials.java b/v2/src/main/java/com/skyflow/config/Credentials.java index 7293bbff..43deda99 100644 --- a/v2/src/main/java/com/skyflow/config/Credentials.java +++ b/v2/src/main/java/com/skyflow/config/Credentials.java @@ -7,15 +7,19 @@ public class Credentials { private ArrayList roles; private String context; private String credentialsString; + private String token; - // constructor - Credentials() { + public Credentials() { this.path = null; this.roles = new ArrayList<>(); this.context = null; this.credentialsString = null; } + public void setToken(String token) { + this.token = token; + } + public void setPath(String path) { this.path = path; } diff --git a/v2/src/main/java/com/skyflow/config/VaultConfig.java b/v2/src/main/java/com/skyflow/config/VaultConfig.java index 7e06c391..49bfa5e2 100644 --- a/v2/src/main/java/com/skyflow/config/VaultConfig.java +++ b/v2/src/main/java/com/skyflow/config/VaultConfig.java @@ -55,9 +55,9 @@ public String getVaultURL() { @Override public String toString() { return "VaultConfig {" + - "\tvaultId: '" + vaultId + "'," + - "\tclusterId: '" + clusterId + "'," + - "\tenv: " + env + + "\n\tvaultId: '" + vaultId + "'," + + "\n\tclusterId: '" + clusterId + "'," + + "\n\tenv: " + env + "\n}"; } } diff --git a/v2/src/main/java/com/skyflow/serviceaccount/Utils.java b/v2/src/main/java/com/skyflow/serviceaccount/Utils.java deleted file mode 100644 index ea6ec67b..00000000 --- a/v2/src/main/java/com/skyflow/serviceaccount/Utils.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.skyflow.serviceaccount; - -public class Utils { - // Add service account related methods here -} From 6049e1c99dd4becf58bc79043ae575bf9a174df0 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 3 Oct 2024 13:03:30 +0530 Subject: [PATCH 011/126] SK-1677 Used Constants instead of hard-coded strings --- v2/src/main/java/com/skyflow/Skyflow.java | 2 +- v2/src/main/java/com/skyflow/VaultClient.java | 13 +------------ .../main/java/com/skyflow/utils/Constants.java | 9 +++++++++ v2/src/main/java/com/skyflow/utils/Utils.java | 17 ++++++++++++----- 4 files changed, 23 insertions(+), 18 deletions(-) create mode 100644 v2/src/main/java/com/skyflow/utils/Constants.java diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/v2/src/main/java/com/skyflow/Skyflow.java index f9d39d6d..2786d4cc 100644 --- a/v2/src/main/java/com/skyflow/Skyflow.java +++ b/v2/src/main/java/com/skyflow/Skyflow.java @@ -111,7 +111,7 @@ public SkyflowClientBuilder addVaultConfig(VaultConfig vaultConfig) throws Skyfl public SkyflowClientBuilder updateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { if (this.vaultClientsMap.containsKey(vaultConfig.getVaultId())) { VaultConfig updatedConfig = findAndUpdateVaultConfig(vaultConfig); - this.vaultClientsMap.get(updatedConfig.getVaultId()).updateVaultConfig(updatedConfig); + this.vaultClientsMap.get(updatedConfig.getVaultId()).updateVaultURL(); } else { // display error log, throw error, or both } diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/v2/src/main/java/com/skyflow/VaultClient.java index f725c510..456525f7 100644 --- a/v2/src/main/java/com/skyflow/VaultClient.java +++ b/v2/src/main/java/com/skyflow/VaultClient.java @@ -2,7 +2,6 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.ENV; import com.skyflow.generated.rest.ApiClient; import com.skyflow.generated.rest.api.RecordsApi; import com.skyflow.generated.rest.api.TokensApi; @@ -53,17 +52,7 @@ protected void setCommonCredentials(Credentials commonCredentials) { prioritiseCredentials(); } - protected void updateVaultConfig(VaultConfig vaultConfig) { - ENV env = vaultConfig.getEnv() != null ? vaultConfig.getEnv() : this.vaultConfig.getEnv(); - String clusterId = vaultConfig.getClusterId() != null ? vaultConfig.getClusterId() : this.vaultConfig.getClusterId(); - Credentials credentials = vaultConfig.getCredentials() != null ? vaultConfig.getCredentials() : this.vaultConfig.getCredentials(); - this.vaultConfig.setEnv(env); - this.vaultConfig.setClusterId(clusterId); - this.vaultConfig.setCredentials(credentials); - updateVaultURL(); - } - - private void updateVaultURL() { + protected void updateVaultURL() { String vaultURL = Utils.getVaultURL(this.vaultConfig.getClusterId(), this.vaultConfig.getEnv()); this.apiClient.setBasePath(vaultURL); } diff --git a/v2/src/main/java/com/skyflow/utils/Constants.java b/v2/src/main/java/com/skyflow/utils/Constants.java new file mode 100644 index 00000000..475c8e35 --- /dev/null +++ b/v2/src/main/java/com/skyflow/utils/Constants.java @@ -0,0 +1,9 @@ +package com.skyflow.utils; + +public class Constants { + public static String SECURE_PROTOCOL = "https"; + public static String DEV_DOMAIN = ".vault.skyflowapis.dev"; + public static String STAGE_DOMAIN = ".vault.skyflowapis.tech"; + public static String SANDBOX_DOMAIN = ".vault.skyflowapis-preview.com"; + public static String PROD_DOMAIN = ".vault.skyflowapis.com"; +} diff --git a/v2/src/main/java/com/skyflow/utils/Utils.java b/v2/src/main/java/com/skyflow/utils/Utils.java index 90fb8a48..a1698394 100644 --- a/v2/src/main/java/com/skyflow/utils/Utils.java +++ b/v2/src/main/java/com/skyflow/utils/Utils.java @@ -7,17 +7,24 @@ public class Utils { public static String getVaultURL(String clusterId, ENV env) { + StringBuilder sb = new StringBuilder(Constants.SECURE_PROTOCOL); + sb.append(clusterId); switch (env) { case DEV: - return "https://" + clusterId + ".vault.skyflowapis.dev"; + sb.append(Constants.DEV_DOMAIN); + break; case STAGE: - return "https://" + clusterId + ".vault.skyflowapis.tech"; + sb.append(Constants.STAGE_DOMAIN); + break; case SANDBOX: - return "https://" + clusterId + ".vault.skyflowapis-preview.com"; + sb.append(Constants.SANDBOX_DOMAIN); + break; case PROD: default: - return "https://" + clusterId + ".vault.skyflowapis.com"; + sb.append(Constants.PROD_DOMAIN); + break; } + return sb.toString(); } public static void updateBearerTokenIfExpired(ApiClient apiClient, Credentials credentials) { @@ -25,6 +32,6 @@ public static void updateBearerTokenIfExpired(ApiClient apiClient, Credentials c // check validity of bearer token // String token = Bearer.getBearerToken(); // generate bearer token, set in ApiClient if expired or null - Bearer.setBearerToken("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwczovL21hbmFnZS5za3lmbG93YXBpcy50ZWNoIiwiY2xpIjoiYzFiMWZjODViYWEzNDk0NGJkZGNkMzQzMTA2YzIyOGQiLCJleHAiOjE3Mjc3ODk0OTUsImlhdCI6MTcyNzc4NTg5NiwiaXNzIjoic2EtYXV0aEBtYW5hZ2Uuc2t5Zmxvd2FwaXMudGVjaCIsImp0aSI6InQxNjhjNTlhYWIzNDRiZTZiMDE0ZWY3MzY4MDlhMjZhIiwia2V5IjoiamI4ODgxZjRiYTM5NDg0YjkzYzY5MzVjMjhhODg5MDgiLCJzY3AiOm51bGwsInN1YiI6IlNES19FMkUifQ.EmCYoR1ieDdseC4XTWOA9oBD7EJPSd5kz4Oka7mPFqLNW4Ms21GMhXll66Q3seKXZH-_DiLR8d3juGSx3nnZZDaAmNANiPfrvNCF66LU-587RDzzIowL-I5qhGigGG8dLh2FICf0eEoRAvdtiYSolWjErbhd-o5k1whxdCZ2cU_8JHiqq3hr48Gy1pVcFYycJ_oj0bxrOqn-r3vfdv_ChruLRQ2xh74qevkzEePg3XSkuniVDemhPp_fVOW4RE6TGYo6vEaWsY6NoPqx21CL49U8avqkIISZm7Uo5PO-sfaRDh3XCy-QFvvR7KoWiMTGj8cHcIkV5uusCV-S8CFIvQ"); + Bearer.setBearerToken("BEARER_TOKEN"); } } From 988ab14a81a10783beff3f18f4c4a2672217db5b Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 4 Oct 2024 16:56:23 +0530 Subject: [PATCH 012/126] SK-1678 Bearer Token uitlities - Implemented bearer token utilities for generating bearer token with or without context and roles - Implemented Token utilties to check for validity of tokens - Implemented signed data tokens utilities to generate signed data tokens --- pom.xml | 36 +-- v1/pom.xml | 20 ++ v2/pom.xml | 55 +++++ v2/src/main/java/com/skyflow/Skyflow.java | 16 +- v2/src/main/java/com/skyflow/VaultClient.java | 7 +- .../java/com/skyflow/config/Credentials.java | 24 +- .../serviceaccount/util/BearerToken.java | 208 ++++++++++++++++++ .../util/SignedDataTokenResponse.java | 22 ++ .../serviceaccount/util/SignedDataTokens.java | 205 +++++++++++++++++ .../skyflow/serviceaccount/util/Token.java | 44 ++++ .../java/com/skyflow/utils/Constants.java | 14 +- v2/src/main/java/com/skyflow/utils/Utils.java | 90 +++++++- .../vault/controller/VaultController.java | 17 +- 13 files changed, 708 insertions(+), 50 deletions(-) create mode 100644 v1/pom.xml create mode 100644 v2/pom.xml create mode 100644 v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java create mode 100644 v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java create mode 100644 v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java create mode 100644 v2/src/main/java/com/skyflow/serviceaccount/util/Token.java diff --git a/pom.xml b/pom.xml index dc4fd6c4..85befa48 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ com.skyflow skyflow-java 1.15.0 - jar + pom ${project.groupId}:${project.artifactId} Skyflow SDK for the Java programming language @@ -25,6 +25,10 @@ skyflow + + v1 + v2 + scm:git:git://github.com:skyflowapi/skyflow-java.git scm:git:ssh://github.com:skyflowapi/skyflow-java.git @@ -51,36 +55,6 @@ - - io.github.cdimascio - dotenv-java - 3.0.0 - - - com.google.code.findbugs - jsr305 - 3.0.2 - - - io.gsonfire - gson-fire - ${gson-fire-version} - - - com.google.code.gson - gson - ${gson-version} - - - com.squareup.okhttp3 - okhttp - ${okhttp-version} - - - com.squareup.okhttp3 - logging-interceptor - ${okhttp-version} - com.fasterxml.jackson.core jackson-core diff --git a/v1/pom.xml b/v1/pom.xml new file mode 100644 index 00000000..ff3fc13a --- /dev/null +++ b/v1/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + + com.skyflow + skyflow-java + 1.15.0 + + + v1 + + + 8 + 8 + UTF-8 + + + \ No newline at end of file diff --git a/v2/pom.xml b/v2/pom.xml new file mode 100644 index 00000000..4e314ed9 --- /dev/null +++ b/v2/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + + com.skyflow + skyflow-java + 1.15.0 + + + v2 + + + 8 + 8 + UTF-8 + 4.12.0 + 2.10.1 + 1.9.0 + + + + + io.github.cdimascio + dotenv-java + 3.0.0 + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + io.gsonfire + gson-fire + ${gson-fire-version} + + + com.google.code.gson + gson + ${gson-version} + + + com.squareup.okhttp3 + okhttp + ${okhttp-version} + + + com.squareup.okhttp3 + logging-interceptor + ${okhttp-version} + + + \ No newline at end of file diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/v2/src/main/java/com/skyflow/Skyflow.java index 2786d4cc..7a0e45aa 100644 --- a/v2/src/main/java/com/skyflow/Skyflow.java +++ b/v2/src/main/java/com/skyflow/Skyflow.java @@ -62,6 +62,20 @@ public Skyflow removeConnectionConfig(String connectionId) { return this; } + public Skyflow updateSkyflowCredentials(Credentials credentials) { + this.builder.addSkyflowCredentials(credentials); + return this; + } + + public Skyflow updateLogLevel(LogLevel logLevel) { + this.builder.setLogLevel(logLevel); + return this; + } + + public LogLevel getLogLevel() { + return this.builder.logLevel; + } + // in case no id is passed, return first vault controller public VaultController vault() { String vaultId = (String) this.builder.vaultClientsMap.keySet().toArray()[0]; @@ -111,7 +125,7 @@ public SkyflowClientBuilder addVaultConfig(VaultConfig vaultConfig) throws Skyfl public SkyflowClientBuilder updateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { if (this.vaultClientsMap.containsKey(vaultConfig.getVaultId())) { VaultConfig updatedConfig = findAndUpdateVaultConfig(vaultConfig); - this.vaultClientsMap.get(updatedConfig.getVaultId()).updateVaultURL(); + this.vaultClientsMap.get(updatedConfig.getVaultId()).updateVaultConfig(); } else { // display error log, throw error, or both } diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/v2/src/main/java/com/skyflow/VaultClient.java index 456525f7..75eda5af 100644 --- a/v2/src/main/java/com/skyflow/VaultClient.java +++ b/v2/src/main/java/com/skyflow/VaultClient.java @@ -52,7 +52,12 @@ protected void setCommonCredentials(Credentials commonCredentials) { prioritiseCredentials(); } - protected void updateVaultURL() { + protected void updateVaultConfig() { + updateVaultURL(); + prioritiseCredentials(); + } + + private void updateVaultURL() { String vaultURL = Utils.getVaultURL(this.vaultConfig.getClusterId(), this.vaultConfig.getEnv()); this.apiClient.setBasePath(vaultURL); } diff --git a/v2/src/main/java/com/skyflow/config/Credentials.java b/v2/src/main/java/com/skyflow/config/Credentials.java index 43deda99..75130b90 100644 --- a/v2/src/main/java/com/skyflow/config/Credentials.java +++ b/v2/src/main/java/com/skyflow/config/Credentials.java @@ -16,23 +16,43 @@ public Credentials() { this.credentialsString = null; } - public void setToken(String token) { - this.token = token; + public String getPath() { + return path; } public void setPath(String path) { this.path = path; } + public ArrayList getRoles() { + return roles; + } + public void setRoles(ArrayList roles) { this.roles = roles; } + public String getContext() { + return context; + } + public void setContext(String context) { this.context = context; } + public String getCredentialsString() { + return credentialsString; + } + public void setCredentialsString(String credentialsString) { this.credentialsString = credentialsString; } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } } diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java b/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java new file mode 100644 index 00000000..6d15fef1 --- /dev/null +++ b/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java @@ -0,0 +1,208 @@ +package com.skyflow.serviceaccount.util; + +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.ApiException; +import com.skyflow.generated.rest.api.AuthenticationApi; +import com.skyflow.generated.rest.models.V1GetAuthTokenRequest; +import com.skyflow.generated.rest.models.V1GetAuthTokenResponse; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.net.MalformedURLException; +import java.security.PrivateKey; +import java.util.ArrayList; +import java.util.Date; +import java.util.Objects; + +public class BearerToken { + private static final ApiClient apiClient = new ApiClient(); + private static final AuthenticationApi authenticationApi = new AuthenticationApi(apiClient); + private final File credentialsFile; + private final String credentialsString; + private final String ctx; + private final ArrayList roles; + private final String credentialsType; + + private BearerToken(BearerTokenBuilder builder) { + this.credentialsFile = builder.credentialsFile; + this.credentialsString = builder.credentialsString; + this.ctx = builder.ctx; + this.roles = builder.roles; + this.credentialsType = builder.credentialsType; + } + + public static BearerTokenBuilder builder() { + return new BearerTokenBuilder(); + } + + private static V1GetAuthTokenResponse generateBearerTokenFromCredentials( + File credentialsPath, String context, ArrayList roles + ) throws SkyflowException { + JSONParser parser = new JSONParser(); + try { + if (credentialsPath == null || !credentialsPath.isFile()) { + throw new SkyflowException("credentials string cannot bt empty"); + } + Object obj = parser.parse(new FileReader(String.valueOf(credentialsPath))); + JSONObject serviceAccountCredentials = (JSONObject) obj; + return getBearerTokenFromCredentials(serviceAccountCredentials, context, roles); + } catch (ParseException e) { + throw new SkyflowException("credentials string is not in valid json string format"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static V1GetAuthTokenResponse generateBearerTokenFromCredentialString( + String credentials, String context, ArrayList roles + ) throws SkyflowException { + JSONParser parser = new JSONParser(); + try { + if (credentials == null || credentials.isEmpty()) { + throw new SkyflowException("credentials string cannot bt empty"); + } + Object obj = parser.parse(credentials); + JSONObject serviceAccountCredentials = (JSONObject) obj; + return getBearerTokenFromCredentials(serviceAccountCredentials, context, roles); + } catch (ParseException e) { + throw new SkyflowException("credentials string is not in valid json string format"); + } + } + + private static V1GetAuthTokenResponse getBearerTokenFromCredentials( + JSONObject credentials, String context, ArrayList roles + ) throws SkyflowException { + try { + String privateKey = (String) credentials.get("privateKey"); + if (privateKey == null) { + throw new SkyflowException("privateKey not found"); + } + + String clientID = (String) credentials.get("clientID"); + if (clientID == null) { + throw new SkyflowException("clientID not found"); + } + + String keyID = (String) credentials.get("keyID"); + if (keyID == null) { + throw new SkyflowException("keyID not found"); + } + + String tokenURI = (String) credentials.get("tokenURI"); + if (tokenURI == null) { + throw new SkyflowException("tokenURI not found"); + } + + PrivateKey pvtKey = Utils.getPrivateKeyFromPem(privateKey); + String signedUserJWT = getSignedToken(clientID, keyID, tokenURI, pvtKey, context); + + String basePath = Utils.getBaseURL(tokenURI); + apiClient.setBasePath(basePath); + + V1GetAuthTokenRequest body = new V1GetAuthTokenRequest(); + body.setGrantType(Constants.GRANT_TYPE); + body.setAssertion(signedUserJWT); + + if (roles != null) { + String scopedRoles = getScopeUsingRoles(roles); + body.setScope(scopedRoles); + } + return authenticationApi.authenticationServiceGetAuthToken(body); + } catch (MalformedURLException e) { + throw new SkyflowException("Invalid value for tokenURI in credentials"); + } catch (ApiException e) { + throw new RuntimeException(e); + } + } + + private static String getSignedToken( + String clientID, String keyID, String tokenURI, PrivateKey pvtKey, String context + ) { + final Date createdDate = new Date(); + final Date expirationDate = new Date(createdDate.getTime() + (3600 * 1000)); + return Jwts.builder() + .claim("iss", clientID) + .claim("key", keyID) + .claim("aud", tokenURI) + .claim("sub", clientID) + .claim("ctx", context) + .setExpiration(expirationDate) + .signWith(SignatureAlgorithm.RS256, pvtKey) + .compact(); + } + + private static String getScopeUsingRoles(ArrayList roles) { + StringBuilder scope = new StringBuilder(); + if (roles != null) { + for (String role : roles) { + scope.append(" role:").append(role); + } + } + return scope.toString(); + } + + public synchronized String getBearerToken() throws SkyflowException { + V1GetAuthTokenResponse response; + String accessToken = null; + try { + if (this.credentialsFile != null && Objects.equals(this.credentialsType, "FILE")) { + response = generateBearerTokenFromCredentials(this.credentialsFile, this.ctx, this.roles); + accessToken = response.getAccessToken(); + } else if (this.credentialsString != null && Objects.equals(this.credentialsType, "STRING")) { + response = generateBearerTokenFromCredentialString(this.credentialsString, this.ctx, this.roles); + accessToken = response.getAccessToken(); + } + } catch (SkyflowException e) { + e.printStackTrace(); + } + return accessToken; + } + + // Builder class + public static class BearerTokenBuilder { + private File credentialsFile; + private String credentialsString; + private String ctx; + private ArrayList roles; + private String credentialsType; + + private void setCredentialsType(String credentialsType) { + this.credentialsType = credentialsType; + } + + public BearerTokenBuilder setCredentials(File credentialsFile) { + setCredentialsType("FILE"); + this.credentialsFile = credentialsFile; + return this; + } + + public BearerTokenBuilder setCredentials(String credentialsString) { + setCredentialsType("STRING"); + this.credentialsString = credentialsString; + return this; + } + + public BearerTokenBuilder setCtx(String ctx) { + this.ctx = ctx; + return this; + } + + public BearerTokenBuilder setRoles(ArrayList roles) { + this.roles = roles; + return this; + } + + public BearerToken build() { + return new BearerToken(this); + } + } +} diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java b/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java new file mode 100644 index 00000000..e7e966bc --- /dev/null +++ b/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java @@ -0,0 +1,22 @@ +package com.skyflow.serviceaccount.util; + +import com.skyflow.utils.Constants; + +public class SignedDataTokenResponse { + private static final String prefix = Constants.SIGNED_DATA_TOKEN_PREFIX; + private final String dataToken; + private final String signedDataToken; + + public SignedDataTokenResponse(String dataToken, String signedDataToken) { + this.dataToken = dataToken; + this.signedDataToken = new StringBuilder(prefix).append(signedDataToken).toString(); + } + + @Override + public String toString() { + return "{" + + "\n\t\"dataToken\":\"" + this.dataToken + "\"," + + "\n\t\"signedDataToken\":\"" + this.signedDataToken + "\"," + + "\n}"; + } +} diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java b/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java new file mode 100644 index 00000000..482398b7 --- /dev/null +++ b/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java @@ -0,0 +1,205 @@ +package com.skyflow.serviceaccount.util; + +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.Utils; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.security.PrivateKey; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Objects; + +public class SignedDataTokens { + private final File credentialsFile; + private final String credentialsString; + private final String credentialsType; + private final String ctx; + private final ArrayList dataTokens; + private final Integer timeToLive; + + private SignedDataTokens(SignedDataTokensBuilder builder) { + this.credentialsFile = builder.credentialsFile; + this.credentialsString = builder.credentialsString; + this.credentialsType = builder.credentialsType; + this.ctx = builder.ctx; + this.dataTokens = builder.dataTokens; + this.timeToLive = builder.timeToLive; + } + + public static SignedDataTokensBuilder builder() { + return new SignedDataTokensBuilder(); + } + + private static List generateSignedTokens( + File credentialsPath, ArrayList dataTokens, Integer timeToLive, String context + ) throws SkyflowException { + // print info log + JSONParser parser = new JSONParser(); + List responseToken; + try { + if (credentialsPath == null || !credentialsPath.isFile()) { + // print error log + throw new SkyflowException("credentials string cannot be empty"); + } + Object obj = parser.parse(new FileReader(String.valueOf(credentialsPath))); + JSONObject serviceAccountCredentials = (JSONObject) obj; + responseToken = getSignedTokenFromCredentialsFile(serviceAccountCredentials, dataTokens, timeToLive, context); + } catch (ParseException e) { + // print error log + throw new SkyflowException("credentials string is not in valid json string format"); + } catch (IOException e) { + throw new RuntimeException(e); + } + + return responseToken; + } + + private static List generateSignedTokensFromCredentialsString( + String credentials, ArrayList dataTokens, Integer timeToLive, String context + ) throws SkyflowException { + // print info log + JSONParser parser = new JSONParser(); + List responseToken; + // print info log + try { + if (credentials == null || credentials.isEmpty()) { + // print error log + throw new SkyflowException("credentials string cannot by empty"); + } + Object obj = parser.parse(credentials); + JSONObject serviceAccountCredentials = (JSONObject) obj; + responseToken = getSignedTokenFromCredentialsFile(serviceAccountCredentials, dataTokens, timeToLive, context); + + } catch (ParseException e) { + // print error log + throw new SkyflowException("credentials string is not in valid json string format"); + } + + return responseToken; + } + + private static List getSignedTokenFromCredentialsFile( + JSONObject credentials, ArrayList dataTokens, Integer timeToLive, String context + ) throws SkyflowException { + List signedDataTokens = null; + try { + String privateKey = (String) credentials.get("privateKey"); + if (privateKey == null) { + throw new SkyflowException("privateKey not found"); + } + + String clientID = (String) credentials.get("clientID"); + if (clientID == null) { + // print error log + throw new SkyflowException("invalid clientID"); + } + String keyID = (String) credentials.get("keyID"); + if (keyID == null) { + // print error log + throw new SkyflowException("invalid KeyID"); + } + PrivateKey pvtKey = Utils.getPrivateKeyFromPem(privateKey); + signedDataTokens = getSignedToken(clientID, keyID, pvtKey, dataTokens, timeToLive, context); + } catch (RuntimeException e) { + // throw error + } + return signedDataTokens; + } + + private static List getSignedToken( + String clientID, String keyID, PrivateKey pvtKey, + ArrayList dataTokens, Integer timeToLive, String context + ) { + final Date createdDate = new Date(); + final Date expirationDate; + + if (timeToLive != null) { + expirationDate = new Date(createdDate.getTime() + (timeToLive * 1000)); + } else { + expirationDate = new Date(createdDate.getTime() + 60000); // Valid for 60 seconds + } + + List list = new ArrayList<>(); + for (String dataToken : dataTokens) { + String eachSignedDataToken = Jwts.builder() + .claim("iss", "sdk") + .claim("iat", (createdDate.getTime() / 1000)) + .claim("key", keyID) + .claim("sub", clientID) + .claim("ctx", context) + .claim("tok", dataToken) + .setExpiration(expirationDate) + .signWith(SignatureAlgorithm.RS256, pvtKey) + .compact(); + SignedDataTokenResponse responseObject = new SignedDataTokenResponse(dataToken, eachSignedDataToken); + list.add(responseObject); + } + return list; + } + + public synchronized List getSignedDataTokens() throws SkyflowException { + List signedToken = new ArrayList<>(); + try { + if (this.credentialsFile != null && Objects.equals(this.credentialsType, "FILE")) { + signedToken = generateSignedTokens(this.credentialsFile, this.dataTokens, this.timeToLive, this.ctx); + } else if (this.credentialsString != null && Objects.equals(this.credentialsType, "STRING")) { + signedToken = generateSignedTokensFromCredentialsString(this.credentialsString, this.dataTokens, this.timeToLive, this.ctx); + } + } catch (SkyflowException e) { + e.printStackTrace(); + } + return signedToken; + } + + public static class SignedDataTokensBuilder { + private ArrayList dataTokens; + private Integer timeToLive; + private File credentialsFile; + private String credentialsString; + private String ctx; + private String credentialsType; + + private void setCredentialsType(String credentialsType) { + this.credentialsType = credentialsType; + } + + public SignedDataTokensBuilder setCredentials(File credentialsFile) { + setCredentialsType("FILE"); + this.credentialsFile = credentialsFile; + return this; + } + + public SignedDataTokensBuilder setCredentials(String credentialsString) { + setCredentialsType("STRING"); + this.credentialsString = credentialsString; + return this; + } + + public SignedDataTokensBuilder setCtx(String ctx) { + this.ctx = ctx; + return this; + } + + public SignedDataTokensBuilder setDataTokens(ArrayList dataTokens) { + this.dataTokens = dataTokens; + return this; + } + + public SignedDataTokensBuilder setTimeToLive(Integer timeToLive) { + this.timeToLive = timeToLive; + return this; + } + + public SignedDataTokens build() { + return new SignedDataTokens(this); + } + } +} diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/Token.java b/v2/src/main/java/com/skyflow/serviceaccount/util/Token.java new file mode 100644 index 00000000..60e49947 --- /dev/null +++ b/v2/src/main/java/com/skyflow/serviceaccount/util/Token.java @@ -0,0 +1,44 @@ +package com.skyflow.serviceaccount.util; + +import com.skyflow.errors.SkyflowException; +import org.apache.commons.codec.binary.Base64; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.util.Date; + +public class Token { + public static boolean isExpired(String token) { + long expiryTime; + long currentTime; + try { + if (token == null || token.isEmpty()) { + // print info log + return true; + } + + currentTime = new Date().getTime() / 1000; + expiryTime = (long) decoded(token).get("exp"); + + } catch (ParseException e) { + // display info log + return true; + } catch (SkyflowException e) { + // display info log + return true; + } + return currentTime > expiryTime; + } + + static JSONObject decoded(String encodedToken) throws ParseException, SkyflowException { + String[] split = encodedToken.split("\\."); + if (split.length < 3) { + throw new SkyflowException("invalid bearer token"); + } + byte[] decodedBytes = Base64.decodeBase64(split[1]); + return (JSONObject) new JSONParser().parse(new String(decodedBytes, StandardCharsets.UTF_8)); + } +} diff --git a/v2/src/main/java/com/skyflow/utils/Constants.java b/v2/src/main/java/com/skyflow/utils/Constants.java index 475c8e35..8aacabe2 100644 --- a/v2/src/main/java/com/skyflow/utils/Constants.java +++ b/v2/src/main/java/com/skyflow/utils/Constants.java @@ -1,9 +1,13 @@ package com.skyflow.utils; public class Constants { - public static String SECURE_PROTOCOL = "https"; - public static String DEV_DOMAIN = ".vault.skyflowapis.dev"; - public static String STAGE_DOMAIN = ".vault.skyflowapis.tech"; - public static String SANDBOX_DOMAIN = ".vault.skyflowapis-preview.com"; - public static String PROD_DOMAIN = ".vault.skyflowapis.com"; + public static final String SECURE_PROTOCOL = "https://"; + public static final String DEV_DOMAIN = ".vault.skyflowapis.dev"; + public static final String STAGE_DOMAIN = ".vault.skyflowapis.tech"; + public static final String SANDBOX_DOMAIN = ".vault.skyflowapis-preview.com"; + public static final String PROD_DOMAIN = ".vault.skyflowapis.com"; + public static final String PKCS8_PRIVATE_HEADER = "-----BEGIN PRIVATE KEY-----"; + public static final String PKCS8_PRIVATE_FOOTER = "-----END PRIVATE KEY-----"; + public static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; + public static final String SIGNED_DATA_TOKEN_PREFIX = "signed_token_"; } diff --git a/v2/src/main/java/com/skyflow/utils/Utils.java b/v2/src/main/java/com/skyflow/utils/Utils.java index a1698394..c3ddf355 100644 --- a/v2/src/main/java/com/skyflow/utils/Utils.java +++ b/v2/src/main/java/com/skyflow/utils/Utils.java @@ -2,8 +2,18 @@ import com.skyflow.config.Credentials; import com.skyflow.enums.ENV; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.auth.HttpBearerAuth; +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.BearerToken; +import org.apache.commons.codec.binary.Base64; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; public class Utils { public static String getVaultURL(String clusterId, ENV env) { @@ -27,11 +37,75 @@ public static String getVaultURL(String clusterId, ENV env) { return sb.toString(); } - public static void updateBearerTokenIfExpired(ApiClient apiClient, Credentials credentials) { - HttpBearerAuth Bearer = (HttpBearerAuth) apiClient.getAuthentication("Bearer"); - // check validity of bearer token - // String token = Bearer.getBearerToken(); - // generate bearer token, set in ApiClient if expired or null - Bearer.setBearerToken("BEARER_TOKEN"); + public static String generateBearerToken(Credentials credentials) throws SkyflowException { + if (credentials.getPath() != null) { + return BearerToken.builder() + .setCredentials(new File(credentials.getPath())) + .setRoles(credentials.getRoles()) + .setCtx(credentials.getContext()) + .build() + .getBearerToken(); + } else if (credentials.getCredentialsString() != null) { + return BearerToken.builder() + .setCredentials(credentials.getCredentialsString()) + .setRoles(credentials.getRoles()) + .setCtx(credentials.getContext()) + .build() + .getBearerToken(); + } else { + return credentials.getToken(); + } + } + + public static PrivateKey getPrivateKeyFromPem(String pemKey) throws SkyflowException { + String PKCS8PrivateHeader = Constants.PKCS8_PRIVATE_HEADER; + String PKCS8PrivateFooter = Constants.PKCS8_PRIVATE_FOOTER; + + String privateKeyContent = pemKey; + PrivateKey privateKey = null; + + if (pemKey.contains(PKCS8PrivateHeader)) { + privateKeyContent = privateKeyContent.replace(PKCS8PrivateHeader, ""); + privateKeyContent = privateKeyContent.replace(PKCS8PrivateFooter, ""); + privateKeyContent = privateKeyContent.replace("\n", ""); + privateKeyContent = privateKeyContent.replace("\r\n", ""); + privateKey = parsePkcs8PrivateKey(Base64.decodeBase64(privateKeyContent)); + } else { + // display error log and throw error + } + return privateKey; + } + + public static String getBaseURL(String url) throws MalformedURLException { + URL parsedUrl = new URL(url); + String protocol = parsedUrl.getProtocol(); + String host = parsedUrl.getHost(); + return new StringBuilder(protocol).append("://").append(host).toString(); + } + + public static void verifyCredentials(Credentials credentials) throws SkyflowException { + int nonNullMembers = 0; + if (credentials.getPath() != null) nonNullMembers++; + if (credentials.getCredentialsString() != null) nonNullMembers++; + if (credentials.getToken() != null) nonNullMembers++; + + if (nonNullMembers != 1) { + throw new SkyflowException("only one of tokens, path, and credentialsString is allowed"); + } + } + + private static PrivateKey parsePkcs8PrivateKey(byte[] pkcs8Bytes) throws SkyflowException { + KeyFactory keyFactory; + PrivateKey privateKey = null; + try { + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8Bytes); + keyFactory = KeyFactory.getInstance("RSA"); + privateKey = keyFactory.generatePrivate(keySpec); + } catch (NoSuchAlgorithmException e) { + // display error log and throw error + } catch (InvalidKeySpecException e) { + // display error log and throw error + } + return privateKey; } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index 9810eeb7..704ab54b 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -3,8 +3,11 @@ import com.skyflow.VaultClient; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.auth.HttpBearerAuth; import com.skyflow.generated.rest.models.V1DetokenizePayload; import com.skyflow.generated.rest.models.V1DetokenizeResponse; +import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Utils; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.InsertResponse; @@ -16,6 +19,8 @@ public final class VaultController extends VaultClient { private AuditController auditController; private BinLookupController binLookupController; + private String token; + public VaultController(VaultConfig vaultConfig, Credentials credentials) { super(vaultConfig, credentials); this.auditController = null; @@ -28,10 +33,9 @@ public InsertResponse insert(InsertRequest insertRequest) { } public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) { - System.out.println(super.getVaultConfig()); V1DetokenizeResponse result = null; try { - Utils.updateBearerTokenIfExpired(super.getApiClient(), super.getFinalCredentials()); + setBearerToken(); V1DetokenizePayload payload = detokenizeRequest.getDetokenizePayload(); result = super.getTokensApi().recordServiceDetokenize(super.getVaultConfig().getVaultId(), payload); } catch (Exception e) { @@ -84,4 +88,13 @@ public DetectController detect() { } return this.detectController; } + + private void setBearerToken() throws SkyflowException { + Utils.verifyCredentials(super.getFinalCredentials()); + if (token == null || Token.isExpired(token)) { + token = Utils.generateBearerToken(super.getFinalCredentials()); + } + HttpBearerAuth Bearer = (HttpBearerAuth) super.getApiClient().getAuthentication("Bearer"); + Bearer.setBearerToken(token); + } } From 5ad62c7f759100602d1221c7b44cb4812d0e4e90 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 7 Oct 2024 18:44:25 +0530 Subject: [PATCH 013/126] SK-1665 Generate and integrate Data API code --- .../skyflow/generated/rest/ApiCallback.java | 62 + .../com/skyflow/generated/rest/ApiClient.java | 1615 +++++++++++++++ .../skyflow/generated/rest/ApiException.java | 167 ++ .../skyflow/generated/rest/ApiResponse.java | 76 + .../skyflow/generated/rest/Configuration.java | 41 + .../rest/GzipRequestInterceptor.java | 85 + .../java/com/skyflow/generated/rest/JSON.java | 440 +++++ .../java/com/skyflow/generated/rest/Pair.java | 57 + .../generated/rest/ProgressRequestBody.java | 73 + .../generated/rest/ProgressResponseBody.java | 70 + .../generated/rest/ServerConfiguration.java | 72 + .../generated/rest/ServerVariable.java | 37 + .../skyflow/generated/rest/StringUtil.java | 83 + .../skyflow/generated/rest/api/AuditApi.java | 466 +++++ .../generated/rest/api/AuthenticationApi.java | 216 ++ .../generated/rest/api/BinLookupApi.java | 208 ++ .../skyflow/generated/rest/api/QueryApi.java | 218 +++ .../generated/rest/api/RecordsApi.java | 1730 +++++++++++++++++ .../skyflow/generated/rest/api/TokensApi.java | 361 ++++ .../generated/rest/auth/ApiKeyAuth.java | 80 + .../generated/rest/auth/Authentication.java | 36 + .../generated/rest/auth/HttpBasicAuth.java | 55 + .../generated/rest/auth/HttpBearerAuth.java | 75 + .../rest/models/AbstractOpenApiSchema.java | 146 ++ .../models/AuditEventAuditResourceType.java | 134 ++ .../rest/models/AuditEventContext.java | 530 +++++ .../generated/rest/models/AuditEventData.java | 205 ++ .../rest/models/AuditEventHTTPInfo.java | 234 +++ .../rest/models/BatchRecordMethod.java | 84 + .../rest/models/ContextAccessType.java | 80 + .../rest/models/ContextAuthMode.java | 82 + .../DetokenizeRecordResponseValueType.java | 92 + .../rest/models/GooglerpcStatus.java | 272 +++ .../generated/rest/models/ProtobufAny.java | 286 +++ .../models/QueryServiceExecuteQueryBody.java | 205 ++ .../RecordServiceBatchOperationBody.java | 284 +++ .../RecordServiceBulkDeleteRecordBody.java | 216 ++ .../models/RecordServiceInsertRecordBody.java | 339 ++++ .../models/RecordServiceUpdateRecordBody.java | 264 +++ .../rest/models/RedactionEnumREDACTION.java | 82 + .../rest/models/RequestActionType.java | 110 ++ .../rest/models/V1AuditAfterOptions.java | 234 +++ .../rest/models/V1AuditEventResponse.java | 291 +++ .../rest/models/V1AuditResponse.java | 258 +++ .../rest/models/V1AuditResponseEvent.java | 367 ++++ .../models/V1AuditResponseEventRequest.java | 456 +++++ .../rest/models/V1BINListRequest.java | 305 +++ .../rest/models/V1BINListResponse.java | 227 +++ .../skyflow/generated/rest/models/V1BYOT.java | 80 + .../rest/models/V1BatchOperationResponse.java | 245 +++ .../generated/rest/models/V1BatchRecord.java | 458 +++++ .../models/V1BulkDeleteRecordResponse.java | 216 ++ .../rest/models/V1BulkGetRecordResponse.java | 227 +++ .../skyflow/generated/rest/models/V1Card.java | 437 +++++ .../rest/models/V1DeleteFileResponse.java | 231 +++ .../rest/models/V1DeleteRecordResponse.java | 231 +++ .../rest/models/V1DetokenizePayload.java | 279 +++ .../models/V1DetokenizeRecordRequest.java | 236 +++ .../models/V1DetokenizeRecordResponse.java | 294 +++ .../rest/models/V1DetokenizeResponse.java | 227 +++ .../generated/rest/models/V1FieldRecords.java | 228 +++ .../rest/models/V1FileAVScanStatus.java | 92 + .../rest/models/V1GetAuthTokenRequest.java | 359 ++++ .../rest/models/V1GetAuthTokenResponse.java | 234 +++ .../models/V1GetFileScanStatusResponse.java | 207 ++ .../rest/models/V1GetQueryResponse.java | 227 +++ .../rest/models/V1InsertRecordResponse.java | 227 +++ .../generated/rest/models/V1MemberType.java | 80 + .../rest/models/V1RecordMetaProperties.java | 231 +++ .../rest/models/V1TokenizePayload.java | 227 +++ .../rest/models/V1TokenizeRecordRequest.java | 234 +++ .../rest/models/V1TokenizeRecordResponse.java | 205 ++ .../rest/models/V1TokenizeResponse.java | 227 +++ .../rest/models/V1UpdateRecordResponse.java | 231 +++ .../rest/models/V1VaultFieldMapping.java | 263 +++ .../rest/models/V1VaultSchemaConfig.java | 265 +++ 76 files changed, 18804 insertions(+) create mode 100644 v2/src/main/java/com/skyflow/generated/rest/ApiCallback.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/ApiClient.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/ApiException.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/ApiResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/Configuration.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/JSON.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/Pair.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/ServerConfiguration.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/ServerVariable.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/StringUtil.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/api/AuditApi.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/api/QueryApi.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/api/RecordsApi.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/api/TokensApi.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/auth/Authentication.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/AuditEventData.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/RequestActionType.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1BYOT.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1Card.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1MemberType.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java create mode 100644 v2/src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/ApiCallback.java b/v2/src/main/java/com/skyflow/generated/rest/ApiCallback.java new file mode 100644 index 00000000..84a241d3 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/ApiCallback.java @@ -0,0 +1,62 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API download processing. + * + * @param bytesRead bytes Read + * @param contentLength content length of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/ApiClient.java b/v2/src/main/java/com/skyflow/generated/rest/ApiClient.java new file mode 100644 index 00000000..bb0391a4 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/ApiClient.java @@ -0,0 +1,1615 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest; + +import okhttp3.*; +import okhttp3.internal.http.HttpMethod; +import okhttp3.internal.tls.OkHostnameVerifier; +import okhttp3.logging.HttpLoggingInterceptor; +import okhttp3.logging.HttpLoggingInterceptor.Level; +import okio.Buffer; +import okio.BufferedSink; +import okio.Okio; + +import javax.net.ssl.*; +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; +import java.nio.file.Paths; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.text.DateFormat; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.skyflow.generated.rest.auth.Authentication; +import com.skyflow.generated.rest.auth.HttpBasicAuth; +import com.skyflow.generated.rest.auth.HttpBearerAuth; +import com.skyflow.generated.rest.auth.ApiKeyAuth; + +/** + *

ApiClient class.

+ */ +public class ApiClient { + + private String basePath = "https://identifier.vault.skyflowapis.com"; + protected List servers = new ArrayList(Arrays.asList( + new ServerConfiguration( + "https://identifier.vault.skyflowapis.com", + "Production", + new HashMap() + ), + new ServerConfiguration( + "https://identifier.vault.skyflowapis-preview.com", + "Sandbox", + new HashMap() + ) + )); + protected Integer serverIndex = 0; + protected Map serverVariables = null; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private Map defaultCookieMap = new HashMap(); + private String tempFolderPath = null; + + private Map authentications; + + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; + + private InputStream sslCaCert; + private boolean verifyingSsl; + private KeyManager[] keyManagers; + + private OkHttpClient httpClient; + private JSON json; + + private HttpLoggingInterceptor loggingInterceptor; + + /** + * Basic constructor for ApiClient + */ + public ApiClient() { + init(); + initHttpClient(); + + // Setup authentications (key: authentication name, value: authentication). + authentications.put("Bearer", new HttpBearerAuth("bearer")); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Basic constructor with custom OkHttpClient + * + * @param client a {@link okhttp3.OkHttpClient} object + */ + public ApiClient(OkHttpClient client) { + init(); + + httpClient = client; + + // Setup authentications (key: authentication name, value: authentication). + authentications.put("Bearer", new HttpBearerAuth("bearer")); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + private void initHttpClient() { + initHttpClient(Collections.emptyList()); + } + + private void initHttpClient(List interceptors) { + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + builder.addNetworkInterceptor(getProgressInterceptor()); + for (Interceptor interceptor: interceptors) { + builder.addInterceptor(interceptor); + } + + httpClient = builder.build(); + } + + private void init() { + verifyingSsl = true; + + json = new JSON(); + + // Set default User-Agent. + setUserAgent("OpenAPI-Generator/v1/java"); + + authentications = new HashMap(); + } + + /** + * Get base path + * + * @return Base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set base path + * + * @param basePath Base path of the URL (e.g https://identifier.vault.skyflowapis.com + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + this.serverIndex = null; + return this; + } + + public List getServers() { + return servers; + } + + public ApiClient setServers(List servers) { + this.servers = servers; + return this; + } + + public Integer getServerIndex() { + return serverIndex; + } + + public ApiClient setServerIndex(Integer serverIndex) { + this.serverIndex = serverIndex; + return this; + } + + public Map getServerVariables() { + return serverVariables; + } + + public ApiClient setServerVariables(Map serverVariables) { + this.serverVariables = 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 + * + * @return JSON object + */ + public JSON getJSON() { + return json; + } + + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + + /** + *

Getter for the field keyManagers.

+ * + * @return an array of {@link javax.net.ssl.KeyManager} objects + */ + public KeyManager[] getKeyManagers() { + return keyManagers; + } + + /** + * Configure client keys to use for authorization in an SSL session. + * Use null to reset to default. + * + * @param managers The KeyManagers to use + * @return ApiClient + */ + public ApiClient setKeyManagers(KeyManager[] managers) { + this.keyManagers = managers; + applySslSettings(); + return this; + } + + /** + *

Getter for the field dateFormat.

+ * + * @return a {@link java.text.DateFormat} object + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + *

Setter for the field dateFormat.

+ * + * @param dateFormat a {@link java.text.DateFormat} object + * @return a {@link com.skyflow.generated.rest.ApiClient} object + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + JSON.setDateFormat(dateFormat); + return this; + } + + /** + *

Set SqlDateFormat.

+ * + * @param dateFormat a {@link java.text.DateFormat} object + * @return a {@link com.skyflow.generated.rest.ApiClient} object + */ + public ApiClient setSqlDateFormat(DateFormat dateFormat) { + JSON.setSqlDateFormat(dateFormat); + return this; + } + + /** + *

Set OffsetDateTimeFormat.

+ * + * @param dateFormat a {@link java.time.format.DateTimeFormatter} object + * @return a {@link com.skyflow.generated.rest.ApiClient} object + */ + public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + JSON.setOffsetDateTimeFormat(dateFormat); + return this; + } + + /** + *

Set LocalDateFormat.

+ * + * @param dateFormat a {@link java.time.format.DateTimeFormatter} object + * @return a {@link com.skyflow.generated.rest.ApiClient} object + */ + public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { + JSON.setLocalDateFormat(dateFormat); + return this; + } + + /** + *

Set LenientOnJson.

+ * + * @param lenientOnJson a boolean + * @return a {@link com.skyflow.generated.rest.ApiClient} object + */ + public ApiClient setLenientOnJson(boolean lenientOnJson) { + JSON.setLenientOnJson(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 access token for the first Bearer authentication. + * @param bearerToken Bearer token + */ + public void setBearerToken(String bearerToken) { + setBearerToken(() -> bearerToken); + } + + /** + * Helper method to set the supplier of access tokens for Bearer authentication. + * + * @param tokenSupplier The supplier of bearer tokens + */ + public void setBearerToken(Supplier tokenSupplier) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(tokenSupplier); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + /** + * 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). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Add a default cookie. + * + * @param key The cookie's key + * @param value The cookie's value + * @return ApiClient + */ + public ApiClient addDefaultCookie(String key, String value) { + defaultCookieMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); + } else { + final OkHttpClient.Builder builder = httpClient.newBuilder(); + builder.interceptors().remove(loggingInterceptor); + httpClient = builder.build(); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default temporary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the temporary folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.connectTimeoutMillis(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + /** + * Get read timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getReadTimeout() { + return httpClient.readTimeoutMillis(); + } + + /** + * Sets the read timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param readTimeout read timeout in milliseconds + * @return Api client + */ + public ApiClient setReadTimeout(int readTimeout) { + httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + /** + * Get write timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getWriteTimeout() { + return httpClient.writeTimeoutMillis(); + } + + /** + * Sets the write timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param writeTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setWriteTimeout(int writeTimeout) { + httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) { + //Serialize to json string and remove the " enclosing characters + String jsonStr = JSON.serialize(param); + return jsonStr.substring(1, jsonStr.length() - 1); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection) param) { + if (b.length() > 0) { + b.append(","); + } + b.append(o); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Formats the specified query parameter to a list containing a single {@code Pair} object. + * + * Note that {@code value} must not be a collection. + * + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list containing a single {@code Pair} object. + */ + public List parameterToPair(String name, Object value) { + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null || value instanceof Collection) { + return params; + } + + params.add(new Pair(name, parameterToString(value))); + return params; + } + + /** + * Formats the specified collection query parameters to a list of {@code Pair} objects. + * + * Note that the values of each of the returned Pair objects are percent-encoded. + * + * @param collectionFormat The collection format of the parameter. + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list of {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Collection value) { + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null || value.isEmpty()) { + return params; + } + + // create the params based on the collection format + if ("multi".equals(collectionFormat)) { + for (Object item : value) { + params.add(new Pair(name, escapeString(parameterToString(item)))); + } + return params; + } + + // collectionFormat is assumed to be "csv" by default + String delimiter = ","; + + // escape all delimiters except commas, which are URI reserved + // characters + if ("ssv".equals(collectionFormat)) { + delimiter = escapeString(" "); + } else if ("tsv".equals(collectionFormat)) { + delimiter = escapeString("\t"); + } else if ("pipes".equals(collectionFormat)) { + delimiter = escapeString("|"); + } + + StringBuilder sb = new StringBuilder(); + for (Object item : value) { + sb.append(delimiter); + sb.append(escapeString(parameterToString(item))); + } + + params.add(new Pair(name, sb.substring(delimiter.length()))); + + return params; + } + + /** + * Formats the specified free-form query parameters to a list of {@code Pair} objects. + * + * @param value The free-form query parameters. + * @return A list of {@code Pair} objects. + */ + public List freeFormParameterToPairs(Object value) { + List params = new ArrayList<>(); + + // preconditions + if (value == null || !(value instanceof Map )) { + return params; + } + + final Map valuesMap = (Map) value; + + for (Map.Entry entry : valuesMap.entrySet()) { + params.add(new Pair(entry.getKey(), parameterToString(entry.getValue()))); + } + + return params; + } + + + /** + * Formats the specified collection path parameter to a string value. + * + * @param collectionFormat The collection format of the parameter. + * @param value The value of the parameter. + * @return String representation of the parameter + */ + public String collectionPathParameterToString(String collectionFormat, Collection value) { + // create the value based on the collection format + if ("multi".equals(collectionFormat)) { + // not valid for path params + return parameterToString(value); + } + + // collectionFormat is assumed to be "csv" by default + String delimiter = ","; + + if ("ssv".equals(collectionFormat)) { + delimiter = " "; + } else if ("tsv".equals(collectionFormat)) { + delimiter = "\t"; + } else if ("pipes".equals(collectionFormat)) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : value) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + return sb.substring(delimiter.length()); + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * "* / *" is also default to JSON + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; + return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * returns null. If it matches "any", JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return null; + } + + if (contentTypes[0].equals("*/*")) { + return "application/json"; + } + + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws com.skyflow.generated.rest.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") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) { + return null; + } + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (isJsonMime(contentType)) { + return JSON.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws com.skyflow.generated.rest.ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create((File) obj, MediaType.parse(contentType)); + } else if ("text/plain".equals(contentType) && obj instanceof String) { + return RequestBody.create((String) obj, MediaType.parse(contentType)); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = JSON.serialize(obj); + } else { + content = null; + } + return RequestBody.create(content, MediaType.parse(contentType)); + } else if (obj instanceof String) { + return RequestBody.create((String) obj, MediaType.parse(contentType)); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws com.skyflow.generated.rest.ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @return Prepared file for the download + * @throws java.io.IOException If fail to prepare file for download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // Files.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return Files.createTempFile(prefix, suffix).toFile(); + else + return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @return ApiResponse<T> + * @throws com.skyflow.generated.rest.ApiException If fail to execute the call + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @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 com.skyflow.generated.rest.ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + * @see #execute(Call, Type) + */ + @SuppressWarnings("unchecked") + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Call call, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Call call, Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } catch (Exception e) { + callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @return Type + * @throws com.skyflow.generated.rest.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 { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + if (response.body() != null) { + try { + response.body().close(); + } catch (Exception e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param baseUrl The base URL + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param callback Callback for upload/download progress + * @return The HTTP call + * @throws com.skyflow.generated.rest.ApiException If fail to serialize the request body object + */ + public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); + + return httpClient.newCall(request); + } + + /** + * Build an HTTP request with the given options. + * + * @param baseUrl The base URL + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param callback Callback for upload/download progress + * @return The HTTP request + * @throws com.skyflow.generated.rest.ApiException If fail to serialize the request body object + */ + public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); + + // prepare HTTP request body + RequestBody reqBody; + String contentType = headerParams.get("Content-Type"); + String contentTypePure = contentType; + if (contentTypePure != null && contentTypePure.contains(";")) { + contentTypePure = contentType.substring(0, contentType.indexOf(";")); + } + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentTypePure)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentTypePure)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create("", contentType == null ? null : MediaType.parse(contentType)); + } + } else { + reqBody = serialize(body, contentType); + } + + 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)); + processHeaderParams(headerParams, reqBuilder); + processCookieParams(cookieParams, reqBuilder); + + // Associate callback with request (if not null) so interceptor can + // access it when creating ProgressResponseBody + reqBuilder.tag(callback); + + Request request = null; + + if (callback != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return request; + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param baseUrl The base URL + * @param path The sub path + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @return The full URL + */ + public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { + final StringBuilder url = new StringBuilder(); + if (baseUrl != null) { + url.append(baseUrl).append(path); + } else { + String baseURL; + if (serverIndex != null) { + if (serverIndex < 0 || serverIndex >= servers.size()) { + throw new ArrayIndexOutOfBoundsException(String.format( + "Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size() + )); + } + baseURL = servers.get(serverIndex).URL(serverVariables); + } else { + baseURL = basePath; + } + url.append(baseURL).append(path); + } + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { + String prefix = url.toString().contains("?") ? "&" : "?"; + for (Pair param : collectionQueryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + // collection query parameter value already escaped as part of parameterToPairs + url.append(escapeString(param.getName())).append("=").append(value); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the form of Map + * @param reqBuilder Request.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Set cookie parameters to the request builder, including default cookies. + * + * @param cookieParams Cookie parameters in the form of Map + * @param reqBuilder Request.Builder + */ + public void processCookieParams(Map cookieParams, Request.Builder reqBuilder) { + for (Entry param : cookieParams.entrySet()) { + reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); + } + for (Entry param : defaultCookieMap.entrySet()) { + if (!cookieParams.containsKey(param.getKey())) { + reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); + } + } + } + + /** + * 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 com.skyflow.generated.rest.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. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + addPartToMultiPartBuilder(mpBuilder, param.getKey(), file); + } else if (param.getValue() instanceof List) { + List list = (List) param.getValue(); + for (Object item: list) { + if (item instanceof File) { + addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item); + } else { + addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); + } + } + } else { + addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Add a Content-Disposition Header for the given key and file to the MultipartBody Builder. + * + * @param mpBuilder MultipartBody.Builder + * @param key The key of the Header element + * @param file The file to add to the Header + */ + private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, File file) { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); + } + + /** + * Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder. + * + * @param mpBuilder MultipartBody.Builder + * @param key The key of the Header element + * @param obj The complex object to add to the Header + */ + private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) { + RequestBody requestBody; + if (obj instanceof String) { + requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain")); + } else { + String content; + if (obj != null) { + content = JSON.serialize(obj); + } else { + content = null; + } + requestBody = RequestBody.create(content, MediaType.parse("application/json")); + } + + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""); + mpBuilder.addPart(partHeaders, requestBody); + } + + /** + * Get network interceptor to add it to the httpClient to track download progress for + * async requests. + */ + private Interceptor getProgressInterceptor() { + return new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + final Request request = chain.request(); + final Response originalResponse = chain.proceed(request); + if (request.tag() instanceof ApiCallback) { + final ApiCallback callback = (ApiCallback) request.tag(); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), callback)) + .build(); + } + return originalResponse; + } + }; + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + TrustManager[] trustManagers; + HostnameVerifier hostnameVerifier; + if (!verifyingSsl) { + trustManagers = new TrustManager[]{ + new X509TrustManager() { + @Override + public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[]{}; + } + } + }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + } else { + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + + if (sslCaCert == null) { + trustManagerFactory.init((KeyStore) null); + } else { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + (index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + trustManagerFactory.init(caKeyStore); + } + trustManagers = trustManagerFactory.getTrustManagers(); + hostnameVerifier = OkHostnameVerifier.INSTANCE; + } + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient = httpClient.newBuilder() + .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) + .hostnameVerifier(hostnameVerifier) + .build(); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } + + /** + * Convert the HTTP request body to a string. + * + * @param requestBody The HTTP request object + * @return The string representation of the HTTP request body + * @throws com.skyflow.generated.rest.ApiException If fail to serialize the request body object into a string + */ + private String requestBodyToString(RequestBody requestBody) throws ApiException { + if (requestBody != null) { + try { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return buffer.readUtf8(); + } catch (final IOException e) { + throw new ApiException(e); + } + } + + // empty http request body + return ""; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/ApiException.java b/v2/src/main/java/com/skyflow/generated/rest/ApiException.java new file mode 100644 index 00000000..d10c995e --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/ApiException.java @@ -0,0 +1,167 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest; + +import java.util.Map; +import java.util.List; + + +/** + *

ApiException class.

+ */ +@SuppressWarnings("serial") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.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/v2/src/main/java/com/skyflow/generated/rest/ApiResponse.java b/v2/src/main/java/com/skyflow/generated/rest/ApiResponse.java new file mode 100644 index 00000000..d3cdb698 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/ApiResponse.java @@ -0,0 +1,76 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + *

Constructor for ApiResponse.

+ * + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + *

Constructor for ApiResponse.

+ * + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + /** + *

Get the status code.

+ * + * @return the status code + */ + public int getStatusCode() { + return statusCode; + } + + /** + *

Get the headers.

+ * + * @return a {@link java.util.Map} of headers + */ + public Map> getHeaders() { + return headers; + } + + /** + *

Get the data.

+ * + * @return the data + */ + public T getData() { + return data; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/Configuration.java b/v2/src/main/java/com/skyflow/generated/rest/Configuration.java new file mode 100644 index 00000000..6b12e8bb --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/Configuration.java @@ -0,0 +1,41 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class Configuration { + public static final String VERSION = "v1"; + + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * 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() { + return defaultApiClient; + } + + /** + * 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 = apiClient; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java b/v2/src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java new file mode 100644 index 00000000..2b69f358 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java @@ -0,0 +1,85 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest; + +import okhttp3.*; +import okio.Buffer; +import okio.BufferedSink; +import okio.GzipSink; +import okio.Okio; + +import java.io.IOException; + +/** + * Encodes request bodies using gzip. + * + * Taken from https://github.com/square/okhttp/issues/350 + */ +class GzipRequestInterceptor implements Interceptor { + @Override + public Response intercept(Chain chain) throws IOException { + Request originalRequest = chain.request(); + if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) { + return chain.proceed(originalRequest); + } + + Request compressedRequest = originalRequest.newBuilder() + .header("Content-Encoding", "gzip") + .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))) + .build(); + return chain.proceed(compressedRequest); + } + + private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return new RequestBody() { + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() { + return buffer.size(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + sink.write(buffer.snapshot()); + } + }; + } + + private RequestBody gzip(final RequestBody body) { + return new RequestBody() { + @Override + public MediaType contentType() { + return body.contentType(); + } + + @Override + public long contentLength() { + return -1; // We don't know the compressed length in advance! + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); + body.writeTo(gzipSink); + gzipSink.close(); + } + }; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/JSON.java b/v2/src/main/java/com/skyflow/generated/rest/JSON.java new file mode 100644 index 00000000..8e6e8375 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/JSON.java @@ -0,0 +1,440 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonElement; +import io.gsonfire.GsonFireBuilder; +import io.gsonfire.TypeSelector; + +import okio.ByteString; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.ParsePosition; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.Locale; +import java.util.Map; +import java.util.HashMap; + +/* + * A JSON utility class + * + * NOTE: in the future, this class may be converted to static, which may break + * backward-compatibility + */ +public class JSON { + private static Gson gson; + private static boolean isLenientOnJson = false; + private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); + private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); + private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); + private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); + + @SuppressWarnings("unchecked") + public static GsonBuilder createGson() { + GsonFireBuilder fireBuilder = new GsonFireBuilder() + ; + GsonBuilder builder = fireBuilder.createGsonBuilder(); + return builder; + } + + private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { + JsonElement element = readElement.getAsJsonObject().get(discriminatorField); + if (null == element) { + throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); + } + return element.getAsString(); + } + + /** + * Returns the Java class that implements the OpenAPI schema for the specified discriminator value. + * + * @param classByDiscriminatorValue The map of discriminator values to Java classes. + * @param discriminatorValue The value of the OpenAPI discriminator in the input data. + * @return The Java class that implements the OpenAPI schema + */ + private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { + Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue); + if (null == clazz) { + throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); + } + return clazz; + } + + static { + GsonBuilder gsonBuilder = createGson(); + gsonBuilder.registerTypeAdapter(Date.class, dateTypeAdapter); + gsonBuilder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); + gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); + gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); + gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.AuditEventContext.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.AuditEventData.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.AuditEventHTTPInfo.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.GooglerpcStatus.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.ProtobufAny.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.QueryServiceExecuteQueryBody.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.RecordServiceBatchOperationBody.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.RecordServiceBulkDeleteRecordBody.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.RecordServiceInsertRecordBody.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.RecordServiceUpdateRecordBody.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1AuditAfterOptions.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1AuditEventResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1AuditResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1AuditResponseEvent.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1AuditResponseEventRequest.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1BINListRequest.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1BINListResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1BatchOperationResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1BatchRecord.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1BulkDeleteRecordResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1BulkGetRecordResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1Card.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1DeleteFileResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1DeleteRecordResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1DetokenizePayload.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1DetokenizeRecordRequest.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1DetokenizeRecordResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1DetokenizeResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1FieldRecords.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1GetFileScanStatusResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1GetQueryResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1InsertRecordResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1RecordMetaProperties.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1TokenizePayload.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1TokenizeRecordRequest.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1TokenizeRecordResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1TokenizeResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1UpdateRecordResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1VaultFieldMapping.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1VaultSchemaConfig.CustomTypeAdapterFactory()); + gson = gsonBuilder.create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public static Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public static void setGson(Gson gson) { + JSON.gson = gson; + } + + public static void setLenientOnJson(boolean lenientOnJson) { + isLenientOnJson = lenientOnJson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public static String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize into + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public static T deserialize(String body, Type returnType) { + try { + if (isLenientOnJson) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + if (returnType.equals(String.class)) { + return (T) body; + } else { + throw (e); + } + } + } + + /** + * Gson TypeAdapter for Byte Array type + */ + public static class ByteArrayAdapter extends TypeAdapter { + + @Override + public void write(JsonWriter out, byte[] value) throws IOException { + if (value == null) { + out.nullValue(); + } else { + out.value(ByteString.of(value).base64()); + } + } + + @Override + public byte[] read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String bytesAsBase64 = in.nextString(); + ByteString byteString = ByteString.decodeBase64(bytesAsBase64); + return byteString.toByteArray(); + } + } + } + + /** + * Gson TypeAdapter for JSR310 OffsetDateTime type + */ + public static class OffsetDateTimeTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public OffsetDateTimeTypeAdapter() { + this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); + } + + public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, OffsetDateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public OffsetDateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + if (date.endsWith("+0000")) { + date = date.substring(0, date.length()-5) + "Z"; + } + return OffsetDateTime.parse(date, formatter); + } + } + } + + /** + * Gson TypeAdapter for JSR310 LocalDate type + */ + public static class LocalDateTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public LocalDateTypeAdapter() { + this(DateTimeFormatter.ISO_LOCAL_DATE); + } + + public LocalDateTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return LocalDate.parse(date, formatter); + } + } + } + + public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + offsetDateTimeTypeAdapter.setFormat(dateFormat); + } + + public static void setLocalDateFormat(DateTimeFormatter dateFormat) { + localDateTypeAdapter.setFormat(dateFormat); + } + + /** + * Gson TypeAdapter for java.sql.Date type + * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used + * (more efficient than SimpleDateFormat). + */ + public static class SqlDateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public SqlDateTypeAdapter() {} + + public SqlDateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, java.sql.Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = date.toString(); + } + out.value(value); + } + } + + @Override + public java.sql.Date read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return new java.sql.Date(dateFormat.parse(date).getTime()); + } + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } + } + + /** + * Gson TypeAdapter for java.util.Date type + * If the dateFormat is null, ISO8601Utils will be used. + */ + public static class DateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public DateTypeAdapter() {} + + public DateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = ISO8601Utils.format(date, true); + } + out.value(value); + } + } + + @Override + public Date read(JsonReader in) throws IOException { + try { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return dateFormat.parse(date); + } + return ISO8601Utils.parse(date, new ParsePosition(0)); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } catch (IllegalArgumentException e) { + throw new JsonParseException(e); + } + } + } + + public static void setDateFormat(DateFormat dateFormat) { + dateTypeAdapter.setFormat(dateFormat); + } + + public static void setSqlDateFormat(DateFormat dateFormat) { + sqlDateTypeAdapter.setFormat(dateFormat); + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/Pair.java b/v2/src/main/java/com/skyflow/generated/rest/Pair.java new file mode 100644 index 00000000..0f182d02 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/Pair.java @@ -0,0 +1,57 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) { + return; + } + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) { + return; + } + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) { + return false; + } + + return true; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java b/v2/src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java new file mode 100644 index 00000000..38d16e94 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java @@ -0,0 +1,73 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest; + +import okhttp3.MediaType; +import okhttp3.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + private final RequestBody requestBody; + + private final ApiCallback callback; + + public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) { + this.requestBody = requestBody; + this.callback = callback; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink bufferedSink = Okio.buffer(sink(sink)); + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + callback.onUploadProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java b/v2/src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java new file mode 100644 index 00000000..6bd61b5a --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java @@ -0,0 +1,70 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest; + +import okhttp3.MediaType; +import okhttp3.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + private final ResponseBody responseBody; + private final ApiCallback callback; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) { + this.responseBody = responseBody; + this.callback = callback; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/ServerConfiguration.java b/v2/src/main/java/com/skyflow/generated/rest/ServerConfiguration.java new file mode 100644 index 00000000..f91ef52d --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/ServerConfiguration.java @@ -0,0 +1,72 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest; + +import java.util.Map; + +/** + * Representing a Server configuration. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class ServerConfiguration { + public String URL; + public String description; + public Map variables; + + /** + * @param URL A URL to the target host. + * @param description A description of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + public ServerConfiguration(String URL, String description, Map variables) { + this.URL = URL; + this.description = description; + this.variables = variables; + } + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + public String URL(Map variables) { + String url = this.URL; + + // go through variables and replace placeholders + for (Map.Entry variable: this.variables.entrySet()) { + String name = variable.getKey(); + ServerVariable serverVariable = variable.getValue(); + String value = serverVariable.defaultValue; + + if (variables != null && variables.containsKey(name)) { + value = variables.get(name); + if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { + throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + "."); + } + } + url = url.replace("{" + name + "}", value); + } + return url; + } + + /** + * Format URL template using default server variables. + * + * @return Formatted URL. + */ + public String URL() { + return URL(null); + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/ServerVariable.java b/v2/src/main/java/com/skyflow/generated/rest/ServerVariable.java new file mode 100644 index 00000000..53b17180 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/ServerVariable.java @@ -0,0 +1,37 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest; + +import java.util.HashSet; + +/** + * Representing a Server Variable for server URL template substitution. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class ServerVariable { + public String description; + public String defaultValue; + public HashSet enumValues = null; + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + public ServerVariable(String description, String defaultValue, HashSet enumValues) { + this.description = description; + this.defaultValue = defaultValue; + this.enumValues = enumValues; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/StringUtil.java b/v2/src/main/java/com/skyflow/generated/rest/StringUtil.java new file mode 100644 index 00000000..433e15d7 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/StringUtil.java @@ -0,0 +1,83 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest; + +import java.util.Collection; +import java.util.Iterator; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/api/AuditApi.java b/v2/src/main/java/com/skyflow/generated/rest/api/AuditApi.java new file mode 100644 index 00000000..6b441971 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/api/AuditApi.java @@ -0,0 +1,466 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.api; + +import com.skyflow.generated.rest.ApiCallback; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.ApiException; +import com.skyflow.generated.rest.ApiResponse; +import com.skyflow.generated.rest.Configuration; +import com.skyflow.generated.rest.Pair; +import com.skyflow.generated.rest.ProgressRequestBody; +import com.skyflow.generated.rest.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import com.skyflow.generated.rest.models.GooglerpcStatus; +import com.skyflow.generated.rest.models.V1AuditResponse; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AuditApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public AuditApi() { + this(Configuration.getDefaultApiClient()); + } + + public AuditApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for auditServiceListAuditEvents + * @param filterOpsAccountID Resources with the specified account ID. (required) + * @param filterOpsContextChangeID ID for the audit event. (optional) + * @param filterOpsContextRequestID ID for the request that caused the event. (optional) + * @param filterOpsContextTraceID ID for the request set by the service that received the request. (optional) + * @param filterOpsContextSessionID ID for the session in which the request was sent. (optional) + * @param filterOpsContextActor Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. (optional) + * @param filterOpsContextActorType Type of member who sent the request. (optional, default to NONE) + * @param filterOpsContextAccessType Type of access for the request. (optional, default to ACCESS_NONE) + * @param filterOpsContextIpAddress IP Address of the client that made the request. (optional) + * @param filterOpsContextOrigin HTTP Origin request header (including scheme, hostname, and port) of the request. (optional) + * @param filterOpsContextAuthMode Authentication mode the `actor` used. (optional, default to AUTH_NONE) + * @param filterOpsContextJwtID ID of the JWT token. (optional) + * @param filterOpsContextBearerTokenContextID Embedded User Context. (optional) + * @param filterOpsParentAccountID Resources with the specified parent account ID. (optional) + * @param filterOpsWorkspaceID Resources with the specified workspace ID. (optional) + * @param filterOpsVaultID Resources with the specified vault ID. (optional) + * @param filterOpsResourceIDs Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\<resourceType\\>/\\<resourceID\\>\". For example, \"VAULT/12345, USER/67890\". (optional) + * @param filterOpsActionType Events with the specified action type. (optional, default to NONE) + * @param filterOpsResourceType Resources with the specified type. (optional, default to NONE_API) + * @param filterOpsTags Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\". (optional) + * @param filterOpsResponseCode HTTP response code of the request. (optional) + * @param filterOpsStartTime Start timestamp for the query, in SQL format. (optional) + * @param filterOpsEndTime End timestamp for the query, in SQL format. (optional) + * @param filterOpsApiName Name of the API called in the request. (optional) + * @param filterOpsResponseMessage Response message of the request. (optional) + * @param filterOpsHttpMethod HTTP method of the request. (optional) + * @param filterOpsHttpURI HTTP URI of the request. (optional) + * @param sortOpsSortBy Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\"). (optional) + * @param sortOpsOrderBy Ascending or descending ordering of results. (optional, default to ASCENDING) + * @param afterOpsTimestamp Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) + * @param afterOpsChangeID Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) + * @param limit Number of results to return. (optional, default to 25) + * @param offset Record position at which to start returning results. (optional, default to 0) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details +
+ + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call auditServiceListAuditEventsCall(String filterOpsAccountID, String filterOpsContextChangeID, String filterOpsContextRequestID, String filterOpsContextTraceID, String filterOpsContextSessionID, String filterOpsContextActor, String filterOpsContextActorType, String filterOpsContextAccessType, String filterOpsContextIpAddress, String filterOpsContextOrigin, String filterOpsContextAuthMode, String filterOpsContextJwtID, String filterOpsContextBearerTokenContextID, String filterOpsParentAccountID, String filterOpsWorkspaceID, String filterOpsVaultID, String filterOpsResourceIDs, String filterOpsActionType, String filterOpsResourceType, String filterOpsTags, Integer filterOpsResponseCode, String filterOpsStartTime, String filterOpsEndTime, String filterOpsApiName, String filterOpsResponseMessage, String filterOpsHttpMethod, String filterOpsHttpURI, String sortOpsSortBy, String sortOpsOrderBy, String afterOpsTimestamp, String afterOpsChangeID, Long limit, Long offset, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/v1/audit/events"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (filterOpsContextChangeID != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.changeID", filterOpsContextChangeID)); + } + + if (filterOpsContextRequestID != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.requestID", filterOpsContextRequestID)); + } + + if (filterOpsContextTraceID != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.traceID", filterOpsContextTraceID)); + } + + if (filterOpsContextSessionID != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.sessionID", filterOpsContextSessionID)); + } + + if (filterOpsContextActor != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.actor", filterOpsContextActor)); + } + + if (filterOpsContextActorType != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.actorType", filterOpsContextActorType)); + } + + if (filterOpsContextAccessType != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.accessType", filterOpsContextAccessType)); + } + + if (filterOpsContextIpAddress != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.ipAddress", filterOpsContextIpAddress)); + } + + if (filterOpsContextOrigin != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.origin", filterOpsContextOrigin)); + } + + if (filterOpsContextAuthMode != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.authMode", filterOpsContextAuthMode)); + } + + if (filterOpsContextJwtID != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.jwtID", filterOpsContextJwtID)); + } + + if (filterOpsContextBearerTokenContextID != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.bearerTokenContextID", filterOpsContextBearerTokenContextID)); + } + + if (filterOpsParentAccountID != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.parentAccountID", filterOpsParentAccountID)); + } + + if (filterOpsAccountID != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.accountID", filterOpsAccountID)); + } + + if (filterOpsWorkspaceID != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.workspaceID", filterOpsWorkspaceID)); + } + + if (filterOpsVaultID != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.vaultID", filterOpsVaultID)); + } + + if (filterOpsResourceIDs != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.resourceIDs", filterOpsResourceIDs)); + } + + if (filterOpsActionType != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.actionType", filterOpsActionType)); + } + + if (filterOpsResourceType != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.resourceType", filterOpsResourceType)); + } + + if (filterOpsTags != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.tags", filterOpsTags)); + } + + if (filterOpsResponseCode != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.responseCode", filterOpsResponseCode)); + } + + if (filterOpsStartTime != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.startTime", filterOpsStartTime)); + } + + if (filterOpsEndTime != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.endTime", filterOpsEndTime)); + } + + if (filterOpsApiName != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.apiName", filterOpsApiName)); + } + + if (filterOpsResponseMessage != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.responseMessage", filterOpsResponseMessage)); + } + + if (filterOpsHttpMethod != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.httpMethod", filterOpsHttpMethod)); + } + + if (filterOpsHttpURI != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.httpURI", filterOpsHttpURI)); + } + + if (sortOpsSortBy != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("sortOps.sortBy", sortOpsSortBy)); + } + + if (sortOpsOrderBy != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("sortOps.orderBy", sortOpsOrderBy)); + } + + if (afterOpsTimestamp != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("afterOps.timestamp", afterOpsTimestamp)); + } + + if (afterOpsChangeID != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("afterOps.changeID", afterOpsChangeID)); + } + + if (limit != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("limit", limit)); + } + + if (offset != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("offset", offset)); + } + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call auditServiceListAuditEventsValidateBeforeCall(String filterOpsAccountID, String filterOpsContextChangeID, String filterOpsContextRequestID, String filterOpsContextTraceID, String filterOpsContextSessionID, String filterOpsContextActor, String filterOpsContextActorType, String filterOpsContextAccessType, String filterOpsContextIpAddress, String filterOpsContextOrigin, String filterOpsContextAuthMode, String filterOpsContextJwtID, String filterOpsContextBearerTokenContextID, String filterOpsParentAccountID, String filterOpsWorkspaceID, String filterOpsVaultID, String filterOpsResourceIDs, String filterOpsActionType, String filterOpsResourceType, String filterOpsTags, Integer filterOpsResponseCode, String filterOpsStartTime, String filterOpsEndTime, String filterOpsApiName, String filterOpsResponseMessage, String filterOpsHttpMethod, String filterOpsHttpURI, String sortOpsSortBy, String sortOpsOrderBy, String afterOpsTimestamp, String afterOpsChangeID, Long limit, Long offset, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'filterOpsAccountID' is set + if (filterOpsAccountID == null) { + throw new ApiException("Missing the required parameter 'filterOpsAccountID' when calling auditServiceListAuditEvents(Async)"); + } + + return auditServiceListAuditEventsCall(filterOpsAccountID, filterOpsContextChangeID, filterOpsContextRequestID, filterOpsContextTraceID, filterOpsContextSessionID, filterOpsContextActor, filterOpsContextActorType, filterOpsContextAccessType, filterOpsContextIpAddress, filterOpsContextOrigin, filterOpsContextAuthMode, filterOpsContextJwtID, filterOpsContextBearerTokenContextID, filterOpsParentAccountID, filterOpsWorkspaceID, filterOpsVaultID, filterOpsResourceIDs, filterOpsActionType, filterOpsResourceType, filterOpsTags, filterOpsResponseCode, filterOpsStartTime, filterOpsEndTime, filterOpsApiName, filterOpsResponseMessage, filterOpsHttpMethod, filterOpsHttpURI, sortOpsSortBy, sortOpsOrderBy, afterOpsTimestamp, afterOpsChangeID, limit, offset, _callback); + + } + + /** + * List Audit Events + * Lists audit events that match query parameters. + * @param filterOpsAccountID Resources with the specified account ID. (required) + * @param filterOpsContextChangeID ID for the audit event. (optional) + * @param filterOpsContextRequestID ID for the request that caused the event. (optional) + * @param filterOpsContextTraceID ID for the request set by the service that received the request. (optional) + * @param filterOpsContextSessionID ID for the session in which the request was sent. (optional) + * @param filterOpsContextActor Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. (optional) + * @param filterOpsContextActorType Type of member who sent the request. (optional, default to NONE) + * @param filterOpsContextAccessType Type of access for the request. (optional, default to ACCESS_NONE) + * @param filterOpsContextIpAddress IP Address of the client that made the request. (optional) + * @param filterOpsContextOrigin HTTP Origin request header (including scheme, hostname, and port) of the request. (optional) + * @param filterOpsContextAuthMode Authentication mode the `actor` used. (optional, default to AUTH_NONE) + * @param filterOpsContextJwtID ID of the JWT token. (optional) + * @param filterOpsContextBearerTokenContextID Embedded User Context. (optional) + * @param filterOpsParentAccountID Resources with the specified parent account ID. (optional) + * @param filterOpsWorkspaceID Resources with the specified workspace ID. (optional) + * @param filterOpsVaultID Resources with the specified vault ID. (optional) + * @param filterOpsResourceIDs Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\<resourceType\\>/\\<resourceID\\>\". For example, \"VAULT/12345, USER/67890\". (optional) + * @param filterOpsActionType Events with the specified action type. (optional, default to NONE) + * @param filterOpsResourceType Resources with the specified type. (optional, default to NONE_API) + * @param filterOpsTags Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\". (optional) + * @param filterOpsResponseCode HTTP response code of the request. (optional) + * @param filterOpsStartTime Start timestamp for the query, in SQL format. (optional) + * @param filterOpsEndTime End timestamp for the query, in SQL format. (optional) + * @param filterOpsApiName Name of the API called in the request. (optional) + * @param filterOpsResponseMessage Response message of the request. (optional) + * @param filterOpsHttpMethod HTTP method of the request. (optional) + * @param filterOpsHttpURI HTTP URI of the request. (optional) + * @param sortOpsSortBy Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\"). (optional) + * @param sortOpsOrderBy Ascending or descending ordering of results. (optional, default to ASCENDING) + * @param afterOpsTimestamp Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) + * @param afterOpsChangeID Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) + * @param limit Number of results to return. (optional, default to 25) + * @param offset Record position at which to start returning results. (optional, default to 0) + * @return V1AuditResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1AuditResponse auditServiceListAuditEvents(String filterOpsAccountID, String filterOpsContextChangeID, String filterOpsContextRequestID, String filterOpsContextTraceID, String filterOpsContextSessionID, String filterOpsContextActor, String filterOpsContextActorType, String filterOpsContextAccessType, String filterOpsContextIpAddress, String filterOpsContextOrigin, String filterOpsContextAuthMode, String filterOpsContextJwtID, String filterOpsContextBearerTokenContextID, String filterOpsParentAccountID, String filterOpsWorkspaceID, String filterOpsVaultID, String filterOpsResourceIDs, String filterOpsActionType, String filterOpsResourceType, String filterOpsTags, Integer filterOpsResponseCode, String filterOpsStartTime, String filterOpsEndTime, String filterOpsApiName, String filterOpsResponseMessage, String filterOpsHttpMethod, String filterOpsHttpURI, String sortOpsSortBy, String sortOpsOrderBy, String afterOpsTimestamp, String afterOpsChangeID, Long limit, Long offset) throws ApiException { + ApiResponse localVarResp = auditServiceListAuditEventsWithHttpInfo(filterOpsAccountID, filterOpsContextChangeID, filterOpsContextRequestID, filterOpsContextTraceID, filterOpsContextSessionID, filterOpsContextActor, filterOpsContextActorType, filterOpsContextAccessType, filterOpsContextIpAddress, filterOpsContextOrigin, filterOpsContextAuthMode, filterOpsContextJwtID, filterOpsContextBearerTokenContextID, filterOpsParentAccountID, filterOpsWorkspaceID, filterOpsVaultID, filterOpsResourceIDs, filterOpsActionType, filterOpsResourceType, filterOpsTags, filterOpsResponseCode, filterOpsStartTime, filterOpsEndTime, filterOpsApiName, filterOpsResponseMessage, filterOpsHttpMethod, filterOpsHttpURI, sortOpsSortBy, sortOpsOrderBy, afterOpsTimestamp, afterOpsChangeID, limit, offset); + return localVarResp.getData(); + } + + /** + * List Audit Events + * Lists audit events that match query parameters. + * @param filterOpsAccountID Resources with the specified account ID. (required) + * @param filterOpsContextChangeID ID for the audit event. (optional) + * @param filterOpsContextRequestID ID for the request that caused the event. (optional) + * @param filterOpsContextTraceID ID for the request set by the service that received the request. (optional) + * @param filterOpsContextSessionID ID for the session in which the request was sent. (optional) + * @param filterOpsContextActor Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. (optional) + * @param filterOpsContextActorType Type of member who sent the request. (optional, default to NONE) + * @param filterOpsContextAccessType Type of access for the request. (optional, default to ACCESS_NONE) + * @param filterOpsContextIpAddress IP Address of the client that made the request. (optional) + * @param filterOpsContextOrigin HTTP Origin request header (including scheme, hostname, and port) of the request. (optional) + * @param filterOpsContextAuthMode Authentication mode the `actor` used. (optional, default to AUTH_NONE) + * @param filterOpsContextJwtID ID of the JWT token. (optional) + * @param filterOpsContextBearerTokenContextID Embedded User Context. (optional) + * @param filterOpsParentAccountID Resources with the specified parent account ID. (optional) + * @param filterOpsWorkspaceID Resources with the specified workspace ID. (optional) + * @param filterOpsVaultID Resources with the specified vault ID. (optional) + * @param filterOpsResourceIDs Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\<resourceType\\>/\\<resourceID\\>\". For example, \"VAULT/12345, USER/67890\". (optional) + * @param filterOpsActionType Events with the specified action type. (optional, default to NONE) + * @param filterOpsResourceType Resources with the specified type. (optional, default to NONE_API) + * @param filterOpsTags Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\". (optional) + * @param filterOpsResponseCode HTTP response code of the request. (optional) + * @param filterOpsStartTime Start timestamp for the query, in SQL format. (optional) + * @param filterOpsEndTime End timestamp for the query, in SQL format. (optional) + * @param filterOpsApiName Name of the API called in the request. (optional) + * @param filterOpsResponseMessage Response message of the request. (optional) + * @param filterOpsHttpMethod HTTP method of the request. (optional) + * @param filterOpsHttpURI HTTP URI of the request. (optional) + * @param sortOpsSortBy Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\"). (optional) + * @param sortOpsOrderBy Ascending or descending ordering of results. (optional, default to ASCENDING) + * @param afterOpsTimestamp Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) + * @param afterOpsChangeID Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) + * @param limit Number of results to return. (optional, default to 25) + * @param offset Record position at which to start returning results. (optional, default to 0) + * @return ApiResponse<V1AuditResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse auditServiceListAuditEventsWithHttpInfo(String filterOpsAccountID, String filterOpsContextChangeID, String filterOpsContextRequestID, String filterOpsContextTraceID, String filterOpsContextSessionID, String filterOpsContextActor, String filterOpsContextActorType, String filterOpsContextAccessType, String filterOpsContextIpAddress, String filterOpsContextOrigin, String filterOpsContextAuthMode, String filterOpsContextJwtID, String filterOpsContextBearerTokenContextID, String filterOpsParentAccountID, String filterOpsWorkspaceID, String filterOpsVaultID, String filterOpsResourceIDs, String filterOpsActionType, String filterOpsResourceType, String filterOpsTags, Integer filterOpsResponseCode, String filterOpsStartTime, String filterOpsEndTime, String filterOpsApiName, String filterOpsResponseMessage, String filterOpsHttpMethod, String filterOpsHttpURI, String sortOpsSortBy, String sortOpsOrderBy, String afterOpsTimestamp, String afterOpsChangeID, Long limit, Long offset) throws ApiException { + okhttp3.Call localVarCall = auditServiceListAuditEventsValidateBeforeCall(filterOpsAccountID, filterOpsContextChangeID, filterOpsContextRequestID, filterOpsContextTraceID, filterOpsContextSessionID, filterOpsContextActor, filterOpsContextActorType, filterOpsContextAccessType, filterOpsContextIpAddress, filterOpsContextOrigin, filterOpsContextAuthMode, filterOpsContextJwtID, filterOpsContextBearerTokenContextID, filterOpsParentAccountID, filterOpsWorkspaceID, filterOpsVaultID, filterOpsResourceIDs, filterOpsActionType, filterOpsResourceType, filterOpsTags, filterOpsResponseCode, filterOpsStartTime, filterOpsEndTime, filterOpsApiName, filterOpsResponseMessage, filterOpsHttpMethod, filterOpsHttpURI, sortOpsSortBy, sortOpsOrderBy, afterOpsTimestamp, afterOpsChangeID, limit, offset, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * List Audit Events (asynchronously) + * Lists audit events that match query parameters. + * @param filterOpsAccountID Resources with the specified account ID. (required) + * @param filterOpsContextChangeID ID for the audit event. (optional) + * @param filterOpsContextRequestID ID for the request that caused the event. (optional) + * @param filterOpsContextTraceID ID for the request set by the service that received the request. (optional) + * @param filterOpsContextSessionID ID for the session in which the request was sent. (optional) + * @param filterOpsContextActor Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. (optional) + * @param filterOpsContextActorType Type of member who sent the request. (optional, default to NONE) + * @param filterOpsContextAccessType Type of access for the request. (optional, default to ACCESS_NONE) + * @param filterOpsContextIpAddress IP Address of the client that made the request. (optional) + * @param filterOpsContextOrigin HTTP Origin request header (including scheme, hostname, and port) of the request. (optional) + * @param filterOpsContextAuthMode Authentication mode the `actor` used. (optional, default to AUTH_NONE) + * @param filterOpsContextJwtID ID of the JWT token. (optional) + * @param filterOpsContextBearerTokenContextID Embedded User Context. (optional) + * @param filterOpsParentAccountID Resources with the specified parent account ID. (optional) + * @param filterOpsWorkspaceID Resources with the specified workspace ID. (optional) + * @param filterOpsVaultID Resources with the specified vault ID. (optional) + * @param filterOpsResourceIDs Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\<resourceType\\>/\\<resourceID\\>\". For example, \"VAULT/12345, USER/67890\". (optional) + * @param filterOpsActionType Events with the specified action type. (optional, default to NONE) + * @param filterOpsResourceType Resources with the specified type. (optional, default to NONE_API) + * @param filterOpsTags Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\". (optional) + * @param filterOpsResponseCode HTTP response code of the request. (optional) + * @param filterOpsStartTime Start timestamp for the query, in SQL format. (optional) + * @param filterOpsEndTime End timestamp for the query, in SQL format. (optional) + * @param filterOpsApiName Name of the API called in the request. (optional) + * @param filterOpsResponseMessage Response message of the request. (optional) + * @param filterOpsHttpMethod HTTP method of the request. (optional) + * @param filterOpsHttpURI HTTP URI of the request. (optional) + * @param sortOpsSortBy Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\"). (optional) + * @param sortOpsOrderBy Ascending or descending ordering of results. (optional, default to ASCENDING) + * @param afterOpsTimestamp Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) + * @param afterOpsChangeID Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) + * @param limit Number of results to return. (optional, default to 25) + * @param offset Record position at which to start returning results. (optional, default to 0) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call auditServiceListAuditEventsAsync(String filterOpsAccountID, String filterOpsContextChangeID, String filterOpsContextRequestID, String filterOpsContextTraceID, String filterOpsContextSessionID, String filterOpsContextActor, String filterOpsContextActorType, String filterOpsContextAccessType, String filterOpsContextIpAddress, String filterOpsContextOrigin, String filterOpsContextAuthMode, String filterOpsContextJwtID, String filterOpsContextBearerTokenContextID, String filterOpsParentAccountID, String filterOpsWorkspaceID, String filterOpsVaultID, String filterOpsResourceIDs, String filterOpsActionType, String filterOpsResourceType, String filterOpsTags, Integer filterOpsResponseCode, String filterOpsStartTime, String filterOpsEndTime, String filterOpsApiName, String filterOpsResponseMessage, String filterOpsHttpMethod, String filterOpsHttpURI, String sortOpsSortBy, String sortOpsOrderBy, String afterOpsTimestamp, String afterOpsChangeID, Long limit, Long offset, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = auditServiceListAuditEventsValidateBeforeCall(filterOpsAccountID, filterOpsContextChangeID, filterOpsContextRequestID, filterOpsContextTraceID, filterOpsContextSessionID, filterOpsContextActor, filterOpsContextActorType, filterOpsContextAccessType, filterOpsContextIpAddress, filterOpsContextOrigin, filterOpsContextAuthMode, filterOpsContextJwtID, filterOpsContextBearerTokenContextID, filterOpsParentAccountID, filterOpsWorkspaceID, filterOpsVaultID, filterOpsResourceIDs, filterOpsActionType, filterOpsResourceType, filterOpsTags, filterOpsResponseCode, filterOpsStartTime, filterOpsEndTime, filterOpsApiName, filterOpsResponseMessage, filterOpsHttpMethod, filterOpsHttpURI, sortOpsSortBy, sortOpsOrderBy, afterOpsTimestamp, afterOpsChangeID, limit, offset, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java b/v2/src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java new file mode 100644 index 00000000..e26da776 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java @@ -0,0 +1,216 @@ +/* + * Skyflow Management API + * # Management API This API controls aspects of your account and schema, including workspaces, vaults, keys, users, permissions, and more. The Management API is available from two base URIs:
  • Sandbox: https://manage.skyflowapis-preview.com
  • Production: https://manage.skyflowapis.com
When you make an API call, you need to add two headers:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
X-SKYFLOW-ACCOUNT-IDYour Skyflow account ID.X-SKYFLOW-ACCOUNT-ID: h451b763713e4424a7jke1bbkbbc84ef
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.api; + +import com.skyflow.generated.rest.ApiCallback; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.ApiException; +import com.skyflow.generated.rest.ApiResponse; +import com.skyflow.generated.rest.Configuration; +import com.skyflow.generated.rest.Pair; +import com.skyflow.generated.rest.ProgressRequestBody; +import com.skyflow.generated.rest.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import com.skyflow.generated.rest.models.GooglerpcStatus; +import com.skyflow.generated.rest.models.V1GetAuthTokenRequest; +import com.skyflow.generated.rest.models.V1GetAuthTokenResponse; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AuthenticationApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public AuthenticationApi() { + this(Configuration.getDefaultApiClient()); + } + + public AuthenticationApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for authenticationServiceGetAuthToken + * @param body (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details +
+ + + + + + +
Status Code Description Response Headers
200 A successful response. -
400 Invalid scope format. -
401 Key expired or JWT token unparseable. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call authenticationServiceGetAuthTokenCall(V1GetAuthTokenRequest body, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/v1/auth/sa/oauth/token"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call authenticationServiceGetAuthTokenValidateBeforeCall(V1GetAuthTokenRequest body, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling authenticationServiceGetAuthToken(Async)"); + } + + return authenticationServiceGetAuthTokenCall(body, _callback); + + } + + /** + * Get Bearer Token + * <p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p> + * @param body (required) + * @return V1GetAuthTokenResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + + + +
Status Code Description Response Headers
200 A successful response. -
400 Invalid scope format. -
401 Key expired or JWT token unparseable. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1GetAuthTokenResponse authenticationServiceGetAuthToken(V1GetAuthTokenRequest body) throws ApiException { + ApiResponse localVarResp = authenticationServiceGetAuthTokenWithHttpInfo(body); + return localVarResp.getData(); + } + + /** + * Get Bearer Token + * <p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p> + * @param body (required) + * @return ApiResponse<V1GetAuthTokenResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + + + +
Status Code Description Response Headers
200 A successful response. -
400 Invalid scope format. -
401 Key expired or JWT token unparseable. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse authenticationServiceGetAuthTokenWithHttpInfo(V1GetAuthTokenRequest body) throws ApiException { + okhttp3.Call localVarCall = authenticationServiceGetAuthTokenValidateBeforeCall(body, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Get Bearer Token (asynchronously) + * <p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p> + * @param body (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + + + +
Status Code Description Response Headers
200 A successful response. -
400 Invalid scope format. -
401 Key expired or JWT token unparseable. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call authenticationServiceGetAuthTokenAsync(V1GetAuthTokenRequest body, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = authenticationServiceGetAuthTokenValidateBeforeCall(body, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java b/v2/src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java new file mode 100644 index 00000000..da1a862a --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java @@ -0,0 +1,208 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.api; + +import com.skyflow.generated.rest.ApiCallback; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.ApiException; +import com.skyflow.generated.rest.ApiResponse; +import com.skyflow.generated.rest.Configuration; +import com.skyflow.generated.rest.Pair; +import com.skyflow.generated.rest.ProgressRequestBody; +import com.skyflow.generated.rest.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import com.skyflow.generated.rest.models.GooglerpcStatus; +import com.skyflow.generated.rest.models.V1BINListRequest; +import com.skyflow.generated.rest.models.V1BINListResponse; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class BinLookupApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public BinLookupApi() { + this(Configuration.getDefaultApiClient()); + } + + public BinLookupApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for bINListServiceListCardsOfBIN + * @param body Request to return specific card metadata. (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details +
+ + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call bINListServiceListCardsOfBINCall(V1BINListRequest body, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/v1/card_lookup"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call bINListServiceListCardsOfBINValidateBeforeCall(V1BINListRequest body, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling bINListServiceListCardsOfBIN(Async)"); + } + + return bINListServiceListCardsOfBINCall(body, _callback); + + } + + /** + * Get BIN + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + * @param body Request to return specific card metadata. (required) + * @return V1BINListResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1BINListResponse bINListServiceListCardsOfBIN(V1BINListRequest body) throws ApiException { + ApiResponse localVarResp = bINListServiceListCardsOfBINWithHttpInfo(body); + return localVarResp.getData(); + } + + /** + * Get BIN + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + * @param body Request to return specific card metadata. (required) + * @return ApiResponse<V1BINListResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse bINListServiceListCardsOfBINWithHttpInfo(V1BINListRequest body) throws ApiException { + okhttp3.Call localVarCall = bINListServiceListCardsOfBINValidateBeforeCall(body, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Get BIN (asynchronously) + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + * @param body Request to return specific card metadata. (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call bINListServiceListCardsOfBINAsync(V1BINListRequest body, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = bINListServiceListCardsOfBINValidateBeforeCall(body, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/api/QueryApi.java b/v2/src/main/java/com/skyflow/generated/rest/api/QueryApi.java new file mode 100644 index 00000000..fad624ce --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/api/QueryApi.java @@ -0,0 +1,218 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.api; + +import com.skyflow.generated.rest.ApiCallback; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.ApiException; +import com.skyflow.generated.rest.ApiResponse; +import com.skyflow.generated.rest.Configuration; +import com.skyflow.generated.rest.Pair; +import com.skyflow.generated.rest.ProgressRequestBody; +import com.skyflow.generated.rest.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import com.skyflow.generated.rest.models.GooglerpcStatus; +import com.skyflow.generated.rest.models.QueryServiceExecuteQueryBody; +import com.skyflow.generated.rest.models.V1GetQueryResponse; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class QueryApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public QueryApi() { + this(Configuration.getDefaultApiClient()); + } + + public QueryApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for queryServiceExecuteQuery + * @param vaultID ID of the vault. (required) + * @param body (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details +
+ + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call queryServiceExecuteQueryCall(String vaultID, QueryServiceExecuteQueryBody body, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/v1/vaults/{vaultID}/query" + .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call queryServiceExecuteQueryValidateBeforeCall(String vaultID, QueryServiceExecuteQueryBody body, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'vaultID' is set + if (vaultID == null) { + throw new ApiException("Missing the required parameter 'vaultID' when calling queryServiceExecuteQuery(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling queryServiceExecuteQuery(Async)"); + } + + return queryServiceExecuteQueryCall(vaultID, body, _callback); + + } + + /** + * Execute Query + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support `?` conditional for columns with column-level encryption disabled.</li><ul> + * @param vaultID ID of the vault. (required) + * @param body (required) + * @return V1GetQueryResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1GetQueryResponse queryServiceExecuteQuery(String vaultID, QueryServiceExecuteQueryBody body) throws ApiException { + ApiResponse localVarResp = queryServiceExecuteQueryWithHttpInfo(vaultID, body); + return localVarResp.getData(); + } + + /** + * Execute Query + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support `?` conditional for columns with column-level encryption disabled.</li><ul> + * @param vaultID ID of the vault. (required) + * @param body (required) + * @return ApiResponse<V1GetQueryResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse queryServiceExecuteQueryWithHttpInfo(String vaultID, QueryServiceExecuteQueryBody body) throws ApiException { + okhttp3.Call localVarCall = queryServiceExecuteQueryValidateBeforeCall(vaultID, body, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Execute Query (asynchronously) + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support `?` conditional for columns with column-level encryption disabled.</li><ul> + * @param vaultID ID of the vault. (required) + * @param body (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call queryServiceExecuteQueryAsync(String vaultID, QueryServiceExecuteQueryBody body, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = queryServiceExecuteQueryValidateBeforeCall(vaultID, body, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/api/RecordsApi.java b/v2/src/main/java/com/skyflow/generated/rest/api/RecordsApi.java new file mode 100644 index 00000000..d8d8257b --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/api/RecordsApi.java @@ -0,0 +1,1730 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.api; + +import com.skyflow.generated.rest.ApiCallback; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.ApiException; +import com.skyflow.generated.rest.ApiResponse; +import com.skyflow.generated.rest.Configuration; +import com.skyflow.generated.rest.Pair; +import com.skyflow.generated.rest.ProgressRequestBody; +import com.skyflow.generated.rest.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import java.io.File; +import com.skyflow.generated.rest.models.GooglerpcStatus; +import com.skyflow.generated.rest.models.RecordServiceBatchOperationBody; +import com.skyflow.generated.rest.models.RecordServiceBulkDeleteRecordBody; +import com.skyflow.generated.rest.models.RecordServiceInsertRecordBody; +import com.skyflow.generated.rest.models.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.models.V1BatchOperationResponse; +import com.skyflow.generated.rest.models.V1BulkDeleteRecordResponse; +import com.skyflow.generated.rest.models.V1BulkGetRecordResponse; +import com.skyflow.generated.rest.models.V1DeleteFileResponse; +import com.skyflow.generated.rest.models.V1DeleteRecordResponse; +import com.skyflow.generated.rest.models.V1FieldRecords; +import com.skyflow.generated.rest.models.V1GetFileScanStatusResponse; +import com.skyflow.generated.rest.models.V1InsertRecordResponse; +import com.skyflow.generated.rest.models.V1UpdateRecordResponse; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class RecordsApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public RecordsApi() { + this(Configuration.getDefaultApiClient()); + } + + public RecordsApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for fileServiceDeleteFile + * @param vaultID ID of the vault. (required) + * @param tableName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param columnName Name of the column that contains the file. (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details +
+ + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call fileServiceDeleteFileCall(String vaultID, String tableName, String ID, String columnName, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/v1/vaults/{vaultID}/{tableName}/{ID}/files/{columnName}" + .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) + .replace("{" + "tableName" + "}", localVarApiClient.escapeString(tableName.toString())) + .replace("{" + "ID" + "}", localVarApiClient.escapeString(ID.toString())) + .replace("{" + "columnName" + "}", localVarApiClient.escapeString(columnName.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fileServiceDeleteFileValidateBeforeCall(String vaultID, String tableName, String ID, String columnName, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'vaultID' is set + if (vaultID == null) { + throw new ApiException("Missing the required parameter 'vaultID' when calling fileServiceDeleteFile(Async)"); + } + + // verify the required parameter 'tableName' is set + if (tableName == null) { + throw new ApiException("Missing the required parameter 'tableName' when calling fileServiceDeleteFile(Async)"); + } + + // verify the required parameter 'ID' is set + if (ID == null) { + throw new ApiException("Missing the required parameter 'ID' when calling fileServiceDeleteFile(Async)"); + } + + // verify the required parameter 'columnName' is set + if (columnName == null) { + throw new ApiException("Missing the required parameter 'columnName' when calling fileServiceDeleteFile(Async)"); + } + + return fileServiceDeleteFileCall(vaultID, tableName, ID, columnName, _callback); + + } + + /** + * Delete File + * Deletes a file from the specified record. + * @param vaultID ID of the vault. (required) + * @param tableName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param columnName Name of the column that contains the file. (required) + * @return V1DeleteFileResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1DeleteFileResponse fileServiceDeleteFile(String vaultID, String tableName, String ID, String columnName) throws ApiException { + ApiResponse localVarResp = fileServiceDeleteFileWithHttpInfo(vaultID, tableName, ID, columnName); + return localVarResp.getData(); + } + + /** + * Delete File + * Deletes a file from the specified record. + * @param vaultID ID of the vault. (required) + * @param tableName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param columnName Name of the column that contains the file. (required) + * @return ApiResponse<V1DeleteFileResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse fileServiceDeleteFileWithHttpInfo(String vaultID, String tableName, String ID, String columnName) throws ApiException { + okhttp3.Call localVarCall = fileServiceDeleteFileValidateBeforeCall(vaultID, tableName, ID, columnName, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Delete File (asynchronously) + * Deletes a file from the specified record. + * @param vaultID ID of the vault. (required) + * @param tableName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param columnName Name of the column that contains the file. (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call fileServiceDeleteFileAsync(String vaultID, String tableName, String ID, String columnName, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fileServiceDeleteFileValidateBeforeCall(vaultID, tableName, ID, columnName, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fileServiceGetFileScanStatus + * @param vaultID ID of the vault. (required) + * @param tableName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param columnName Name of the column that contains the file. (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call fileServiceGetFileScanStatusCall(String vaultID, String tableName, String ID, String columnName, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/v1/vaults/{vaultID}/{tableName}/{ID}/files/{columnName}/scan-status" + .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) + .replace("{" + "tableName" + "}", localVarApiClient.escapeString(tableName.toString())) + .replace("{" + "ID" + "}", localVarApiClient.escapeString(ID.toString())) + .replace("{" + "columnName" + "}", localVarApiClient.escapeString(columnName.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fileServiceGetFileScanStatusValidateBeforeCall(String vaultID, String tableName, String ID, String columnName, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'vaultID' is set + if (vaultID == null) { + throw new ApiException("Missing the required parameter 'vaultID' when calling fileServiceGetFileScanStatus(Async)"); + } + + // verify the required parameter 'tableName' is set + if (tableName == null) { + throw new ApiException("Missing the required parameter 'tableName' when calling fileServiceGetFileScanStatus(Async)"); + } + + // verify the required parameter 'ID' is set + if (ID == null) { + throw new ApiException("Missing the required parameter 'ID' when calling fileServiceGetFileScanStatus(Async)"); + } + + // verify the required parameter 'columnName' is set + if (columnName == null) { + throw new ApiException("Missing the required parameter 'columnName' when calling fileServiceGetFileScanStatus(Async)"); + } + + return fileServiceGetFileScanStatusCall(vaultID, tableName, ID, columnName, _callback); + + } + + /** + * Get File Scan Status + * Returns the anti-virus scan status of a file. + * @param vaultID ID of the vault. (required) + * @param tableName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param columnName Name of the column that contains the file. (required) + * @return V1GetFileScanStatusResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1GetFileScanStatusResponse fileServiceGetFileScanStatus(String vaultID, String tableName, String ID, String columnName) throws ApiException { + ApiResponse localVarResp = fileServiceGetFileScanStatusWithHttpInfo(vaultID, tableName, ID, columnName); + return localVarResp.getData(); + } + + /** + * Get File Scan Status + * Returns the anti-virus scan status of a file. + * @param vaultID ID of the vault. (required) + * @param tableName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param columnName Name of the column that contains the file. (required) + * @return ApiResponse<V1GetFileScanStatusResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse fileServiceGetFileScanStatusWithHttpInfo(String vaultID, String tableName, String ID, String columnName) throws ApiException { + okhttp3.Call localVarCall = fileServiceGetFileScanStatusValidateBeforeCall(vaultID, tableName, ID, columnName, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Get File Scan Status (asynchronously) + * Returns the anti-virus scan status of a file. + * @param vaultID ID of the vault. (required) + * @param tableName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param columnName Name of the column that contains the file. (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call fileServiceGetFileScanStatusAsync(String vaultID, String tableName, String ID, String columnName, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fileServiceGetFileScanStatusValidateBeforeCall(vaultID, tableName, ID, columnName, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fileServiceUploadFile + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param fileColumnName Name of the column to store the file in. The column must have a file data type. (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call fileServiceUploadFileCall(String vaultID, String objectName, String ID, File fileColumnName, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/v1/vaults/{vaultID}/{objectName}/{ID}/files" + .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) + .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())) + .replace("{" + "ID" + "}", localVarApiClient.escapeString(ID.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (fileColumnName != null) { + localVarFormParams.put("fileColumnName", fileColumnName); + } + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fileServiceUploadFileValidateBeforeCall(String vaultID, String objectName, String ID, File fileColumnName, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'vaultID' is set + if (vaultID == null) { + throw new ApiException("Missing the required parameter 'vaultID' when calling fileServiceUploadFile(Async)"); + } + + // verify the required parameter 'objectName' is set + if (objectName == null) { + throw new ApiException("Missing the required parameter 'objectName' when calling fileServiceUploadFile(Async)"); + } + + // verify the required parameter 'ID' is set + if (ID == null) { + throw new ApiException("Missing the required parameter 'ID' when calling fileServiceUploadFile(Async)"); + } + + return fileServiceUploadFileCall(vaultID, objectName, ID, fileColumnName, _callback); + + } + + /** + * Upload File + * Uploads a file to the specified record. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param fileColumnName Name of the column to store the file in. The column must have a file data type. (optional) + * @return V1UpdateRecordResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1UpdateRecordResponse fileServiceUploadFile(String vaultID, String objectName, String ID, File fileColumnName) throws ApiException { + ApiResponse localVarResp = fileServiceUploadFileWithHttpInfo(vaultID, objectName, ID, fileColumnName); + return localVarResp.getData(); + } + + /** + * Upload File + * Uploads a file to the specified record. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param fileColumnName Name of the column to store the file in. The column must have a file data type. (optional) + * @return ApiResponse<V1UpdateRecordResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse fileServiceUploadFileWithHttpInfo(String vaultID, String objectName, String ID, File fileColumnName) throws ApiException { + okhttp3.Call localVarCall = fileServiceUploadFileValidateBeforeCall(vaultID, objectName, ID, fileColumnName, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Upload File (asynchronously) + * Uploads a file to the specified record. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param fileColumnName Name of the column to store the file in. The column must have a file data type. (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call fileServiceUploadFileAsync(String vaultID, String objectName, String ID, File fileColumnName, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fileServiceUploadFileValidateBeforeCall(vaultID, objectName, ID, fileColumnName, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for recordServiceBatchOperation + * @param vaultID ID of the vault. (required) + * @param body (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceBatchOperationCall(String vaultID, RecordServiceBatchOperationBody body, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/v1/vaults/{vaultID}" + .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call recordServiceBatchOperationValidateBeforeCall(String vaultID, RecordServiceBatchOperationBody body, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'vaultID' is set + if (vaultID == null) { + throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceBatchOperation(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling recordServiceBatchOperation(Async)"); + } + + return recordServiceBatchOperationCall(vaultID, body, _callback); + + } + + /** + * Batch Operation + * Performs multiple record operations in a single transaction. + * @param vaultID ID of the vault. (required) + * @param body (required) + * @return V1BatchOperationResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1BatchOperationResponse recordServiceBatchOperation(String vaultID, RecordServiceBatchOperationBody body) throws ApiException { + ApiResponse localVarResp = recordServiceBatchOperationWithHttpInfo(vaultID, body); + return localVarResp.getData(); + } + + /** + * Batch Operation + * Performs multiple record operations in a single transaction. + * @param vaultID ID of the vault. (required) + * @param body (required) + * @return ApiResponse<V1BatchOperationResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse recordServiceBatchOperationWithHttpInfo(String vaultID, RecordServiceBatchOperationBody body) throws ApiException { + okhttp3.Call localVarCall = recordServiceBatchOperationValidateBeforeCall(vaultID, body, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Batch Operation (asynchronously) + * Performs multiple record operations in a single transaction. + * @param vaultID ID of the vault. (required) + * @param body (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceBatchOperationAsync(String vaultID, RecordServiceBatchOperationBody body, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = recordServiceBatchOperationValidateBeforeCall(vaultID, body, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for recordServiceBulkDeleteRecord + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param body (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceBulkDeleteRecordCall(String vaultID, String objectName, RecordServiceBulkDeleteRecordBody body, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/v1/vaults/{vaultID}/{objectName}" + .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) + .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call recordServiceBulkDeleteRecordValidateBeforeCall(String vaultID, String objectName, RecordServiceBulkDeleteRecordBody body, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'vaultID' is set + if (vaultID == null) { + throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceBulkDeleteRecord(Async)"); + } + + // verify the required parameter 'objectName' is set + if (objectName == null) { + throw new ApiException("Missing the required parameter 'objectName' when calling recordServiceBulkDeleteRecord(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling recordServiceBulkDeleteRecord(Async)"); + } + + return recordServiceBulkDeleteRecordCall(vaultID, objectName, body, _callback); + + } + + /** + * Bulk Delete Records + * Deletes the specified records from a table. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param body (required) + * @return V1BulkDeleteRecordResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1BulkDeleteRecordResponse recordServiceBulkDeleteRecord(String vaultID, String objectName, RecordServiceBulkDeleteRecordBody body) throws ApiException { + ApiResponse localVarResp = recordServiceBulkDeleteRecordWithHttpInfo(vaultID, objectName, body); + return localVarResp.getData(); + } + + /** + * Bulk Delete Records + * Deletes the specified records from a table. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param body (required) + * @return ApiResponse<V1BulkDeleteRecordResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse recordServiceBulkDeleteRecordWithHttpInfo(String vaultID, String objectName, RecordServiceBulkDeleteRecordBody body) throws ApiException { + okhttp3.Call localVarCall = recordServiceBulkDeleteRecordValidateBeforeCall(vaultID, objectName, body, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Bulk Delete Records (asynchronously) + * Deletes the specified records from a table. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param body (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceBulkDeleteRecordAsync(String vaultID, String objectName, RecordServiceBulkDeleteRecordBody body, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = recordServiceBulkDeleteRecordValidateBeforeCall(vaultID, objectName, body, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for recordServiceBulkGetRecord + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table that contains the records. (required) + * @param skyflowIds `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.<br /><br />If not specified, returns the first 25 records in the table. (optional) + * @param redaction Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. (optional, default to DEFAULT) + * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) + * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) + * @param offset Record position at which to start receiving data. (optional, default to 0) + * @param limit Number of record to return. Maximum 25. (optional, default to 25) + * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) + * @param columnName Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) + * @param columnValues Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.<br /><br />`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) + * @param orderBy Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. (optional, default to ASCENDING) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceBulkGetRecordCall(String vaultID, String objectName, List skyflowIds, String redaction, Boolean tokenization, List fields, String offset, String limit, Boolean downloadURL, String columnName, List columnValues, String orderBy, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/v1/vaults/{vaultID}/{objectName}" + .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) + .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (skyflowIds != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "skyflow_ids", skyflowIds)); + } + + if (redaction != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("redaction", redaction)); + } + + if (tokenization != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("tokenization", tokenization)); + } + + if (fields != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "fields", fields)); + } + + if (offset != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("offset", offset)); + } + + if (limit != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("limit", limit)); + } + + if (downloadURL != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("downloadURL", downloadURL)); + } + + if (columnName != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("column_name", columnName)); + } + + if (columnValues != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "column_values", columnValues)); + } + + if (orderBy != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("order_by", orderBy)); + } + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call recordServiceBulkGetRecordValidateBeforeCall(String vaultID, String objectName, List skyflowIds, String redaction, Boolean tokenization, List fields, String offset, String limit, Boolean downloadURL, String columnName, List columnValues, String orderBy, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'vaultID' is set + if (vaultID == null) { + throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceBulkGetRecord(Async)"); + } + + // verify the required parameter 'objectName' is set + if (objectName == null) { + throw new ApiException("Missing the required parameter 'objectName' when calling recordServiceBulkGetRecord(Async)"); + } + + return recordServiceBulkGetRecordCall(vaultID, objectName, skyflowIds, redaction, tokenization, fields, offset, limit, downloadURL, columnName, columnValues, orderBy, _callback); + + } + + /** + * Get Record(s) + * Gets the specified records from a table. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table that contains the records. (required) + * @param skyflowIds `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.<br /><br />If not specified, returns the first 25 records in the table. (optional) + * @param redaction Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. (optional, default to DEFAULT) + * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) + * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) + * @param offset Record position at which to start receiving data. (optional, default to 0) + * @param limit Number of record to return. Maximum 25. (optional, default to 25) + * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) + * @param columnName Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) + * @param columnValues Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.<br /><br />`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) + * @param orderBy Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. (optional, default to ASCENDING) + * @return V1BulkGetRecordResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1BulkGetRecordResponse recordServiceBulkGetRecord(String vaultID, String objectName, List skyflowIds, String redaction, Boolean tokenization, List fields, String offset, String limit, Boolean downloadURL, String columnName, List columnValues, String orderBy) throws ApiException { + ApiResponse localVarResp = recordServiceBulkGetRecordWithHttpInfo(vaultID, objectName, skyflowIds, redaction, tokenization, fields, offset, limit, downloadURL, columnName, columnValues, orderBy); + return localVarResp.getData(); + } + + /** + * Get Record(s) + * Gets the specified records from a table. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table that contains the records. (required) + * @param skyflowIds `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.<br /><br />If not specified, returns the first 25 records in the table. (optional) + * @param redaction Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. (optional, default to DEFAULT) + * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) + * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) + * @param offset Record position at which to start receiving data. (optional, default to 0) + * @param limit Number of record to return. Maximum 25. (optional, default to 25) + * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) + * @param columnName Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) + * @param columnValues Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.<br /><br />`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) + * @param orderBy Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. (optional, default to ASCENDING) + * @return ApiResponse<V1BulkGetRecordResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse recordServiceBulkGetRecordWithHttpInfo(String vaultID, String objectName, List skyflowIds, String redaction, Boolean tokenization, List fields, String offset, String limit, Boolean downloadURL, String columnName, List columnValues, String orderBy) throws ApiException { + okhttp3.Call localVarCall = recordServiceBulkGetRecordValidateBeforeCall(vaultID, objectName, skyflowIds, redaction, tokenization, fields, offset, limit, downloadURL, columnName, columnValues, orderBy, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Get Record(s) (asynchronously) + * Gets the specified records from a table. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table that contains the records. (required) + * @param skyflowIds `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.<br /><br />If not specified, returns the first 25 records in the table. (optional) + * @param redaction Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. (optional, default to DEFAULT) + * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) + * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) + * @param offset Record position at which to start receiving data. (optional, default to 0) + * @param limit Number of record to return. Maximum 25. (optional, default to 25) + * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) + * @param columnName Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) + * @param columnValues Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.<br /><br />`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) + * @param orderBy Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. (optional, default to ASCENDING) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceBulkGetRecordAsync(String vaultID, String objectName, List skyflowIds, String redaction, Boolean tokenization, List fields, String offset, String limit, Boolean downloadURL, String columnName, List columnValues, String orderBy, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = recordServiceBulkGetRecordValidateBeforeCall(vaultID, objectName, skyflowIds, redaction, tokenization, fields, offset, limit, downloadURL, columnName, columnValues, orderBy, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for recordServiceDeleteRecord + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record to delete. (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceDeleteRecordCall(String vaultID, String objectName, String ID, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/v1/vaults/{vaultID}/{objectName}/{ID}" + .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) + .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())) + .replace("{" + "ID" + "}", localVarApiClient.escapeString(ID.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call recordServiceDeleteRecordValidateBeforeCall(String vaultID, String objectName, String ID, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'vaultID' is set + if (vaultID == null) { + throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceDeleteRecord(Async)"); + } + + // verify the required parameter 'objectName' is set + if (objectName == null) { + throw new ApiException("Missing the required parameter 'objectName' when calling recordServiceDeleteRecord(Async)"); + } + + // verify the required parameter 'ID' is set + if (ID == null) { + throw new ApiException("Missing the required parameter 'ID' when calling recordServiceDeleteRecord(Async)"); + } + + return recordServiceDeleteRecordCall(vaultID, objectName, ID, _callback); + + } + + /** + * Delete Record + * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record to delete. (required) + * @return V1DeleteRecordResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1DeleteRecordResponse recordServiceDeleteRecord(String vaultID, String objectName, String ID) throws ApiException { + ApiResponse localVarResp = recordServiceDeleteRecordWithHttpInfo(vaultID, objectName, ID); + return localVarResp.getData(); + } + + /** + * Delete Record + * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record to delete. (required) + * @return ApiResponse<V1DeleteRecordResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse recordServiceDeleteRecordWithHttpInfo(String vaultID, String objectName, String ID) throws ApiException { + okhttp3.Call localVarCall = recordServiceDeleteRecordValidateBeforeCall(vaultID, objectName, ID, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Delete Record (asynchronously) + * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record to delete. (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceDeleteRecordAsync(String vaultID, String objectName, String ID, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = recordServiceDeleteRecordValidateBeforeCall(vaultID, objectName, ID, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for recordServiceGetRecord + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param redaction Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. (optional, default to DEFAULT) + * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) + * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) + * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceGetRecordCall(String vaultID, String objectName, String ID, String redaction, Boolean tokenization, List fields, Boolean downloadURL, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/v1/vaults/{vaultID}/{objectName}/{ID}" + .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) + .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())) + .replace("{" + "ID" + "}", localVarApiClient.escapeString(ID.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (redaction != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("redaction", redaction)); + } + + if (tokenization != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("tokenization", tokenization)); + } + + if (fields != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "fields", fields)); + } + + if (downloadURL != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("downloadURL", downloadURL)); + } + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call recordServiceGetRecordValidateBeforeCall(String vaultID, String objectName, String ID, String redaction, Boolean tokenization, List fields, Boolean downloadURL, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'vaultID' is set + if (vaultID == null) { + throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceGetRecord(Async)"); + } + + // verify the required parameter 'objectName' is set + if (objectName == null) { + throw new ApiException("Missing the required parameter 'objectName' when calling recordServiceGetRecord(Async)"); + } + + // verify the required parameter 'ID' is set + if (ID == null) { + throw new ApiException("Missing the required parameter 'ID' when calling recordServiceGetRecord(Async)"); + } + + return recordServiceGetRecordCall(vaultID, objectName, ID, redaction, tokenization, fields, downloadURL, _callback); + + } + + /** + * Get Record By ID + * Returns the specified record from a table. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param redaction Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. (optional, default to DEFAULT) + * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) + * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) + * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) + * @return V1FieldRecords + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1FieldRecords recordServiceGetRecord(String vaultID, String objectName, String ID, String redaction, Boolean tokenization, List fields, Boolean downloadURL) throws ApiException { + ApiResponse localVarResp = recordServiceGetRecordWithHttpInfo(vaultID, objectName, ID, redaction, tokenization, fields, downloadURL); + return localVarResp.getData(); + } + + /** + * Get Record By ID + * Returns the specified record from a table. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param redaction Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. (optional, default to DEFAULT) + * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) + * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) + * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) + * @return ApiResponse<V1FieldRecords> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse recordServiceGetRecordWithHttpInfo(String vaultID, String objectName, String ID, String redaction, Boolean tokenization, List fields, Boolean downloadURL) throws ApiException { + okhttp3.Call localVarCall = recordServiceGetRecordValidateBeforeCall(vaultID, objectName, ID, redaction, tokenization, fields, downloadURL, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Get Record By ID (asynchronously) + * Returns the specified record from a table. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param redaction Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. (optional, default to DEFAULT) + * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) + * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) + * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceGetRecordAsync(String vaultID, String objectName, String ID, String redaction, Boolean tokenization, List fields, Boolean downloadURL, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = recordServiceGetRecordValidateBeforeCall(vaultID, objectName, ID, redaction, tokenization, fields, downloadURL, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for recordServiceInsertRecord + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param body (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceInsertRecordCall(String vaultID, String objectName, RecordServiceInsertRecordBody body, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/v1/vaults/{vaultID}/{objectName}" + .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) + .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call recordServiceInsertRecordValidateBeforeCall(String vaultID, String objectName, RecordServiceInsertRecordBody body, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'vaultID' is set + if (vaultID == null) { + throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceInsertRecord(Async)"); + } + + // verify the required parameter 'objectName' is set + if (objectName == null) { + throw new ApiException("Missing the required parameter 'objectName' when calling recordServiceInsertRecord(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling recordServiceInsertRecord(Async)"); + } + + return recordServiceInsertRecordCall(vaultID, objectName, body, _callback); + + } + + /** + * Insert Records + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param body (required) + * @return V1InsertRecordResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1InsertRecordResponse recordServiceInsertRecord(String vaultID, String objectName, RecordServiceInsertRecordBody body) throws ApiException { + ApiResponse localVarResp = recordServiceInsertRecordWithHttpInfo(vaultID, objectName, body); + return localVarResp.getData(); + } + + /** + * Insert Records + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param body (required) + * @return ApiResponse<V1InsertRecordResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse recordServiceInsertRecordWithHttpInfo(String vaultID, String objectName, RecordServiceInsertRecordBody body) throws ApiException { + okhttp3.Call localVarCall = recordServiceInsertRecordValidateBeforeCall(vaultID, objectName, body, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Insert Records (asynchronously) + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param body (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceInsertRecordAsync(String vaultID, String objectName, RecordServiceInsertRecordBody body, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = recordServiceInsertRecordValidateBeforeCall(vaultID, objectName, body, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for recordServiceUpdateRecord + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param body (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceUpdateRecordCall(String vaultID, String objectName, String ID, RecordServiceUpdateRecordBody body, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/v1/vaults/{vaultID}/{objectName}/{ID}" + .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) + .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())) + .replace("{" + "ID" + "}", localVarApiClient.escapeString(ID.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call recordServiceUpdateRecordValidateBeforeCall(String vaultID, String objectName, String ID, RecordServiceUpdateRecordBody body, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'vaultID' is set + if (vaultID == null) { + throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceUpdateRecord(Async)"); + } + + // verify the required parameter 'objectName' is set + if (objectName == null) { + throw new ApiException("Missing the required parameter 'objectName' when calling recordServiceUpdateRecord(Async)"); + } + + // verify the required parameter 'ID' is set + if (ID == null) { + throw new ApiException("Missing the required parameter 'ID' when calling recordServiceUpdateRecord(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling recordServiceUpdateRecord(Async)"); + } + + return recordServiceUpdateRecordCall(vaultID, objectName, ID, body, _callback); + + } + + /** + * Update Record + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param body (required) + * @return V1UpdateRecordResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1UpdateRecordResponse recordServiceUpdateRecord(String vaultID, String objectName, String ID, RecordServiceUpdateRecordBody body) throws ApiException { + ApiResponse localVarResp = recordServiceUpdateRecordWithHttpInfo(vaultID, objectName, ID, body); + return localVarResp.getData(); + } + + /** + * Update Record + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param body (required) + * @return ApiResponse<V1UpdateRecordResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse recordServiceUpdateRecordWithHttpInfo(String vaultID, String objectName, String ID, RecordServiceUpdateRecordBody body) throws ApiException { + okhttp3.Call localVarCall = recordServiceUpdateRecordValidateBeforeCall(vaultID, objectName, ID, body, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Update Record (asynchronously) + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + * @param vaultID ID of the vault. (required) + * @param objectName Name of the table. (required) + * @param ID `skyflow_id` of the record. (required) + * @param body (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceUpdateRecordAsync(String vaultID, String objectName, String ID, RecordServiceUpdateRecordBody body, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = recordServiceUpdateRecordValidateBeforeCall(vaultID, objectName, ID, body, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/api/TokensApi.java b/v2/src/main/java/com/skyflow/generated/rest/api/TokensApi.java new file mode 100644 index 00000000..f2ec51a3 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/api/TokensApi.java @@ -0,0 +1,361 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.api; + +import com.skyflow.generated.rest.ApiCallback; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.ApiException; +import com.skyflow.generated.rest.ApiResponse; +import com.skyflow.generated.rest.Configuration; +import com.skyflow.generated.rest.Pair; +import com.skyflow.generated.rest.ProgressRequestBody; +import com.skyflow.generated.rest.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import com.skyflow.generated.rest.models.GooglerpcStatus; +import com.skyflow.generated.rest.models.V1DetokenizePayload; +import com.skyflow.generated.rest.models.V1DetokenizeResponse; +import com.skyflow.generated.rest.models.V1TokenizePayload; +import com.skyflow.generated.rest.models.V1TokenizeResponse; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class TokensApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public TokensApi() { + this(Configuration.getDefaultApiClient()); + } + + public TokensApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for recordServiceDetokenize + * @param vaultID ID of the vault. (required) + * @param detokenizePayload (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details +
+ + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceDetokenizeCall(String vaultID, V1DetokenizePayload detokenizePayload, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = detokenizePayload; + + // create path and map variables + String localVarPath = "/v1/vaults/{vaultID}/detokenize" + .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call recordServiceDetokenizeValidateBeforeCall(String vaultID, V1DetokenizePayload detokenizePayload, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'vaultID' is set + if (vaultID == null) { + throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceDetokenize(Async)"); + } + + // verify the required parameter 'detokenizePayload' is set + if (detokenizePayload == null) { + throw new ApiException("Missing the required parameter 'detokenizePayload' when calling recordServiceDetokenize(Async)"); + } + + return recordServiceDetokenizeCall(vaultID, detokenizePayload, _callback); + + } + + /** + * Detokenize + * Returns records that correspond to the specified tokens. + * @param vaultID ID of the vault. (required) + * @param detokenizePayload (required) + * @return V1DetokenizeResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1DetokenizeResponse recordServiceDetokenize(String vaultID, V1DetokenizePayload detokenizePayload) throws ApiException { + ApiResponse localVarResp = recordServiceDetokenizeWithHttpInfo(vaultID, detokenizePayload); + return localVarResp.getData(); + } + + /** + * Detokenize + * Returns records that correspond to the specified tokens. + * @param vaultID ID of the vault. (required) + * @param detokenizePayload (required) + * @return ApiResponse<V1DetokenizeResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse recordServiceDetokenizeWithHttpInfo(String vaultID, V1DetokenizePayload detokenizePayload) throws ApiException { + okhttp3.Call localVarCall = recordServiceDetokenizeValidateBeforeCall(vaultID, detokenizePayload, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Detokenize (asynchronously) + * Returns records that correspond to the specified tokens. + * @param vaultID ID of the vault. (required) + * @param detokenizePayload (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceDetokenizeAsync(String vaultID, V1DetokenizePayload detokenizePayload, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = recordServiceDetokenizeValidateBeforeCall(vaultID, detokenizePayload, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for recordServiceTokenize + * @param vaultID ID of the vault. (required) + * @param tokenizePayload (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceTokenizeCall(String vaultID, V1TokenizePayload tokenizePayload, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = tokenizePayload; + + // create path and map variables + String localVarPath = "/v1/vaults/{vaultID}/tokenize" + .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "Bearer" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call recordServiceTokenizeValidateBeforeCall(String vaultID, V1TokenizePayload tokenizePayload, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'vaultID' is set + if (vaultID == null) { + throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceTokenize(Async)"); + } + + // verify the required parameter 'tokenizePayload' is set + if (tokenizePayload == null) { + throw new ApiException("Missing the required parameter 'tokenizePayload' when calling recordServiceTokenize(Async)"); + } + + return recordServiceTokenizeCall(vaultID, tokenizePayload, _callback); + + } + + /** + * Tokenize + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + * @param vaultID ID of the vault. (required) + * @param tokenizePayload (required) + * @return V1TokenizeResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public V1TokenizeResponse recordServiceTokenize(String vaultID, V1TokenizePayload tokenizePayload) throws ApiException { + ApiResponse localVarResp = recordServiceTokenizeWithHttpInfo(vaultID, tokenizePayload); + return localVarResp.getData(); + } + + /** + * Tokenize + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + * @param vaultID ID of the vault. (required) + * @param tokenizePayload (required) + * @return ApiResponse<V1TokenizeResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public ApiResponse recordServiceTokenizeWithHttpInfo(String vaultID, V1TokenizePayload tokenizePayload) throws ApiException { + okhttp3.Call localVarCall = recordServiceTokenizeValidateBeforeCall(vaultID, tokenizePayload, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Tokenize (asynchronously) + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + * @param vaultID ID of the vault. (required) + * @param tokenizePayload (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
+ */ + public okhttp3.Call recordServiceTokenizeAsync(String vaultID, V1TokenizePayload tokenizePayload, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = recordServiceTokenizeValidateBeforeCall(vaultID, tokenizePayload, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java b/v2/src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java new file mode 100644 index 00000000..79949c2b --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java @@ -0,0 +1,80 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.auth; + +import com.skyflow.generated.rest.ApiException; +import com.skyflow.generated.rest.Pair; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.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/v2/src/main/java/com/skyflow/generated/rest/auth/Authentication.java b/v2/src/main/java/com/skyflow/generated/rest/auth/Authentication.java new file mode 100644 index 00000000..219caa17 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/auth/Authentication.java @@ -0,0 +1,36 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.auth; + +import com.skyflow.generated.rest.Pair; +import com.skyflow.generated.rest.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +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/v2/src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java b/v2/src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java new file mode 100644 index 00000000..5bf3124a --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java @@ -0,0 +1,55 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.auth; + +import com.skyflow.generated.rest.Pair; +import com.skyflow.generated.rest.ApiException; + +import okhttp3.Credentials; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +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/v2/src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java b/v2/src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java new file mode 100644 index 00000000..e8797964 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java @@ -0,0 +1,75 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.auth; + +import com.skyflow.generated.rest.ApiException; +import com.skyflow.generated.rest.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", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.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; + } +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java b/v2/src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java new file mode 100644 index 00000000..c506e085 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java @@ -0,0 +1,146 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import com.skyflow.generated.rest.ApiException; +import java.util.Objects; +import java.lang.reflect.Type; +import java.util.Map; + +/** + * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public abstract class AbstractOpenApiSchema { + + // store the actual instance of the schema/object + private Object instance; + + // is nullable + private Boolean isNullable; + + // schema type (e.g. oneOf, anyOf) + private final String schemaType; + + public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { + this.schemaType = schemaType; + this.isNullable = isNullable; + } + + /** + * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object + * + * @return an instance of the actual schema/object + */ + public abstract Map> getSchemas(); + + /** + * Get the actual instance + * + * @return an instance of the actual schema/object + */ + //@JsonValue + public Object getActualInstance() {return instance;} + + /** + * Set the actual instance + * + * @param instance the actual instance of the schema/object + */ + public void setActualInstance(Object instance) {this.instance = instance;} + + /** + * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well + * + * @return an instance of the actual schema/object + */ + public Object getActualInstanceRecursively() { + return getActualInstanceRecursively(this); + } + + private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { + if (object.getActualInstance() == null) { + return null; + } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { + return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); + } else { + return object.getActualInstance(); + } + } + + /** + * Get the schema type (e.g. anyOf, oneOf) + * + * @return the schema type + */ + public String getSchemaType() { + return schemaType; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ").append(getClass()).append(" {\n"); + sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); + sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); + sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; + return Objects.equals(this.instance, a.instance) && + Objects.equals(this.isNullable, a.isNullable) && + Objects.equals(this.schemaType, a.schemaType); + } + + @Override + public int hashCode() { + return Objects.hash(instance, isNullable, schemaType); + } + + /** + * Is nullable + * + * @return true if it's nullable + */ + public Boolean isNullable() { + if (Boolean.TRUE.equals(isNullable)) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + + +} diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java b/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java new file mode 100644 index 00000000..ee029542 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java @@ -0,0 +1,134 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Type of the resource. + */ +@JsonAdapter(AuditEventAuditResourceType.Adapter.class) +public enum AuditEventAuditResourceType { + + NONE_API("NONE_API"), + + ACCOUNT("ACCOUNT"), + + AUDIT("AUDIT"), + + BASE_DATA_TYPE("BASE_DATA_TYPE"), + + FIELD_TEMPLATE("FIELD_TEMPLATE"), + + FILE("FILE"), + + KEY("KEY"), + + POLICY("POLICY"), + + PROTO_PARSE("PROTO_PARSE"), + + RECORD("RECORD"), + + ROLE("ROLE"), + + RULE("RULE"), + + SECRET("SECRET"), + + SERVICE_ACCOUNT("SERVICE_ACCOUNT"), + + TOKEN("TOKEN"), + + USER("USER"), + + VAULT("VAULT"), + + VAULT_TEMPLATE("VAULT_TEMPLATE"), + + WORKSPACE("WORKSPACE"), + + TABLE("TABLE"), + + POLICY_TEMPLATE("POLICY_TEMPLATE"), + + MEMBER("MEMBER"), + + TAG("TAG"), + + CONNECTION("CONNECTION"), + + MIGRATION("MIGRATION"), + + SCHEDULED_JOB("SCHEDULED_JOB"), + + JOB("JOB"), + + COLUMN_NAME("COLUMN_NAME"), + + NETWORK_TOKEN("NETWORK_TOKEN"), + + SUBSCRIPTION("SUBSCRIPTION"); + + private String value; + + AuditEventAuditResourceType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static AuditEventAuditResourceType fromValue(String value) { + for (AuditEventAuditResourceType b : AuditEventAuditResourceType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final AuditEventAuditResourceType enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public AuditEventAuditResourceType read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return AuditEventAuditResourceType.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + AuditEventAuditResourceType.fromValue(value); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java b/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java new file mode 100644 index 00000000..5732e155 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java @@ -0,0 +1,530 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.ContextAccessType; +import com.skyflow.generated.rest.models.ContextAuthMode; +import com.skyflow.generated.rest.models.V1MemberType; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * Context for an audit event. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class AuditEventContext { + public static final String SERIALIZED_NAME_CHANGE_I_D = "changeID"; + @SerializedName(SERIALIZED_NAME_CHANGE_I_D) + private String changeID; + + public static final String SERIALIZED_NAME_REQUEST_I_D = "requestID"; + @SerializedName(SERIALIZED_NAME_REQUEST_I_D) + private String requestID; + + public static final String SERIALIZED_NAME_TRACE_I_D = "traceID"; + @SerializedName(SERIALIZED_NAME_TRACE_I_D) + private String traceID; + + public static final String SERIALIZED_NAME_SESSION_I_D = "sessionID"; + @SerializedName(SERIALIZED_NAME_SESSION_I_D) + private String sessionID; + + public static final String SERIALIZED_NAME_ACTOR = "actor"; + @SerializedName(SERIALIZED_NAME_ACTOR) + private String actor; + + public static final String SERIALIZED_NAME_ACTOR_TYPE = "actorType"; + @SerializedName(SERIALIZED_NAME_ACTOR_TYPE) + private V1MemberType actorType = V1MemberType.NONE; + + public static final String SERIALIZED_NAME_ACCESS_TYPE = "accessType"; + @SerializedName(SERIALIZED_NAME_ACCESS_TYPE) + private ContextAccessType accessType = ContextAccessType.ACCESS_NONE; + + public static final String SERIALIZED_NAME_IP_ADDRESS = "ipAddress"; + @SerializedName(SERIALIZED_NAME_IP_ADDRESS) + private String ipAddress; + + public static final String SERIALIZED_NAME_ORIGIN = "origin"; + @SerializedName(SERIALIZED_NAME_ORIGIN) + private String origin; + + public static final String SERIALIZED_NAME_AUTH_MODE = "authMode"; + @SerializedName(SERIALIZED_NAME_AUTH_MODE) + private ContextAuthMode authMode = ContextAuthMode.AUTH_NONE; + + public static final String SERIALIZED_NAME_JWT_I_D = "jwtID"; + @SerializedName(SERIALIZED_NAME_JWT_I_D) + private String jwtID; + + public static final String SERIALIZED_NAME_BEARER_TOKEN_CONTEXT_I_D = "bearerTokenContextID"; + @SerializedName(SERIALIZED_NAME_BEARER_TOKEN_CONTEXT_I_D) + private String bearerTokenContextID; + + public AuditEventContext() { + } + + public AuditEventContext changeID(String changeID) { + this.changeID = changeID; + return this; + } + + /** + * ID for the audit event. + * @return changeID + */ + @javax.annotation.Nullable + public String getChangeID() { + return changeID; + } + + public void setChangeID(String changeID) { + this.changeID = changeID; + } + + + public AuditEventContext requestID(String requestID) { + this.requestID = requestID; + return this; + } + + /** + * ID for the request that caused the event. + * @return requestID + */ + @javax.annotation.Nullable + public String getRequestID() { + return requestID; + } + + public void setRequestID(String requestID) { + this.requestID = requestID; + } + + + public AuditEventContext traceID(String traceID) { + this.traceID = traceID; + return this; + } + + /** + * ID for the request set by the service that received the request. + * @return traceID + */ + @javax.annotation.Nullable + public String getTraceID() { + return traceID; + } + + public void setTraceID(String traceID) { + this.traceID = traceID; + } + + + public AuditEventContext sessionID(String sessionID) { + this.sessionID = sessionID; + return this; + } + + /** + * ID for the session in which the request was sent. + * @return sessionID + */ + @javax.annotation.Nullable + public String getSessionID() { + return sessionID; + } + + public void setSessionID(String sessionID) { + this.sessionID = sessionID; + } + + + public AuditEventContext actor(String actor) { + this.actor = actor; + return this; + } + + /** + * Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. + * @return actor + */ + @javax.annotation.Nullable + public String getActor() { + return actor; + } + + public void setActor(String actor) { + this.actor = actor; + } + + + public AuditEventContext actorType(V1MemberType actorType) { + this.actorType = actorType; + return this; + } + + /** + * Get actorType + * @return actorType + */ + @javax.annotation.Nullable + public V1MemberType getActorType() { + return actorType; + } + + public void setActorType(V1MemberType actorType) { + this.actorType = actorType; + } + + + public AuditEventContext accessType(ContextAccessType accessType) { + this.accessType = accessType; + return this; + } + + /** + * Get accessType + * @return accessType + */ + @javax.annotation.Nullable + public ContextAccessType getAccessType() { + return accessType; + } + + public void setAccessType(ContextAccessType accessType) { + this.accessType = accessType; + } + + + public AuditEventContext ipAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + /** + * IP Address of the client that made the request. + * @return ipAddress + */ + @javax.annotation.Nullable + public String getIpAddress() { + return ipAddress; + } + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + + public AuditEventContext origin(String origin) { + this.origin = origin; + return this; + } + + /** + * HTTP Origin request header (including scheme, hostname, and port) of the request. + * @return origin + */ + @javax.annotation.Nullable + public String getOrigin() { + return origin; + } + + public void setOrigin(String origin) { + this.origin = origin; + } + + + public AuditEventContext authMode(ContextAuthMode authMode) { + this.authMode = authMode; + return this; + } + + /** + * Get authMode + * @return authMode + */ + @javax.annotation.Nullable + public ContextAuthMode getAuthMode() { + return authMode; + } + + public void setAuthMode(ContextAuthMode authMode) { + this.authMode = authMode; + } + + + public AuditEventContext jwtID(String jwtID) { + this.jwtID = jwtID; + return this; + } + + /** + * ID of the JWT token. + * @return jwtID + */ + @javax.annotation.Nullable + public String getJwtID() { + return jwtID; + } + + public void setJwtID(String jwtID) { + this.jwtID = jwtID; + } + + + public AuditEventContext bearerTokenContextID(String bearerTokenContextID) { + this.bearerTokenContextID = bearerTokenContextID; + return this; + } + + /** + * Embedded User Context. + * @return bearerTokenContextID + */ + @javax.annotation.Nullable + public String getBearerTokenContextID() { + return bearerTokenContextID; + } + + public void setBearerTokenContextID(String bearerTokenContextID) { + this.bearerTokenContextID = bearerTokenContextID; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AuditEventContext auditEventContext = (AuditEventContext) o; + return Objects.equals(this.changeID, auditEventContext.changeID) && + Objects.equals(this.requestID, auditEventContext.requestID) && + Objects.equals(this.traceID, auditEventContext.traceID) && + Objects.equals(this.sessionID, auditEventContext.sessionID) && + Objects.equals(this.actor, auditEventContext.actor) && + Objects.equals(this.actorType, auditEventContext.actorType) && + Objects.equals(this.accessType, auditEventContext.accessType) && + Objects.equals(this.ipAddress, auditEventContext.ipAddress) && + Objects.equals(this.origin, auditEventContext.origin) && + Objects.equals(this.authMode, auditEventContext.authMode) && + Objects.equals(this.jwtID, auditEventContext.jwtID) && + Objects.equals(this.bearerTokenContextID, auditEventContext.bearerTokenContextID); + } + + @Override + public int hashCode() { + return Objects.hash(changeID, requestID, traceID, sessionID, actor, actorType, accessType, ipAddress, origin, authMode, jwtID, bearerTokenContextID); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AuditEventContext {\n"); + sb.append(" changeID: ").append(toIndentedString(changeID)).append("\n"); + sb.append(" requestID: ").append(toIndentedString(requestID)).append("\n"); + sb.append(" traceID: ").append(toIndentedString(traceID)).append("\n"); + sb.append(" sessionID: ").append(toIndentedString(sessionID)).append("\n"); + sb.append(" actor: ").append(toIndentedString(actor)).append("\n"); + sb.append(" actorType: ").append(toIndentedString(actorType)).append("\n"); + sb.append(" accessType: ").append(toIndentedString(accessType)).append("\n"); + sb.append(" ipAddress: ").append(toIndentedString(ipAddress)).append("\n"); + sb.append(" origin: ").append(toIndentedString(origin)).append("\n"); + sb.append(" authMode: ").append(toIndentedString(authMode)).append("\n"); + sb.append(" jwtID: ").append(toIndentedString(jwtID)).append("\n"); + sb.append(" bearerTokenContextID: ").append(toIndentedString(bearerTokenContextID)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("changeID"); + openapiFields.add("requestID"); + openapiFields.add("traceID"); + openapiFields.add("sessionID"); + openapiFields.add("actor"); + openapiFields.add("actorType"); + openapiFields.add("accessType"); + openapiFields.add("ipAddress"); + openapiFields.add("origin"); + openapiFields.add("authMode"); + openapiFields.add("jwtID"); + openapiFields.add("bearerTokenContextID"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to AuditEventContext + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AuditEventContext.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AuditEventContext is not found in the empty JSON string", AuditEventContext.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!AuditEventContext.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AuditEventContext` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("changeID") != null && !jsonObj.get("changeID").isJsonNull()) && !jsonObj.get("changeID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `changeID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("changeID").toString())); + } + if ((jsonObj.get("requestID") != null && !jsonObj.get("requestID").isJsonNull()) && !jsonObj.get("requestID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `requestID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("requestID").toString())); + } + if ((jsonObj.get("traceID") != null && !jsonObj.get("traceID").isJsonNull()) && !jsonObj.get("traceID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `traceID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("traceID").toString())); + } + if ((jsonObj.get("sessionID") != null && !jsonObj.get("sessionID").isJsonNull()) && !jsonObj.get("sessionID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `sessionID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("sessionID").toString())); + } + if ((jsonObj.get("actor") != null && !jsonObj.get("actor").isJsonNull()) && !jsonObj.get("actor").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `actor` to be a primitive type in the JSON string but got `%s`", jsonObj.get("actor").toString())); + } + // validate the optional field `actorType` + if (jsonObj.get("actorType") != null && !jsonObj.get("actorType").isJsonNull()) { + V1MemberType.validateJsonElement(jsonObj.get("actorType")); + } + // validate the optional field `accessType` + if (jsonObj.get("accessType") != null && !jsonObj.get("accessType").isJsonNull()) { + ContextAccessType.validateJsonElement(jsonObj.get("accessType")); + } + if ((jsonObj.get("ipAddress") != null && !jsonObj.get("ipAddress").isJsonNull()) && !jsonObj.get("ipAddress").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `ipAddress` to be a primitive type in the JSON string but got `%s`", jsonObj.get("ipAddress").toString())); + } + if ((jsonObj.get("origin") != null && !jsonObj.get("origin").isJsonNull()) && !jsonObj.get("origin").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `origin` to be a primitive type in the JSON string but got `%s`", jsonObj.get("origin").toString())); + } + // validate the optional field `authMode` + if (jsonObj.get("authMode") != null && !jsonObj.get("authMode").isJsonNull()) { + ContextAuthMode.validateJsonElement(jsonObj.get("authMode")); + } + if ((jsonObj.get("jwtID") != null && !jsonObj.get("jwtID").isJsonNull()) && !jsonObj.get("jwtID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `jwtID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("jwtID").toString())); + } + if ((jsonObj.get("bearerTokenContextID") != null && !jsonObj.get("bearerTokenContextID").isJsonNull()) && !jsonObj.get("bearerTokenContextID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `bearerTokenContextID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bearerTokenContextID").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AuditEventContext.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AuditEventContext' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AuditEventContext.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AuditEventContext value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public AuditEventContext read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AuditEventContext given an JSON string + * + * @param jsonString JSON string + * @return An instance of AuditEventContext + * @throws IOException if the JSON string is invalid with respect to AuditEventContext + */ + public static AuditEventContext fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AuditEventContext.class); + } + + /** + * Convert an instance of AuditEventContext to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventData.java b/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventData.java new file mode 100644 index 00000000..4631467b --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventData.java @@ -0,0 +1,205 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * Any Sensitive data that needs to be wrapped. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class AuditEventData { + public static final String SERIALIZED_NAME_CONTENT = "content"; + @SerializedName(SERIALIZED_NAME_CONTENT) + private String content; + + public AuditEventData() { + } + + public AuditEventData content(String content) { + this.content = content; + return this; + } + + /** + * The entire body of the data requested or the query fired. + * @return content + */ + @javax.annotation.Nullable + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AuditEventData auditEventData = (AuditEventData) o; + return Objects.equals(this.content, auditEventData.content); + } + + @Override + public int hashCode() { + return Objects.hash(content); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AuditEventData {\n"); + sb.append(" content: ").append(toIndentedString(content)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("content"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to AuditEventData + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AuditEventData.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AuditEventData is not found in the empty JSON string", AuditEventData.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!AuditEventData.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AuditEventData` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("content") != null && !jsonObj.get("content").isJsonNull()) && !jsonObj.get("content").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `content` to be a primitive type in the JSON string but got `%s`", jsonObj.get("content").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AuditEventData.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AuditEventData' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AuditEventData.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AuditEventData value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public AuditEventData read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AuditEventData given an JSON string + * + * @param jsonString JSON string + * @return An instance of AuditEventData + * @throws IOException if the JSON string is invalid with respect to AuditEventData + */ + public static AuditEventData fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AuditEventData.class); + } + + /** + * Convert an instance of AuditEventData to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java b/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java new file mode 100644 index 00000000..8d35595f --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java @@ -0,0 +1,234 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * AuditEventHTTPInfo + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class AuditEventHTTPInfo { + public static final String SERIALIZED_NAME_U_R_I = "URI"; + @SerializedName(SERIALIZED_NAME_U_R_I) + private String URI; + + public static final String SERIALIZED_NAME_METHOD = "method"; + @SerializedName(SERIALIZED_NAME_METHOD) + private String method; + + public AuditEventHTTPInfo() { + } + + public AuditEventHTTPInfo URI(String URI) { + this.URI = URI; + return this; + } + + /** + * The http URI that is used. + * @return URI + */ + @javax.annotation.Nullable + public String getURI() { + return URI; + } + + public void setURI(String URI) { + this.URI = URI; + } + + + public AuditEventHTTPInfo method(String method) { + this.method = method; + return this; + } + + /** + * http method used. + * @return method + */ + @javax.annotation.Nullable + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AuditEventHTTPInfo auditEventHTTPInfo = (AuditEventHTTPInfo) o; + return Objects.equals(this.URI, auditEventHTTPInfo.URI) && + Objects.equals(this.method, auditEventHTTPInfo.method); + } + + @Override + public int hashCode() { + return Objects.hash(URI, method); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AuditEventHTTPInfo {\n"); + sb.append(" URI: ").append(toIndentedString(URI)).append("\n"); + sb.append(" method: ").append(toIndentedString(method)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("URI"); + openapiFields.add("method"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to AuditEventHTTPInfo + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AuditEventHTTPInfo.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AuditEventHTTPInfo is not found in the empty JSON string", AuditEventHTTPInfo.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!AuditEventHTTPInfo.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AuditEventHTTPInfo` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("URI") != null && !jsonObj.get("URI").isJsonNull()) && !jsonObj.get("URI").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `URI` to be a primitive type in the JSON string but got `%s`", jsonObj.get("URI").toString())); + } + if ((jsonObj.get("method") != null && !jsonObj.get("method").isJsonNull()) && !jsonObj.get("method").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `method` to be a primitive type in the JSON string but got `%s`", jsonObj.get("method").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AuditEventHTTPInfo.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AuditEventHTTPInfo' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AuditEventHTTPInfo.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AuditEventHTTPInfo value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public AuditEventHTTPInfo read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AuditEventHTTPInfo given an JSON string + * + * @param jsonString JSON string + * @return An instance of AuditEventHTTPInfo + * @throws IOException if the JSON string is invalid with respect to AuditEventHTTPInfo + */ + public static AuditEventHTTPInfo fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AuditEventHTTPInfo.class); + } + + /** + * Convert an instance of AuditEventHTTPInfo to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java b/v2/src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java new file mode 100644 index 00000000..4ef6d0f4 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java @@ -0,0 +1,84 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Method of the operation. + */ +@JsonAdapter(BatchRecordMethod.Adapter.class) +public enum BatchRecordMethod { + + NONE("NONE"), + + POST("POST"), + + PUT("PUT"), + + GET("GET"), + + DELETE("DELETE"); + + private String value; + + BatchRecordMethod(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static BatchRecordMethod fromValue(String value) { + for (BatchRecordMethod b : BatchRecordMethod.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final BatchRecordMethod enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public BatchRecordMethod read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return BatchRecordMethod.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + BatchRecordMethod.fromValue(value); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java b/v2/src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java new file mode 100644 index 00000000..92075e20 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java @@ -0,0 +1,80 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Type of access for the request. + */ +@JsonAdapter(ContextAccessType.Adapter.class) +public enum ContextAccessType { + + ACCESS_NONE("ACCESS_NONE"), + + API("API"), + + SQL("SQL"); + + private String value; + + ContextAccessType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static ContextAccessType fromValue(String value) { + for (ContextAccessType b : ContextAccessType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final ContextAccessType enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public ContextAccessType read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return ContextAccessType.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + ContextAccessType.fromValue(value); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java b/v2/src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java new file mode 100644 index 00000000..d0fc0afc --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java @@ -0,0 +1,82 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Authentication mode the `actor` used. + */ +@JsonAdapter(ContextAuthMode.Adapter.class) +public enum ContextAuthMode { + + AUTH_NONE("AUTH_NONE"), + + OKTA_JWT("OKTA_JWT"), + + SERVICE_ACCOUNT_JWT("SERVICE_ACCOUNT_JWT"), + + PAT_JWT("PAT_JWT"); + + private String value; + + ContextAuthMode(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static ContextAuthMode fromValue(String value) { + for (ContextAuthMode b : ContextAuthMode.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final ContextAuthMode enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public ContextAuthMode read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return ContextAuthMode.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + ContextAuthMode.fromValue(value); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java b/v2/src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java new file mode 100644 index 00000000..346833e6 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java @@ -0,0 +1,92 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Gets or Sets DetokenizeRecordResponseValueType + */ +@JsonAdapter(DetokenizeRecordResponseValueType.Adapter.class) +public enum DetokenizeRecordResponseValueType { + + NONE("NONE"), + + STRING("STRING"), + + INTEGER("INTEGER"), + + FLOAT("FLOAT"), + + BOOL("BOOL"), + + DATETIME("DATETIME"), + + JSON("JSON"), + + ARRAY("ARRAY"), + + DATE("DATE"); + + private String value; + + DetokenizeRecordResponseValueType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static DetokenizeRecordResponseValueType fromValue(String value) { + for (DetokenizeRecordResponseValueType b : DetokenizeRecordResponseValueType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final DetokenizeRecordResponseValueType enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public DetokenizeRecordResponseValueType read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return DetokenizeRecordResponseValueType.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + DetokenizeRecordResponseValueType.fromValue(value); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java b/v2/src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java new file mode 100644 index 00000000..44ca3e7f --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java @@ -0,0 +1,272 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.ProtobufAny; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * GooglerpcStatus + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class GooglerpcStatus { + public static final String SERIALIZED_NAME_CODE = "code"; + @SerializedName(SERIALIZED_NAME_CODE) + private Integer code; + + public static final String SERIALIZED_NAME_MESSAGE = "message"; + @SerializedName(SERIALIZED_NAME_MESSAGE) + private String message; + + public static final String SERIALIZED_NAME_DETAILS = "details"; + @SerializedName(SERIALIZED_NAME_DETAILS) + private List details = new ArrayList<>(); + + public GooglerpcStatus() { + } + + public GooglerpcStatus code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + */ + @javax.annotation.Nullable + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + + public GooglerpcStatus message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + */ + @javax.annotation.Nullable + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + public GooglerpcStatus details(List details) { + this.details = details; + return this; + } + + public GooglerpcStatus addDetailsItem(ProtobufAny detailsItem) { + if (this.details == null) { + this.details = new ArrayList<>(); + } + this.details.add(detailsItem); + return this; + } + + /** + * Get details + * @return details + */ + @javax.annotation.Nullable + public List getDetails() { + return details; + } + + public void setDetails(List details) { + this.details = details; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + GooglerpcStatus googlerpcStatus = (GooglerpcStatus) o; + return Objects.equals(this.code, googlerpcStatus.code) && + Objects.equals(this.message, googlerpcStatus.message) && + Objects.equals(this.details, googlerpcStatus.details); + } + + @Override + public int hashCode() { + return Objects.hash(code, message, details); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class GooglerpcStatus {\n"); + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append(" details: ").append(toIndentedString(details)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("code"); + openapiFields.add("message"); + openapiFields.add("details"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to GooglerpcStatus + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!GooglerpcStatus.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in GooglerpcStatus is not found in the empty JSON string", GooglerpcStatus.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!GooglerpcStatus.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `GooglerpcStatus` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("message") != null && !jsonObj.get("message").isJsonNull()) && !jsonObj.get("message").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString())); + } + // ensure the optional json data is an array if present + if (jsonObj.get("details") != null && !jsonObj.get("details").isJsonNull() && !jsonObj.get("details").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `details` to be an array in the JSON string but got `%s`", jsonObj.get("details").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!GooglerpcStatus.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'GooglerpcStatus' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(GooglerpcStatus.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, GooglerpcStatus value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public GooglerpcStatus read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of GooglerpcStatus given an JSON string + * + * @param jsonString JSON string + * @return An instance of GooglerpcStatus + * @throws IOException if the JSON string is invalid with respect to GooglerpcStatus + */ + public static GooglerpcStatus fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, GooglerpcStatus.class); + } + + /** + * Convert an instance of GooglerpcStatus to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java b/v2/src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java new file mode 100644 index 00000000..658d341e --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java @@ -0,0 +1,286 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * ProtobufAny + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class ProtobufAny { + public static final String SERIALIZED_NAME_AT_TYPE = "@type"; + @SerializedName(SERIALIZED_NAME_AT_TYPE) + private String atType; + + public ProtobufAny() { + } + + public ProtobufAny atType(String atType) { + this.atType = atType; + return this; + } + + /** + * Get atType + * @return atType + */ + @javax.annotation.Nullable + public String getAtType() { + return atType; + } + + public void setAtType(String atType) { + this.atType = atType; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ProtobufAny instance itself + */ + public ProtobufAny putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ProtobufAny protobufAny = (ProtobufAny) o; + return Objects.equals(this.atType, protobufAny.atType)&& + Objects.equals(this.additionalProperties, protobufAny.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(atType, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ProtobufAny {\n"); + sb.append(" atType: ").append(toIndentedString(atType)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("@type"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to ProtobufAny + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ProtobufAny.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in ProtobufAny is not found in the empty JSON string", ProtobufAny.openapiRequiredFields.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("@type") != null && !jsonObj.get("@type").isJsonNull()) && !jsonObj.get("@type").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `@type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("@type").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ProtobufAny.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ProtobufAny' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ProtobufAny.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ProtobufAny value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ProtobufAny read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ProtobufAny instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ProtobufAny given an JSON string + * + * @param jsonString JSON string + * @return An instance of ProtobufAny + * @throws IOException if the JSON string is invalid with respect to ProtobufAny + */ + public static ProtobufAny fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ProtobufAny.class); + } + + /** + * Convert an instance of ProtobufAny to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java b/v2/src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java new file mode 100644 index 00000000..3a7790a0 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java @@ -0,0 +1,205 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * QueryServiceExecuteQueryBody + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class QueryServiceExecuteQueryBody { + public static final String SERIALIZED_NAME_QUERY = "query"; + @SerializedName(SERIALIZED_NAME_QUERY) + private String query; + + public QueryServiceExecuteQueryBody() { + } + + public QueryServiceExecuteQueryBody query(String query) { + this.query = query; + return this; + } + + /** + * The SQL query to execute.<br><br><b>Supported commands:</b> <ul> <li><code>SELECT</code></li> </ul> <b>Supported operators:</b> <ul> <li><code>&gt;</code></li> <li><code>&lt;</code></li> <li><code>=</code></li> <li><code>AND</code></li> <li><code>OR</code></li> <li><code>NOT</code></li> <li><code>LIKE</code></li> <li><code>ILIKE</code></li> <li><code>NULL</code></li> <li><code>NOT NULL</code></li> </ul> <b>Supported keywords:</b> <ul> <li><code>FROM</code></li> <li><code>JOIN</code></li> <li><code>INNER JOIN</code></li> <li><code>LEFT OUTER JOIN</code></li> <li><code>LEFT JOIN</code></li> <li><code>RIGHT OUTER JOIN</code></li> <li><code>RIGHT JOIN</code></li> <li><code>FULL OUTER JOIN</code></li> <li><code>FULL JOIN</code></li> <li><code>OFFSET</code></li> <li><code>LIMIT</code></li> <li><code>WHERE</code></li> </ul> <b>Supported functions:</b> <ul> <li><code>AVG()</code></li> <li><code>SUM()</code></li> <li><code>COUNT()</code></li> <li><code>MIN()</code></li> <li><code>MAX()</code></li> <li><code>REDACTION()</code></li> </ul> + * @return query + */ + @javax.annotation.Nullable + public String getQuery() { + return query; + } + + public void setQuery(String query) { + this.query = query; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + QueryServiceExecuteQueryBody queryServiceExecuteQueryBody = (QueryServiceExecuteQueryBody) o; + return Objects.equals(this.query, queryServiceExecuteQueryBody.query); + } + + @Override + public int hashCode() { + return Objects.hash(query); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class QueryServiceExecuteQueryBody {\n"); + sb.append(" query: ").append(toIndentedString(query)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("query"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to QueryServiceExecuteQueryBody + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!QueryServiceExecuteQueryBody.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in QueryServiceExecuteQueryBody is not found in the empty JSON string", QueryServiceExecuteQueryBody.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!QueryServiceExecuteQueryBody.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `QueryServiceExecuteQueryBody` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("query") != null && !jsonObj.get("query").isJsonNull()) && !jsonObj.get("query").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `query` to be a primitive type in the JSON string but got `%s`", jsonObj.get("query").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!QueryServiceExecuteQueryBody.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'QueryServiceExecuteQueryBody' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(QueryServiceExecuteQueryBody.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, QueryServiceExecuteQueryBody value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public QueryServiceExecuteQueryBody read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of QueryServiceExecuteQueryBody given an JSON string + * + * @param jsonString JSON string + * @return An instance of QueryServiceExecuteQueryBody + * @throws IOException if the JSON string is invalid with respect to QueryServiceExecuteQueryBody + */ + public static QueryServiceExecuteQueryBody fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, QueryServiceExecuteQueryBody.class); + } + + /** + * Convert an instance of QueryServiceExecuteQueryBody to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java b/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java new file mode 100644 index 00000000..ec0c3f95 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java @@ -0,0 +1,284 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1BYOT; +import com.skyflow.generated.rest.models.V1BatchRecord; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * RecordServiceBatchOperationBody + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class RecordServiceBatchOperationBody { + public static final String SERIALIZED_NAME_RECORDS = "records"; + @SerializedName(SERIALIZED_NAME_RECORDS) + private List records = new ArrayList<>(); + + public static final String SERIALIZED_NAME_CONTINUE_ON_ERROR = "continueOnError"; + @SerializedName(SERIALIZED_NAME_CONTINUE_ON_ERROR) + private Boolean continueOnError; + + public static final String SERIALIZED_NAME_BYOT = "byot"; + @SerializedName(SERIALIZED_NAME_BYOT) + private V1BYOT byot = V1BYOT.DISABLE; + + public RecordServiceBatchOperationBody() { + } + + public RecordServiceBatchOperationBody records(List records) { + this.records = records; + return this; + } + + public RecordServiceBatchOperationBody addRecordsItem(V1BatchRecord recordsItem) { + if (this.records == null) { + this.records = new ArrayList<>(); + } + this.records.add(recordsItem); + return this; + } + + /** + * Record operations to perform. + * @return records + */ + @javax.annotation.Nullable + public List getRecords() { + return records; + } + + public void setRecords(List records) { + this.records = records; + } + + + public RecordServiceBatchOperationBody continueOnError(Boolean continueOnError) { + this.continueOnError = continueOnError; + return this; + } + + /** + * Continue performing operations on partial errors. + * @return continueOnError + */ + @javax.annotation.Nullable + public Boolean getContinueOnError() { + return continueOnError; + } + + public void setContinueOnError(Boolean continueOnError) { + this.continueOnError = continueOnError; + } + + + public RecordServiceBatchOperationBody byot(V1BYOT byot) { + this.byot = byot; + return this; + } + + /** + * Get byot + * @return byot + */ + @javax.annotation.Nullable + public V1BYOT getByot() { + return byot; + } + + public void setByot(V1BYOT byot) { + this.byot = byot; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + RecordServiceBatchOperationBody recordServiceBatchOperationBody = (RecordServiceBatchOperationBody) o; + return Objects.equals(this.records, recordServiceBatchOperationBody.records) && + Objects.equals(this.continueOnError, recordServiceBatchOperationBody.continueOnError) && + Objects.equals(this.byot, recordServiceBatchOperationBody.byot); + } + + @Override + public int hashCode() { + return Objects.hash(records, continueOnError, byot); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class RecordServiceBatchOperationBody {\n"); + sb.append(" records: ").append(toIndentedString(records)).append("\n"); + sb.append(" continueOnError: ").append(toIndentedString(continueOnError)).append("\n"); + sb.append(" byot: ").append(toIndentedString(byot)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("records"); + openapiFields.add("continueOnError"); + openapiFields.add("byot"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to RecordServiceBatchOperationBody + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!RecordServiceBatchOperationBody.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in RecordServiceBatchOperationBody is not found in the empty JSON string", RecordServiceBatchOperationBody.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!RecordServiceBatchOperationBody.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `RecordServiceBatchOperationBody` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { + JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); + if (jsonArrayrecords != null) { + // ensure the json data is an array + if (!jsonObj.get("records").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); + } + + // validate the optional field `records` (array) + for (int i = 0; i < jsonArrayrecords.size(); i++) { + V1BatchRecord.validateJsonElement(jsonArrayrecords.get(i)); + }; + } + } + // validate the optional field `byot` + if (jsonObj.get("byot") != null && !jsonObj.get("byot").isJsonNull()) { + V1BYOT.validateJsonElement(jsonObj.get("byot")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!RecordServiceBatchOperationBody.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'RecordServiceBatchOperationBody' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(RecordServiceBatchOperationBody.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, RecordServiceBatchOperationBody value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public RecordServiceBatchOperationBody read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of RecordServiceBatchOperationBody given an JSON string + * + * @param jsonString JSON string + * @return An instance of RecordServiceBatchOperationBody + * @throws IOException if the JSON string is invalid with respect to RecordServiceBatchOperationBody + */ + public static RecordServiceBatchOperationBody fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, RecordServiceBatchOperationBody.class); + } + + /** + * Convert an instance of RecordServiceBatchOperationBody to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java b/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java new file mode 100644 index 00000000..b7358e49 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java @@ -0,0 +1,216 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * RecordServiceBulkDeleteRecordBody + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class RecordServiceBulkDeleteRecordBody { + public static final String SERIALIZED_NAME_SKYFLOW_IDS = "skyflow_ids"; + @SerializedName(SERIALIZED_NAME_SKYFLOW_IDS) + private List skyflowIds = new ArrayList<>(); + + public RecordServiceBulkDeleteRecordBody() { + } + + public RecordServiceBulkDeleteRecordBody skyflowIds(List skyflowIds) { + this.skyflowIds = skyflowIds; + return this; + } + + public RecordServiceBulkDeleteRecordBody addSkyflowIdsItem(String skyflowIdsItem) { + if (this.skyflowIds == null) { + this.skyflowIds = new ArrayList<>(); + } + this.skyflowIds.add(skyflowIdsItem); + return this; + } + + /** + * `skyflow_id` values of the records to delete. If `*` is specified, this operation deletes all records in the table. + * @return skyflowIds + */ + @javax.annotation.Nullable + public List getSkyflowIds() { + return skyflowIds; + } + + public void setSkyflowIds(List skyflowIds) { + this.skyflowIds = skyflowIds; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + RecordServiceBulkDeleteRecordBody recordServiceBulkDeleteRecordBody = (RecordServiceBulkDeleteRecordBody) o; + return Objects.equals(this.skyflowIds, recordServiceBulkDeleteRecordBody.skyflowIds); + } + + @Override + public int hashCode() { + return Objects.hash(skyflowIds); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class RecordServiceBulkDeleteRecordBody {\n"); + sb.append(" skyflowIds: ").append(toIndentedString(skyflowIds)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("skyflow_ids"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to RecordServiceBulkDeleteRecordBody + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!RecordServiceBulkDeleteRecordBody.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in RecordServiceBulkDeleteRecordBody is not found in the empty JSON string", RecordServiceBulkDeleteRecordBody.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!RecordServiceBulkDeleteRecordBody.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `RecordServiceBulkDeleteRecordBody` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // ensure the optional json data is an array if present + if (jsonObj.get("skyflow_ids") != null && !jsonObj.get("skyflow_ids").isJsonNull() && !jsonObj.get("skyflow_ids").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `skyflow_ids` to be an array in the JSON string but got `%s`", jsonObj.get("skyflow_ids").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!RecordServiceBulkDeleteRecordBody.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'RecordServiceBulkDeleteRecordBody' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(RecordServiceBulkDeleteRecordBody.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, RecordServiceBulkDeleteRecordBody value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public RecordServiceBulkDeleteRecordBody read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of RecordServiceBulkDeleteRecordBody given an JSON string + * + * @param jsonString JSON string + * @return An instance of RecordServiceBulkDeleteRecordBody + * @throws IOException if the JSON string is invalid with respect to RecordServiceBulkDeleteRecordBody + */ + public static RecordServiceBulkDeleteRecordBody fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, RecordServiceBulkDeleteRecordBody.class); + } + + /** + * Convert an instance of RecordServiceBulkDeleteRecordBody to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java b/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java new file mode 100644 index 00000000..0ffe7ce8 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java @@ -0,0 +1,339 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1BYOT; +import com.skyflow.generated.rest.models.V1FieldRecords; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * RecordServiceInsertRecordBody + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class RecordServiceInsertRecordBody { + public static final String SERIALIZED_NAME_RECORDS = "records"; + @SerializedName(SERIALIZED_NAME_RECORDS) + private List records = new ArrayList<>(); + + public static final String SERIALIZED_NAME_TOKENIZATION = "tokenization"; + @SerializedName(SERIALIZED_NAME_TOKENIZATION) + private Boolean tokenization; + + public static final String SERIALIZED_NAME_UPSERT = "upsert"; + @SerializedName(SERIALIZED_NAME_UPSERT) + private String upsert; + + public static final String SERIALIZED_NAME_HOMOGENEOUS = "homogeneous"; + @SerializedName(SERIALIZED_NAME_HOMOGENEOUS) + private Boolean homogeneous = false; + + public static final String SERIALIZED_NAME_BYOT = "byot"; + @SerializedName(SERIALIZED_NAME_BYOT) + private V1BYOT byot = V1BYOT.DISABLE; + + public RecordServiceInsertRecordBody() { + } + + public RecordServiceInsertRecordBody records(List records) { + this.records = records; + return this; + } + + public RecordServiceInsertRecordBody addRecordsItem(V1FieldRecords recordsItem) { + if (this.records == null) { + this.records = new ArrayList<>(); + } + this.records.add(recordsItem); + return this; + } + + /** + * Record values and tokens. + * @return records + */ + @javax.annotation.Nullable + public List getRecords() { + return records; + } + + public void setRecords(List records) { + this.records = records; + } + + + public RecordServiceInsertRecordBody tokenization(Boolean tokenization) { + this.tokenization = tokenization; + return this; + } + + /** + * If `true`, this operation returns tokens for fields with tokenization enabled. + * @return tokenization + */ + @javax.annotation.Nullable + public Boolean getTokenization() { + return tokenization; + } + + public void setTokenization(Boolean tokenization) { + this.tokenization = tokenization; + } + + + public RecordServiceInsertRecordBody upsert(String upsert) { + this.upsert = upsert; + return this; + } + + /** + * Name of a unique column in the table. Uses upsert operations to check if a record exists based on the unique column's value. If a matching record exists, the record updates with the values you provide. If a matching record doesn't exist, the upsert operation inserts a new record.<br /><br />When you upsert a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed. + * @return upsert + */ + @javax.annotation.Nullable + public String getUpsert() { + return upsert; + } + + public void setUpsert(String upsert) { + this.upsert = upsert; + } + + + public RecordServiceInsertRecordBody homogeneous(Boolean homogeneous) { + this.homogeneous = homogeneous; + return this; + } + + /** + * If `true`, this operation mandates that all the records have the same fields. This parameter does not work with upsert. + * @return homogeneous + */ + @javax.annotation.Nullable + public Boolean getHomogeneous() { + return homogeneous; + } + + public void setHomogeneous(Boolean homogeneous) { + this.homogeneous = homogeneous; + } + + + public RecordServiceInsertRecordBody byot(V1BYOT byot) { + this.byot = byot; + return this; + } + + /** + * Get byot + * @return byot + */ + @javax.annotation.Nullable + public V1BYOT getByot() { + return byot; + } + + public void setByot(V1BYOT byot) { + this.byot = byot; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + RecordServiceInsertRecordBody recordServiceInsertRecordBody = (RecordServiceInsertRecordBody) o; + return Objects.equals(this.records, recordServiceInsertRecordBody.records) && + Objects.equals(this.tokenization, recordServiceInsertRecordBody.tokenization) && + Objects.equals(this.upsert, recordServiceInsertRecordBody.upsert) && + Objects.equals(this.homogeneous, recordServiceInsertRecordBody.homogeneous) && + Objects.equals(this.byot, recordServiceInsertRecordBody.byot); + } + + @Override + public int hashCode() { + return Objects.hash(records, tokenization, upsert, homogeneous, byot); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class RecordServiceInsertRecordBody {\n"); + sb.append(" records: ").append(toIndentedString(records)).append("\n"); + sb.append(" tokenization: ").append(toIndentedString(tokenization)).append("\n"); + sb.append(" upsert: ").append(toIndentedString(upsert)).append("\n"); + sb.append(" homogeneous: ").append(toIndentedString(homogeneous)).append("\n"); + sb.append(" byot: ").append(toIndentedString(byot)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("records"); + openapiFields.add("tokenization"); + openapiFields.add("upsert"); + openapiFields.add("homogeneous"); + openapiFields.add("byot"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to RecordServiceInsertRecordBody + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!RecordServiceInsertRecordBody.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in RecordServiceInsertRecordBody is not found in the empty JSON string", RecordServiceInsertRecordBody.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!RecordServiceInsertRecordBody.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `RecordServiceInsertRecordBody` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { + JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); + if (jsonArrayrecords != null) { + // ensure the json data is an array + if (!jsonObj.get("records").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); + } + + // validate the optional field `records` (array) + for (int i = 0; i < jsonArrayrecords.size(); i++) { + V1FieldRecords.validateJsonElement(jsonArrayrecords.get(i)); + }; + } + } + if ((jsonObj.get("upsert") != null && !jsonObj.get("upsert").isJsonNull()) && !jsonObj.get("upsert").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `upsert` to be a primitive type in the JSON string but got `%s`", jsonObj.get("upsert").toString())); + } + // validate the optional field `byot` + if (jsonObj.get("byot") != null && !jsonObj.get("byot").isJsonNull()) { + V1BYOT.validateJsonElement(jsonObj.get("byot")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!RecordServiceInsertRecordBody.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'RecordServiceInsertRecordBody' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(RecordServiceInsertRecordBody.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, RecordServiceInsertRecordBody value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public RecordServiceInsertRecordBody read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of RecordServiceInsertRecordBody given an JSON string + * + * @param jsonString JSON string + * @return An instance of RecordServiceInsertRecordBody + * @throws IOException if the JSON string is invalid with respect to RecordServiceInsertRecordBody + */ + public static RecordServiceInsertRecordBody fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, RecordServiceInsertRecordBody.class); + } + + /** + * Convert an instance of RecordServiceInsertRecordBody to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java b/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java new file mode 100644 index 00000000..27e8f48a --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java @@ -0,0 +1,264 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1BYOT; +import com.skyflow.generated.rest.models.V1FieldRecords; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * RecordServiceUpdateRecordBody + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class RecordServiceUpdateRecordBody { + public static final String SERIALIZED_NAME_RECORD = "record"; + @SerializedName(SERIALIZED_NAME_RECORD) + private V1FieldRecords record; + + public static final String SERIALIZED_NAME_TOKENIZATION = "tokenization"; + @SerializedName(SERIALIZED_NAME_TOKENIZATION) + private Boolean tokenization; + + public static final String SERIALIZED_NAME_BYOT = "byot"; + @SerializedName(SERIALIZED_NAME_BYOT) + private V1BYOT byot = V1BYOT.DISABLE; + + public RecordServiceUpdateRecordBody() { + } + + public RecordServiceUpdateRecordBody record(V1FieldRecords record) { + this.record = record; + return this; + } + + /** + * Get record + * @return record + */ + @javax.annotation.Nullable + public V1FieldRecords getRecord() { + return record; + } + + public void setRecord(V1FieldRecords record) { + this.record = record; + } + + + public RecordServiceUpdateRecordBody tokenization(Boolean tokenization) { + this.tokenization = tokenization; + return this; + } + + /** + * If `true`, this operation returns tokens for fields with tokenization enabled. + * @return tokenization + */ + @javax.annotation.Nullable + public Boolean getTokenization() { + return tokenization; + } + + public void setTokenization(Boolean tokenization) { + this.tokenization = tokenization; + } + + + public RecordServiceUpdateRecordBody byot(V1BYOT byot) { + this.byot = byot; + return this; + } + + /** + * Get byot + * @return byot + */ + @javax.annotation.Nullable + public V1BYOT getByot() { + return byot; + } + + public void setByot(V1BYOT byot) { + this.byot = byot; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + RecordServiceUpdateRecordBody recordServiceUpdateRecordBody = (RecordServiceUpdateRecordBody) o; + return Objects.equals(this.record, recordServiceUpdateRecordBody.record) && + Objects.equals(this.tokenization, recordServiceUpdateRecordBody.tokenization) && + Objects.equals(this.byot, recordServiceUpdateRecordBody.byot); + } + + @Override + public int hashCode() { + return Objects.hash(record, tokenization, byot); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class RecordServiceUpdateRecordBody {\n"); + sb.append(" record: ").append(toIndentedString(record)).append("\n"); + sb.append(" tokenization: ").append(toIndentedString(tokenization)).append("\n"); + sb.append(" byot: ").append(toIndentedString(byot)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("record"); + openapiFields.add("tokenization"); + openapiFields.add("byot"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to RecordServiceUpdateRecordBody + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!RecordServiceUpdateRecordBody.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in RecordServiceUpdateRecordBody is not found in the empty JSON string", RecordServiceUpdateRecordBody.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!RecordServiceUpdateRecordBody.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `RecordServiceUpdateRecordBody` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `record` + if (jsonObj.get("record") != null && !jsonObj.get("record").isJsonNull()) { + V1FieldRecords.validateJsonElement(jsonObj.get("record")); + } + // validate the optional field `byot` + if (jsonObj.get("byot") != null && !jsonObj.get("byot").isJsonNull()) { + V1BYOT.validateJsonElement(jsonObj.get("byot")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!RecordServiceUpdateRecordBody.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'RecordServiceUpdateRecordBody' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(RecordServiceUpdateRecordBody.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, RecordServiceUpdateRecordBody value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public RecordServiceUpdateRecordBody read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of RecordServiceUpdateRecordBody given an JSON string + * + * @param jsonString JSON string + * @return An instance of RecordServiceUpdateRecordBody + * @throws IOException if the JSON string is invalid with respect to RecordServiceUpdateRecordBody + */ + public static RecordServiceUpdateRecordBody fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, RecordServiceUpdateRecordBody.class); + } + + /** + * Convert an instance of RecordServiceUpdateRecordBody to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java b/v2/src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java new file mode 100644 index 00000000..e0c8ea98 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java @@ -0,0 +1,82 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Redaction type. Subject to policies assigned to the API caller. When used for detokenization, only supported for vaults that support [column groups](/tokenization-column-groups/). + */ +@JsonAdapter(RedactionEnumREDACTION.Adapter.class) +public enum RedactionEnumREDACTION { + + DEFAULT("DEFAULT"), + + REDACTED("REDACTED"), + + MASKED("MASKED"), + + PLAIN_TEXT("PLAIN_TEXT"); + + private String value; + + RedactionEnumREDACTION(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static RedactionEnumREDACTION fromValue(String value) { + for (RedactionEnumREDACTION b : RedactionEnumREDACTION.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final RedactionEnumREDACTION enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public RedactionEnumREDACTION read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return RedactionEnumREDACTION.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + RedactionEnumREDACTION.fromValue(value); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/RequestActionType.java b/v2/src/main/java/com/skyflow/generated/rest/models/RequestActionType.java new file mode 100644 index 00000000..d5e979d8 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/RequestActionType.java @@ -0,0 +1,110 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Gets or Sets RequestActionType + */ +@JsonAdapter(RequestActionType.Adapter.class) +public enum RequestActionType { + + NONE("NONE"), + + ASSIGN("ASSIGN"), + + CREATE("CREATE"), + + DELETE("DELETE"), + + EXECUTE("EXECUTE"), + + LIST("LIST"), + + READ("READ"), + + UNASSIGN("UNASSIGN"), + + UPDATE("UPDATE"), + + VALIDATE("VALIDATE"), + + LOGIN("LOGIN"), + + ROTATE("ROTATE"), + + SCHEDULEROTATION("SCHEDULEROTATION"), + + SCHEDULEROTATIONALERT("SCHEDULEROTATIONALERT"), + + IMPORT("IMPORT"), + + GETIMPORTPARAMETERS("GETIMPORTPARAMETERS"), + + PING("PING"), + + GETCLOUDPROVIDER("GETCLOUDPROVIDER"); + + private String value; + + RequestActionType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static RequestActionType fromValue(String value) { + for (RequestActionType b : RequestActionType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final RequestActionType enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public RequestActionType read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return RequestActionType.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + RequestActionType.fromValue(value); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java new file mode 100644 index 00000000..faf2c5b3 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java @@ -0,0 +1,234 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1AuditAfterOptions + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1AuditAfterOptions { + public static final String SERIALIZED_NAME_TIMESTAMP = "timestamp"; + @SerializedName(SERIALIZED_NAME_TIMESTAMP) + private String timestamp; + + public static final String SERIALIZED_NAME_CHANGE_I_D = "changeID"; + @SerializedName(SERIALIZED_NAME_CHANGE_I_D) + private String changeID; + + public V1AuditAfterOptions() { + } + + public V1AuditAfterOptions timestamp(String timestamp) { + this.timestamp = timestamp; + return this; + } + + /** + * Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. + * @return timestamp + */ + @javax.annotation.Nullable + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + + public V1AuditAfterOptions changeID(String changeID) { + this.changeID = changeID; + return this; + } + + /** + * Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. + * @return changeID + */ + @javax.annotation.Nullable + public String getChangeID() { + return changeID; + } + + public void setChangeID(String changeID) { + this.changeID = changeID; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1AuditAfterOptions v1AuditAfterOptions = (V1AuditAfterOptions) o; + return Objects.equals(this.timestamp, v1AuditAfterOptions.timestamp) && + Objects.equals(this.changeID, v1AuditAfterOptions.changeID); + } + + @Override + public int hashCode() { + return Objects.hash(timestamp, changeID); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1AuditAfterOptions {\n"); + sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); + sb.append(" changeID: ").append(toIndentedString(changeID)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("timestamp"); + openapiFields.add("changeID"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1AuditAfterOptions + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1AuditAfterOptions.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1AuditAfterOptions is not found in the empty JSON string", V1AuditAfterOptions.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1AuditAfterOptions.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1AuditAfterOptions` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("timestamp") != null && !jsonObj.get("timestamp").isJsonNull()) && !jsonObj.get("timestamp").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `timestamp` to be a primitive type in the JSON string but got `%s`", jsonObj.get("timestamp").toString())); + } + if ((jsonObj.get("changeID") != null && !jsonObj.get("changeID").isJsonNull()) && !jsonObj.get("changeID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `changeID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("changeID").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1AuditAfterOptions.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1AuditAfterOptions' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1AuditAfterOptions.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1AuditAfterOptions value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1AuditAfterOptions read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1AuditAfterOptions given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1AuditAfterOptions + * @throws IOException if the JSON string is invalid with respect to V1AuditAfterOptions + */ + public static V1AuditAfterOptions fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1AuditAfterOptions.class); + } + + /** + * Convert an instance of V1AuditAfterOptions to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java new file mode 100644 index 00000000..97134351 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java @@ -0,0 +1,291 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.AuditEventData; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * Contains fields for defining Response Properties. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1AuditEventResponse { + public static final String SERIALIZED_NAME_CODE = "code"; + @SerializedName(SERIALIZED_NAME_CODE) + private Integer code; + + public static final String SERIALIZED_NAME_MESSAGE = "message"; + @SerializedName(SERIALIZED_NAME_MESSAGE) + private String message; + + public static final String SERIALIZED_NAME_DATA = "data"; + @SerializedName(SERIALIZED_NAME_DATA) + private AuditEventData data; + + public static final String SERIALIZED_NAME_TIMESTAMP = "timestamp"; + @SerializedName(SERIALIZED_NAME_TIMESTAMP) + private String timestamp; + + public V1AuditEventResponse() { + } + + public V1AuditEventResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * The status of the overall operation. + * @return code + */ + @javax.annotation.Nullable + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + + public V1AuditEventResponse message(String message) { + this.message = message; + return this; + } + + /** + * The status message for the overall operation. + * @return message + */ + @javax.annotation.Nullable + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + public V1AuditEventResponse data(AuditEventData data) { + this.data = data; + return this; + } + + /** + * Get data + * @return data + */ + @javax.annotation.Nullable + public AuditEventData getData() { + return data; + } + + public void setData(AuditEventData data) { + this.data = data; + } + + + public V1AuditEventResponse timestamp(String timestamp) { + this.timestamp = timestamp; + return this; + } + + /** + * time when this response is generated, use extention method to set it. + * @return timestamp + */ + @javax.annotation.Nullable + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1AuditEventResponse v1AuditEventResponse = (V1AuditEventResponse) o; + return Objects.equals(this.code, v1AuditEventResponse.code) && + Objects.equals(this.message, v1AuditEventResponse.message) && + Objects.equals(this.data, v1AuditEventResponse.data) && + Objects.equals(this.timestamp, v1AuditEventResponse.timestamp); + } + + @Override + public int hashCode() { + return Objects.hash(code, message, data, timestamp); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1AuditEventResponse {\n"); + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("code"); + openapiFields.add("message"); + openapiFields.add("data"); + openapiFields.add("timestamp"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1AuditEventResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1AuditEventResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1AuditEventResponse is not found in the empty JSON string", V1AuditEventResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1AuditEventResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1AuditEventResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("message") != null && !jsonObj.get("message").isJsonNull()) && !jsonObj.get("message").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString())); + } + // validate the optional field `data` + if (jsonObj.get("data") != null && !jsonObj.get("data").isJsonNull()) { + AuditEventData.validateJsonElement(jsonObj.get("data")); + } + if ((jsonObj.get("timestamp") != null && !jsonObj.get("timestamp").isJsonNull()) && !jsonObj.get("timestamp").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `timestamp` to be a primitive type in the JSON string but got `%s`", jsonObj.get("timestamp").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1AuditEventResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1AuditEventResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1AuditEventResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1AuditEventResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1AuditEventResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1AuditEventResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1AuditEventResponse + * @throws IOException if the JSON string is invalid with respect to V1AuditEventResponse + */ + public static V1AuditEventResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1AuditEventResponse.class); + } + + /** + * Convert an instance of V1AuditEventResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java new file mode 100644 index 00000000..1d0268b4 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java @@ -0,0 +1,258 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1AuditAfterOptions; +import com.skyflow.generated.rest.models.V1AuditResponseEvent; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1AuditResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1AuditResponse { + public static final String SERIALIZED_NAME_EVENT = "event"; + @SerializedName(SERIALIZED_NAME_EVENT) + private List event = new ArrayList<>(); + + public static final String SERIALIZED_NAME_NEXT_OPS = "nextOps"; + @SerializedName(SERIALIZED_NAME_NEXT_OPS) + private V1AuditAfterOptions nextOps; + + public V1AuditResponse() { + } + + public V1AuditResponse event(List event) { + this.event = event; + return this; + } + + public V1AuditResponse addEventItem(V1AuditResponseEvent eventItem) { + if (this.event == null) { + this.event = new ArrayList<>(); + } + this.event.add(eventItem); + return this; + } + + /** + * Events matching the query. + * @return event + */ + @javax.annotation.Nullable + public List getEvent() { + return event; + } + + public void setEvent(List event) { + this.event = event; + } + + + public V1AuditResponse nextOps(V1AuditAfterOptions nextOps) { + this.nextOps = nextOps; + return this; + } + + /** + * Get nextOps + * @return nextOps + */ + @javax.annotation.Nullable + public V1AuditAfterOptions getNextOps() { + return nextOps; + } + + public void setNextOps(V1AuditAfterOptions nextOps) { + this.nextOps = nextOps; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1AuditResponse v1AuditResponse = (V1AuditResponse) o; + return Objects.equals(this.event, v1AuditResponse.event) && + Objects.equals(this.nextOps, v1AuditResponse.nextOps); + } + + @Override + public int hashCode() { + return Objects.hash(event, nextOps); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1AuditResponse {\n"); + sb.append(" event: ").append(toIndentedString(event)).append("\n"); + sb.append(" nextOps: ").append(toIndentedString(nextOps)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("event"); + openapiFields.add("nextOps"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1AuditResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1AuditResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1AuditResponse is not found in the empty JSON string", V1AuditResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1AuditResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1AuditResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (jsonObj.get("event") != null && !jsonObj.get("event").isJsonNull()) { + JsonArray jsonArrayevent = jsonObj.getAsJsonArray("event"); + if (jsonArrayevent != null) { + // ensure the json data is an array + if (!jsonObj.get("event").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `event` to be an array in the JSON string but got `%s`", jsonObj.get("event").toString())); + } + + // validate the optional field `event` (array) + for (int i = 0; i < jsonArrayevent.size(); i++) { + V1AuditResponseEvent.validateJsonElement(jsonArrayevent.get(i)); + }; + } + } + // validate the optional field `nextOps` + if (jsonObj.get("nextOps") != null && !jsonObj.get("nextOps").isJsonNull()) { + V1AuditAfterOptions.validateJsonElement(jsonObj.get("nextOps")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1AuditResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1AuditResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1AuditResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1AuditResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1AuditResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1AuditResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1AuditResponse + * @throws IOException if the JSON string is invalid with respect to V1AuditResponse + */ + public static V1AuditResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1AuditResponse.class); + } + + /** + * Convert an instance of V1AuditResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java new file mode 100644 index 00000000..0e2070ae --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java @@ -0,0 +1,367 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.AuditEventContext; +import com.skyflow.generated.rest.models.V1AuditEventResponse; +import com.skyflow.generated.rest.models.V1AuditResponseEventRequest; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * Audit event details. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1AuditResponseEvent { + public static final String SERIALIZED_NAME_CONTEXT = "context"; + @SerializedName(SERIALIZED_NAME_CONTEXT) + private AuditEventContext context; + + public static final String SERIALIZED_NAME_REQUEST = "request"; + @SerializedName(SERIALIZED_NAME_REQUEST) + private V1AuditResponseEventRequest request; + + public static final String SERIALIZED_NAME_RESPONSE = "response"; + @SerializedName(SERIALIZED_NAME_RESPONSE) + private V1AuditEventResponse response; + + public static final String SERIALIZED_NAME_PARENT_ACCOUNT_I_D = "parentAccountID"; + @SerializedName(SERIALIZED_NAME_PARENT_ACCOUNT_I_D) + private String parentAccountID; + + public static final String SERIALIZED_NAME_ACCOUNT_I_D = "accountID"; + @SerializedName(SERIALIZED_NAME_ACCOUNT_I_D) + private String accountID; + + public static final String SERIALIZED_NAME_RESOURCE_I_DS = "resourceIDs"; + @SerializedName(SERIALIZED_NAME_RESOURCE_I_DS) + private List resourceIDs = new ArrayList<>(); + + public V1AuditResponseEvent() { + } + + public V1AuditResponseEvent context(AuditEventContext context) { + this.context = context; + return this; + } + + /** + * Get context + * @return context + */ + @javax.annotation.Nullable + public AuditEventContext getContext() { + return context; + } + + public void setContext(AuditEventContext context) { + this.context = context; + } + + + public V1AuditResponseEvent request(V1AuditResponseEventRequest request) { + this.request = request; + return this; + } + + /** + * Get request + * @return request + */ + @javax.annotation.Nullable + public V1AuditResponseEventRequest getRequest() { + return request; + } + + public void setRequest(V1AuditResponseEventRequest request) { + this.request = request; + } + + + public V1AuditResponseEvent response(V1AuditEventResponse response) { + this.response = response; + return this; + } + + /** + * Get response + * @return response + */ + @javax.annotation.Nullable + public V1AuditEventResponse getResponse() { + return response; + } + + public void setResponse(V1AuditEventResponse response) { + this.response = response; + } + + + public V1AuditResponseEvent parentAccountID(String parentAccountID) { + this.parentAccountID = parentAccountID; + return this; + } + + /** + * Parent account ID of the account that made the request, if any. + * @return parentAccountID + */ + @javax.annotation.Nullable + public String getParentAccountID() { + return parentAccountID; + } + + public void setParentAccountID(String parentAccountID) { + this.parentAccountID = parentAccountID; + } + + + public V1AuditResponseEvent accountID(String accountID) { + this.accountID = accountID; + return this; + } + + /** + * ID of the account that made the request. + * @return accountID + */ + @javax.annotation.Nullable + public String getAccountID() { + return accountID; + } + + public void setAccountID(String accountID) { + this.accountID = accountID; + } + + + public V1AuditResponseEvent resourceIDs(List resourceIDs) { + this.resourceIDs = resourceIDs; + return this; + } + + public V1AuditResponseEvent addResourceIDsItem(String resourceIDsItem) { + if (this.resourceIDs == null) { + this.resourceIDs = new ArrayList<>(); + } + this.resourceIDs.add(resourceIDsItem); + return this; + } + + /** + * IDs for resources involved in the event. Presented in `{resourceType}/{resourceID}` format. For example, `VAULT/cd1d815aa09b4cbfbb803bd20349f202`. + * @return resourceIDs + */ + @javax.annotation.Nullable + public List getResourceIDs() { + return resourceIDs; + } + + public void setResourceIDs(List resourceIDs) { + this.resourceIDs = resourceIDs; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1AuditResponseEvent v1AuditResponseEvent = (V1AuditResponseEvent) o; + return Objects.equals(this.context, v1AuditResponseEvent.context) && + Objects.equals(this.request, v1AuditResponseEvent.request) && + Objects.equals(this.response, v1AuditResponseEvent.response) && + Objects.equals(this.parentAccountID, v1AuditResponseEvent.parentAccountID) && + Objects.equals(this.accountID, v1AuditResponseEvent.accountID) && + Objects.equals(this.resourceIDs, v1AuditResponseEvent.resourceIDs); + } + + @Override + public int hashCode() { + return Objects.hash(context, request, response, parentAccountID, accountID, resourceIDs); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1AuditResponseEvent {\n"); + sb.append(" context: ").append(toIndentedString(context)).append("\n"); + sb.append(" request: ").append(toIndentedString(request)).append("\n"); + sb.append(" response: ").append(toIndentedString(response)).append("\n"); + sb.append(" parentAccountID: ").append(toIndentedString(parentAccountID)).append("\n"); + sb.append(" accountID: ").append(toIndentedString(accountID)).append("\n"); + sb.append(" resourceIDs: ").append(toIndentedString(resourceIDs)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("context"); + openapiFields.add("request"); + openapiFields.add("response"); + openapiFields.add("parentAccountID"); + openapiFields.add("accountID"); + openapiFields.add("resourceIDs"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1AuditResponseEvent + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1AuditResponseEvent.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1AuditResponseEvent is not found in the empty JSON string", V1AuditResponseEvent.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1AuditResponseEvent.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1AuditResponseEvent` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `context` + if (jsonObj.get("context") != null && !jsonObj.get("context").isJsonNull()) { + AuditEventContext.validateJsonElement(jsonObj.get("context")); + } + // validate the optional field `request` + if (jsonObj.get("request") != null && !jsonObj.get("request").isJsonNull()) { + V1AuditResponseEventRequest.validateJsonElement(jsonObj.get("request")); + } + // validate the optional field `response` + if (jsonObj.get("response") != null && !jsonObj.get("response").isJsonNull()) { + V1AuditEventResponse.validateJsonElement(jsonObj.get("response")); + } + if ((jsonObj.get("parentAccountID") != null && !jsonObj.get("parentAccountID").isJsonNull()) && !jsonObj.get("parentAccountID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `parentAccountID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("parentAccountID").toString())); + } + if ((jsonObj.get("accountID") != null && !jsonObj.get("accountID").isJsonNull()) && !jsonObj.get("accountID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `accountID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("accountID").toString())); + } + // ensure the optional json data is an array if present + if (jsonObj.get("resourceIDs") != null && !jsonObj.get("resourceIDs").isJsonNull() && !jsonObj.get("resourceIDs").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `resourceIDs` to be an array in the JSON string but got `%s`", jsonObj.get("resourceIDs").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1AuditResponseEvent.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1AuditResponseEvent' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1AuditResponseEvent.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1AuditResponseEvent value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1AuditResponseEvent read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1AuditResponseEvent given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1AuditResponseEvent + * @throws IOException if the JSON string is invalid with respect to V1AuditResponseEvent + */ + public static V1AuditResponseEvent fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1AuditResponseEvent.class); + } + + /** + * Convert an instance of V1AuditResponseEvent to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java new file mode 100644 index 00000000..d4b69f55 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java @@ -0,0 +1,456 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.AuditEventAuditResourceType; +import com.skyflow.generated.rest.models.AuditEventData; +import com.skyflow.generated.rest.models.AuditEventHTTPInfo; +import com.skyflow.generated.rest.models.RequestActionType; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * Contains fields for defining Request Properties. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1AuditResponseEventRequest { + public static final String SERIALIZED_NAME_DATA = "data"; + @SerializedName(SERIALIZED_NAME_DATA) + private AuditEventData data; + + public static final String SERIALIZED_NAME_API_NAME = "apiName"; + @SerializedName(SERIALIZED_NAME_API_NAME) + private String apiName; + + public static final String SERIALIZED_NAME_WORKSPACE_I_D = "workspaceID"; + @SerializedName(SERIALIZED_NAME_WORKSPACE_I_D) + private String workspaceID; + + public static final String SERIALIZED_NAME_VAULT_I_D = "vaultID"; + @SerializedName(SERIALIZED_NAME_VAULT_I_D) + private String vaultID; + + public static final String SERIALIZED_NAME_TAGS = "tags"; + @SerializedName(SERIALIZED_NAME_TAGS) + private List tags = new ArrayList<>(); + + public static final String SERIALIZED_NAME_TIMESTAMP = "timestamp"; + @SerializedName(SERIALIZED_NAME_TIMESTAMP) + private String timestamp; + + public static final String SERIALIZED_NAME_ACTION_TYPE = "actionType"; + @SerializedName(SERIALIZED_NAME_ACTION_TYPE) + private RequestActionType actionType = RequestActionType.NONE; + + public static final String SERIALIZED_NAME_RESOURCE_TYPE = "resourceType"; + @SerializedName(SERIALIZED_NAME_RESOURCE_TYPE) + private AuditEventAuditResourceType resourceType = AuditEventAuditResourceType.NONE_API; + + public static final String SERIALIZED_NAME_HTTP_INFO = "httpInfo"; + @SerializedName(SERIALIZED_NAME_HTTP_INFO) + private AuditEventHTTPInfo httpInfo; + + public V1AuditResponseEventRequest() { + } + + public V1AuditResponseEventRequest data(AuditEventData data) { + this.data = data; + return this; + } + + /** + * Get data + * @return data + */ + @javax.annotation.Nullable + public AuditEventData getData() { + return data; + } + + public void setData(AuditEventData data) { + this.data = data; + } + + + public V1AuditResponseEventRequest apiName(String apiName) { + this.apiName = apiName; + return this; + } + + /** + * API name. + * @return apiName + */ + @javax.annotation.Nullable + public String getApiName() { + return apiName; + } + + public void setApiName(String apiName) { + this.apiName = apiName; + } + + + public V1AuditResponseEventRequest workspaceID(String workspaceID) { + this.workspaceID = workspaceID; + return this; + } + + /** + * The workspaceID (if any) of the request. + * @return workspaceID + */ + @javax.annotation.Nullable + public String getWorkspaceID() { + return workspaceID; + } + + public void setWorkspaceID(String workspaceID) { + this.workspaceID = workspaceID; + } + + + public V1AuditResponseEventRequest vaultID(String vaultID) { + this.vaultID = vaultID; + return this; + } + + /** + * The vaultID (if any) of the request. + * @return vaultID + */ + @javax.annotation.Nullable + public String getVaultID() { + return vaultID; + } + + public void setVaultID(String vaultID) { + this.vaultID = vaultID; + } + + + public V1AuditResponseEventRequest tags(List tags) { + this.tags = tags; + return this; + } + + public V1AuditResponseEventRequest addTagsItem(String tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Tags associated with the event. To provide better search capabilities. Like login. + * @return tags + */ + @javax.annotation.Nullable + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + + public V1AuditResponseEventRequest timestamp(String timestamp) { + this.timestamp = timestamp; + return this; + } + + /** + * time when this request is generated, use extention method to set it. + * @return timestamp + */ + @javax.annotation.Nullable + public String getTimestamp() { + return timestamp; + } + + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + + public V1AuditResponseEventRequest actionType(RequestActionType actionType) { + this.actionType = actionType; + return this; + } + + /** + * Get actionType + * @return actionType + */ + @javax.annotation.Nullable + public RequestActionType getActionType() { + return actionType; + } + + public void setActionType(RequestActionType actionType) { + this.actionType = actionType; + } + + + public V1AuditResponseEventRequest resourceType(AuditEventAuditResourceType resourceType) { + this.resourceType = resourceType; + return this; + } + + /** + * Get resourceType + * @return resourceType + */ + @javax.annotation.Nullable + public AuditEventAuditResourceType getResourceType() { + return resourceType; + } + + public void setResourceType(AuditEventAuditResourceType resourceType) { + this.resourceType = resourceType; + } + + + public V1AuditResponseEventRequest httpInfo(AuditEventHTTPInfo httpInfo) { + this.httpInfo = httpInfo; + return this; + } + + /** + * Get httpInfo + * @return httpInfo + */ + @javax.annotation.Nullable + public AuditEventHTTPInfo getHttpInfo() { + return httpInfo; + } + + public void setHttpInfo(AuditEventHTTPInfo httpInfo) { + this.httpInfo = httpInfo; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1AuditResponseEventRequest v1AuditResponseEventRequest = (V1AuditResponseEventRequest) o; + return Objects.equals(this.data, v1AuditResponseEventRequest.data) && + Objects.equals(this.apiName, v1AuditResponseEventRequest.apiName) && + Objects.equals(this.workspaceID, v1AuditResponseEventRequest.workspaceID) && + Objects.equals(this.vaultID, v1AuditResponseEventRequest.vaultID) && + Objects.equals(this.tags, v1AuditResponseEventRequest.tags) && + Objects.equals(this.timestamp, v1AuditResponseEventRequest.timestamp) && + Objects.equals(this.actionType, v1AuditResponseEventRequest.actionType) && + Objects.equals(this.resourceType, v1AuditResponseEventRequest.resourceType) && + Objects.equals(this.httpInfo, v1AuditResponseEventRequest.httpInfo); + } + + @Override + public int hashCode() { + return Objects.hash(data, apiName, workspaceID, vaultID, tags, timestamp, actionType, resourceType, httpInfo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1AuditResponseEventRequest {\n"); + sb.append(" data: ").append(toIndentedString(data)).append("\n"); + sb.append(" apiName: ").append(toIndentedString(apiName)).append("\n"); + sb.append(" workspaceID: ").append(toIndentedString(workspaceID)).append("\n"); + sb.append(" vaultID: ").append(toIndentedString(vaultID)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); + sb.append(" actionType: ").append(toIndentedString(actionType)).append("\n"); + sb.append(" resourceType: ").append(toIndentedString(resourceType)).append("\n"); + sb.append(" httpInfo: ").append(toIndentedString(httpInfo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("data"); + openapiFields.add("apiName"); + openapiFields.add("workspaceID"); + openapiFields.add("vaultID"); + openapiFields.add("tags"); + openapiFields.add("timestamp"); + openapiFields.add("actionType"); + openapiFields.add("resourceType"); + openapiFields.add("httpInfo"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1AuditResponseEventRequest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1AuditResponseEventRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1AuditResponseEventRequest is not found in the empty JSON string", V1AuditResponseEventRequest.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1AuditResponseEventRequest.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1AuditResponseEventRequest` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `data` + if (jsonObj.get("data") != null && !jsonObj.get("data").isJsonNull()) { + AuditEventData.validateJsonElement(jsonObj.get("data")); + } + if ((jsonObj.get("apiName") != null && !jsonObj.get("apiName").isJsonNull()) && !jsonObj.get("apiName").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `apiName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("apiName").toString())); + } + if ((jsonObj.get("workspaceID") != null && !jsonObj.get("workspaceID").isJsonNull()) && !jsonObj.get("workspaceID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `workspaceID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("workspaceID").toString())); + } + if ((jsonObj.get("vaultID") != null && !jsonObj.get("vaultID").isJsonNull()) && !jsonObj.get("vaultID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `vaultID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("vaultID").toString())); + } + // ensure the optional json data is an array if present + if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull() && !jsonObj.get("tags").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); + } + if ((jsonObj.get("timestamp") != null && !jsonObj.get("timestamp").isJsonNull()) && !jsonObj.get("timestamp").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `timestamp` to be a primitive type in the JSON string but got `%s`", jsonObj.get("timestamp").toString())); + } + // validate the optional field `actionType` + if (jsonObj.get("actionType") != null && !jsonObj.get("actionType").isJsonNull()) { + RequestActionType.validateJsonElement(jsonObj.get("actionType")); + } + // validate the optional field `resourceType` + if (jsonObj.get("resourceType") != null && !jsonObj.get("resourceType").isJsonNull()) { + AuditEventAuditResourceType.validateJsonElement(jsonObj.get("resourceType")); + } + // validate the optional field `httpInfo` + if (jsonObj.get("httpInfo") != null && !jsonObj.get("httpInfo").isJsonNull()) { + AuditEventHTTPInfo.validateJsonElement(jsonObj.get("httpInfo")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1AuditResponseEventRequest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1AuditResponseEventRequest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1AuditResponseEventRequest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1AuditResponseEventRequest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1AuditResponseEventRequest read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1AuditResponseEventRequest given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1AuditResponseEventRequest + * @throws IOException if the JSON string is invalid with respect to V1AuditResponseEventRequest + */ + public static V1AuditResponseEventRequest fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1AuditResponseEventRequest.class); + } + + /** + * Convert an instance of V1AuditResponseEventRequest to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java new file mode 100644 index 00000000..292bd674 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java @@ -0,0 +1,305 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1VaultSchemaConfig; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * Request to return specific card metadata. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1BINListRequest { + public static final String SERIALIZED_NAME_FIELDS = "fields"; + @SerializedName(SERIALIZED_NAME_FIELDS) + private List fields = new ArrayList<>(); + + public static final String SERIALIZED_NAME_B_I_N = "BIN"; + @SerializedName(SERIALIZED_NAME_B_I_N) + private String BIN; + + public static final String SERIALIZED_NAME_VAULT_SCHEMA_CONFIG = "vault_schema_config"; + @SerializedName(SERIALIZED_NAME_VAULT_SCHEMA_CONFIG) + private V1VaultSchemaConfig vaultSchemaConfig; + + public static final String SERIALIZED_NAME_SKYFLOW_ID = "skyflow_id"; + @SerializedName(SERIALIZED_NAME_SKYFLOW_ID) + private String skyflowId; + + public V1BINListRequest() { + } + + public V1BINListRequest fields(List fields) { + this.fields = fields; + return this; + } + + public V1BINListRequest addFieldsItem(String fieldsItem) { + if (this.fields == null) { + this.fields = new ArrayList<>(); + } + this.fields.add(fieldsItem); + return this; + } + + /** + * Fields to return. If not specified, all fields are returned. + * @return fields + */ + @javax.annotation.Nullable + public List getFields() { + return fields; + } + + public void setFields(List fields) { + this.fields = fields; + } + + + public V1BINListRequest BIN(String BIN) { + this.BIN = BIN; + return this; + } + + /** + * BIN of the card. + * @return BIN + */ + @javax.annotation.Nullable + public String getBIN() { + return BIN; + } + + public void setBIN(String BIN) { + this.BIN = BIN; + } + + + public V1BINListRequest vaultSchemaConfig(V1VaultSchemaConfig vaultSchemaConfig) { + this.vaultSchemaConfig = vaultSchemaConfig; + return this; + } + + /** + * Get vaultSchemaConfig + * @return vaultSchemaConfig + */ + @javax.annotation.Nullable + public V1VaultSchemaConfig getVaultSchemaConfig() { + return vaultSchemaConfig; + } + + public void setVaultSchemaConfig(V1VaultSchemaConfig vaultSchemaConfig) { + this.vaultSchemaConfig = vaultSchemaConfig; + } + + + public V1BINListRequest skyflowId(String skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + /** + * <code>skyflow_id</code> of the record. + * @return skyflowId + */ + @javax.annotation.Nullable + public String getSkyflowId() { + return skyflowId; + } + + public void setSkyflowId(String skyflowId) { + this.skyflowId = skyflowId; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1BINListRequest v1BINListRequest = (V1BINListRequest) o; + return Objects.equals(this.fields, v1BINListRequest.fields) && + Objects.equals(this.BIN, v1BINListRequest.BIN) && + Objects.equals(this.vaultSchemaConfig, v1BINListRequest.vaultSchemaConfig) && + Objects.equals(this.skyflowId, v1BINListRequest.skyflowId); + } + + @Override + public int hashCode() { + return Objects.hash(fields, BIN, vaultSchemaConfig, skyflowId); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1BINListRequest {\n"); + sb.append(" fields: ").append(toIndentedString(fields)).append("\n"); + sb.append(" BIN: ").append(toIndentedString(BIN)).append("\n"); + sb.append(" vaultSchemaConfig: ").append(toIndentedString(vaultSchemaConfig)).append("\n"); + sb.append(" skyflowId: ").append(toIndentedString(skyflowId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("fields"); + openapiFields.add("BIN"); + openapiFields.add("vault_schema_config"); + openapiFields.add("skyflow_id"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1BINListRequest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1BINListRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1BINListRequest is not found in the empty JSON string", V1BINListRequest.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1BINListRequest.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1BINListRequest` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // ensure the optional json data is an array if present + if (jsonObj.get("fields") != null && !jsonObj.get("fields").isJsonNull() && !jsonObj.get("fields").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `fields` to be an array in the JSON string but got `%s`", jsonObj.get("fields").toString())); + } + if ((jsonObj.get("BIN") != null && !jsonObj.get("BIN").isJsonNull()) && !jsonObj.get("BIN").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `BIN` to be a primitive type in the JSON string but got `%s`", jsonObj.get("BIN").toString())); + } + // validate the optional field `vault_schema_config` + if (jsonObj.get("vault_schema_config") != null && !jsonObj.get("vault_schema_config").isJsonNull()) { + V1VaultSchemaConfig.validateJsonElement(jsonObj.get("vault_schema_config")); + } + if ((jsonObj.get("skyflow_id") != null && !jsonObj.get("skyflow_id").isJsonNull()) && !jsonObj.get("skyflow_id").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `skyflow_id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("skyflow_id").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1BINListRequest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1BINListRequest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1BINListRequest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1BINListRequest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1BINListRequest read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1BINListRequest given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1BINListRequest + * @throws IOException if the JSON string is invalid with respect to V1BINListRequest + */ + public static V1BINListRequest fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1BINListRequest.class); + } + + /** + * Convert an instance of V1BINListRequest to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java new file mode 100644 index 00000000..47f30610 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java @@ -0,0 +1,227 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1Card; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * Response to the Get BIN request. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1BINListResponse { + public static final String SERIALIZED_NAME_CARDS_DATA = "cards_data"; + @SerializedName(SERIALIZED_NAME_CARDS_DATA) + private List cardsData = new ArrayList<>(); + + public V1BINListResponse() { + } + + public V1BINListResponse cardsData(List cardsData) { + this.cardsData = cardsData; + return this; + } + + public V1BINListResponse addCardsDataItem(V1Card cardsDataItem) { + if (this.cardsData == null) { + this.cardsData = new ArrayList<>(); + } + this.cardsData.add(cardsDataItem); + return this; + } + + /** + * Card metadata associated with the specified BIN. + * @return cardsData + */ + @javax.annotation.Nullable + public List getCardsData() { + return cardsData; + } + + public void setCardsData(List cardsData) { + this.cardsData = cardsData; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1BINListResponse v1BINListResponse = (V1BINListResponse) o; + return Objects.equals(this.cardsData, v1BINListResponse.cardsData); + } + + @Override + public int hashCode() { + return Objects.hash(cardsData); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1BINListResponse {\n"); + sb.append(" cardsData: ").append(toIndentedString(cardsData)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("cards_data"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1BINListResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1BINListResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1BINListResponse is not found in the empty JSON string", V1BINListResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1BINListResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1BINListResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (jsonObj.get("cards_data") != null && !jsonObj.get("cards_data").isJsonNull()) { + JsonArray jsonArraycardsData = jsonObj.getAsJsonArray("cards_data"); + if (jsonArraycardsData != null) { + // ensure the json data is an array + if (!jsonObj.get("cards_data").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `cards_data` to be an array in the JSON string but got `%s`", jsonObj.get("cards_data").toString())); + } + + // validate the optional field `cards_data` (array) + for (int i = 0; i < jsonArraycardsData.size(); i++) { + V1Card.validateJsonElement(jsonArraycardsData.get(i)); + }; + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1BINListResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1BINListResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1BINListResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1BINListResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1BINListResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1BINListResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1BINListResponse + * @throws IOException if the JSON string is invalid with respect to V1BINListResponse + */ + public static V1BINListResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1BINListResponse.class); + } + + /** + * Convert an instance of V1BINListResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BYOT.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1BYOT.java new file mode 100644 index 00000000..28bd87e9 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1BYOT.java @@ -0,0 +1,80 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Token insertion behavior. - DISABLE: Tokens aren't allowed for any fields. If tokens are specified, the request fails. - ENABLE: Tokens are allowed—but not required—for all fields. If tokens are specified, they're inserted. - ENABLE_STRICT: Tokens are required for all fields. If tokens are specified, they're inserted. If not, the request fails. + */ +@JsonAdapter(V1BYOT.Adapter.class) +public enum V1BYOT { + + DISABLE("DISABLE"), + + ENABLE("ENABLE"), + + ENABLE_STRICT("ENABLE_STRICT"); + + private String value; + + V1BYOT(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static V1BYOT fromValue(String value) { + for (V1BYOT b : V1BYOT.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final V1BYOT enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public V1BYOT read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return V1BYOT.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + V1BYOT.fromValue(value); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java new file mode 100644 index 00000000..2d98e66e --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java @@ -0,0 +1,245 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1BatchOperationResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1BatchOperationResponse { + public static final String SERIALIZED_NAME_VAULT_I_D = "vaultID"; + @SerializedName(SERIALIZED_NAME_VAULT_I_D) + private String vaultID; + + public static final String SERIALIZED_NAME_RESPONSES = "responses"; + @SerializedName(SERIALIZED_NAME_RESPONSES) + private List responses = new ArrayList<>(); + + public V1BatchOperationResponse() { + } + + public V1BatchOperationResponse vaultID(String vaultID) { + this.vaultID = vaultID; + return this; + } + + /** + * ID of the vault. + * @return vaultID + */ + @javax.annotation.Nullable + public String getVaultID() { + return vaultID; + } + + public void setVaultID(String vaultID) { + this.vaultID = vaultID; + } + + + public V1BatchOperationResponse responses(List responses) { + this.responses = responses; + return this; + } + + public V1BatchOperationResponse addResponsesItem(Object responsesItem) { + if (this.responses == null) { + this.responses = new ArrayList<>(); + } + this.responses.add(responsesItem); + return this; + } + + /** + * Responses in the same order as in the request. Responses have the same payload structure as their corresponding APIs: <br/><ul><li>`POST` returns an Insert Records response.</li><li>`PUT` returns an Update Record response.</li><li>`GET` returns a Get Record response.</li><li>`DELETE` returns a Delete Record response.</li></ul> + * @return responses + */ + @javax.annotation.Nullable + public List getResponses() { + return responses; + } + + public void setResponses(List responses) { + this.responses = responses; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1BatchOperationResponse v1BatchOperationResponse = (V1BatchOperationResponse) o; + return Objects.equals(this.vaultID, v1BatchOperationResponse.vaultID) && + Objects.equals(this.responses, v1BatchOperationResponse.responses); + } + + @Override + public int hashCode() { + return Objects.hash(vaultID, responses); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1BatchOperationResponse {\n"); + sb.append(" vaultID: ").append(toIndentedString(vaultID)).append("\n"); + sb.append(" responses: ").append(toIndentedString(responses)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("vaultID"); + openapiFields.add("responses"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1BatchOperationResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1BatchOperationResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1BatchOperationResponse is not found in the empty JSON string", V1BatchOperationResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1BatchOperationResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1BatchOperationResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("vaultID") != null && !jsonObj.get("vaultID").isJsonNull()) && !jsonObj.get("vaultID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `vaultID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("vaultID").toString())); + } + // ensure the optional json data is an array if present + if (jsonObj.get("responses") != null && !jsonObj.get("responses").isJsonNull() && !jsonObj.get("responses").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `responses` to be an array in the JSON string but got `%s`", jsonObj.get("responses").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1BatchOperationResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1BatchOperationResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1BatchOperationResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1BatchOperationResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1BatchOperationResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1BatchOperationResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1BatchOperationResponse + * @throws IOException if the JSON string is invalid with respect to V1BatchOperationResponse + */ + public static V1BatchOperationResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1BatchOperationResponse.class); + } + + /** + * Convert an instance of V1BatchOperationResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java new file mode 100644 index 00000000..21ab2cf9 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java @@ -0,0 +1,458 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.BatchRecordMethod; +import com.skyflow.generated.rest.models.RedactionEnumREDACTION; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1BatchRecord + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1BatchRecord { + public static final String SERIALIZED_NAME_FIELDS = "fields"; + @SerializedName(SERIALIZED_NAME_FIELDS) + private Object fields; + + public static final String SERIALIZED_NAME_TABLE_NAME = "tableName"; + @SerializedName(SERIALIZED_NAME_TABLE_NAME) + private String tableName; + + public static final String SERIALIZED_NAME_METHOD = "method"; + @SerializedName(SERIALIZED_NAME_METHOD) + private BatchRecordMethod method = BatchRecordMethod.NONE; + + public static final String SERIALIZED_NAME_BATCH_I_D = "batchID"; + @SerializedName(SERIALIZED_NAME_BATCH_I_D) + private String batchID; + + public static final String SERIALIZED_NAME_REDACTION = "redaction"; + @SerializedName(SERIALIZED_NAME_REDACTION) + private RedactionEnumREDACTION redaction = RedactionEnumREDACTION.DEFAULT; + + public static final String SERIALIZED_NAME_TOKENIZATION = "tokenization"; + @SerializedName(SERIALIZED_NAME_TOKENIZATION) + private Boolean tokenization; + + public static final String SERIALIZED_NAME_I_D = "ID"; + @SerializedName(SERIALIZED_NAME_I_D) + private String ID; + + public static final String SERIALIZED_NAME_DOWNLOAD_U_R_L = "downloadURL"; + @SerializedName(SERIALIZED_NAME_DOWNLOAD_U_R_L) + private Boolean downloadURL; + + public static final String SERIALIZED_NAME_UPSERT = "upsert"; + @SerializedName(SERIALIZED_NAME_UPSERT) + private String upsert; + + public static final String SERIALIZED_NAME_TOKENS = "tokens"; + @SerializedName(SERIALIZED_NAME_TOKENS) + private Object tokens; + + public V1BatchRecord() { + } + + public V1BatchRecord fields(Object fields) { + this.fields = fields; + return this; + } + + /** + * Field and value key pairs. For example, `{'field_1':'value_1', 'field_2':'value_2'}`. Only valid when `method` is `POST` or `PUT`. + * @return fields + */ + @javax.annotation.Nullable + public Object getFields() { + return fields; + } + + public void setFields(Object fields) { + this.fields = fields; + } + + + public V1BatchRecord tableName(String tableName) { + this.tableName = tableName; + return this; + } + + /** + * Name of the table to perform the operation on. + * @return tableName + */ + @javax.annotation.Nullable + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + + public V1BatchRecord method(BatchRecordMethod method) { + this.method = method; + return this; + } + + /** + * Get method + * @return method + */ + @javax.annotation.Nullable + public BatchRecordMethod getMethod() { + return method; + } + + public void setMethod(BatchRecordMethod method) { + this.method = method; + } + + + public V1BatchRecord batchID(String batchID) { + this.batchID = batchID; + return this; + } + + /** + * ID to group operations by. Operations in the same group are executed sequentially. + * @return batchID + */ + @javax.annotation.Nullable + public String getBatchID() { + return batchID; + } + + public void setBatchID(String batchID) { + this.batchID = batchID; + } + + + public V1BatchRecord redaction(RedactionEnumREDACTION redaction) { + this.redaction = redaction; + return this; + } + + /** + * Get redaction + * @return redaction + */ + @javax.annotation.Nullable + public RedactionEnumREDACTION getRedaction() { + return redaction; + } + + public void setRedaction(RedactionEnumREDACTION redaction) { + this.redaction = redaction; + } + + + public V1BatchRecord tokenization(Boolean tokenization) { + this.tokenization = tokenization; + return this; + } + + /** + * If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. + * @return tokenization + */ + @javax.annotation.Nullable + public Boolean getTokenization() { + return tokenization; + } + + public void setTokenization(Boolean tokenization) { + this.tokenization = tokenization; + } + + + public V1BatchRecord ID(String ID) { + this.ID = ID; + return this; + } + + /** + * `skyflow_id` for the record. Only valid when `method` is `GET`, `DELETE`, or `PUT`. + * @return ID + */ + @javax.annotation.Nullable + public String getID() { + return ID; + } + + public void setID(String ID) { + this.ID = ID; + } + + + public V1BatchRecord downloadURL(Boolean downloadURL) { + this.downloadURL = downloadURL; + return this; + } + + /** + * If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + * @return downloadURL + */ + @javax.annotation.Nullable + public Boolean getDownloadURL() { + return downloadURL; + } + + public void setDownloadURL(Boolean downloadURL) { + this.downloadURL = downloadURL; + } + + + public V1BatchRecord upsert(String upsert) { + this.upsert = upsert; + return this; + } + + /** + * Column that stores primary keys for upsert operations. The column must be marked as unique in the vault schema. Only valid when `method` is `POST`. + * @return upsert + */ + @javax.annotation.Nullable + public String getUpsert() { + return upsert; + } + + public void setUpsert(String upsert) { + this.upsert = upsert; + } + + + public V1BatchRecord tokens(Object tokens) { + this.tokens = tokens; + return this; + } + + /** + * Fields and tokens for the record. For example, `{'field_1':'token_1', 'field_2':'token_2'}`. + * @return tokens + */ + @javax.annotation.Nullable + public Object getTokens() { + return tokens; + } + + public void setTokens(Object tokens) { + this.tokens = tokens; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1BatchRecord v1BatchRecord = (V1BatchRecord) o; + return Objects.equals(this.fields, v1BatchRecord.fields) && + Objects.equals(this.tableName, v1BatchRecord.tableName) && + Objects.equals(this.method, v1BatchRecord.method) && + Objects.equals(this.batchID, v1BatchRecord.batchID) && + Objects.equals(this.redaction, v1BatchRecord.redaction) && + Objects.equals(this.tokenization, v1BatchRecord.tokenization) && + Objects.equals(this.ID, v1BatchRecord.ID) && + Objects.equals(this.downloadURL, v1BatchRecord.downloadURL) && + Objects.equals(this.upsert, v1BatchRecord.upsert) && + Objects.equals(this.tokens, v1BatchRecord.tokens); + } + + @Override + public int hashCode() { + return Objects.hash(fields, tableName, method, batchID, redaction, tokenization, ID, downloadURL, upsert, tokens); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1BatchRecord {\n"); + sb.append(" fields: ").append(toIndentedString(fields)).append("\n"); + sb.append(" tableName: ").append(toIndentedString(tableName)).append("\n"); + sb.append(" method: ").append(toIndentedString(method)).append("\n"); + sb.append(" batchID: ").append(toIndentedString(batchID)).append("\n"); + sb.append(" redaction: ").append(toIndentedString(redaction)).append("\n"); + sb.append(" tokenization: ").append(toIndentedString(tokenization)).append("\n"); + sb.append(" ID: ").append(toIndentedString(ID)).append("\n"); + sb.append(" downloadURL: ").append(toIndentedString(downloadURL)).append("\n"); + sb.append(" upsert: ").append(toIndentedString(upsert)).append("\n"); + sb.append(" tokens: ").append(toIndentedString(tokens)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("fields"); + openapiFields.add("tableName"); + openapiFields.add("method"); + openapiFields.add("batchID"); + openapiFields.add("redaction"); + openapiFields.add("tokenization"); + openapiFields.add("ID"); + openapiFields.add("downloadURL"); + openapiFields.add("upsert"); + openapiFields.add("tokens"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1BatchRecord + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1BatchRecord.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1BatchRecord is not found in the empty JSON string", V1BatchRecord.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1BatchRecord.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1BatchRecord` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("tableName") != null && !jsonObj.get("tableName").isJsonNull()) && !jsonObj.get("tableName").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `tableName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("tableName").toString())); + } + // validate the optional field `method` + if (jsonObj.get("method") != null && !jsonObj.get("method").isJsonNull()) { + BatchRecordMethod.validateJsonElement(jsonObj.get("method")); + } + if ((jsonObj.get("batchID") != null && !jsonObj.get("batchID").isJsonNull()) && !jsonObj.get("batchID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `batchID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("batchID").toString())); + } + // validate the optional field `redaction` + if (jsonObj.get("redaction") != null && !jsonObj.get("redaction").isJsonNull()) { + RedactionEnumREDACTION.validateJsonElement(jsonObj.get("redaction")); + } + if ((jsonObj.get("ID") != null && !jsonObj.get("ID").isJsonNull()) && !jsonObj.get("ID").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `ID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("ID").toString())); + } + if ((jsonObj.get("upsert") != null && !jsonObj.get("upsert").isJsonNull()) && !jsonObj.get("upsert").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `upsert` to be a primitive type in the JSON string but got `%s`", jsonObj.get("upsert").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1BatchRecord.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1BatchRecord' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1BatchRecord.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1BatchRecord value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1BatchRecord read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1BatchRecord given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1BatchRecord + * @throws IOException if the JSON string is invalid with respect to V1BatchRecord + */ + public static V1BatchRecord fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1BatchRecord.class); + } + + /** + * Convert an instance of V1BatchRecord to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java new file mode 100644 index 00000000..6a89ed40 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java @@ -0,0 +1,216 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1BulkDeleteRecordResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1BulkDeleteRecordResponse { + public static final String SERIALIZED_NAME_RECORD_I_D_RESPONSE = "RecordIDResponse"; + @SerializedName(SERIALIZED_NAME_RECORD_I_D_RESPONSE) + private List recordIDResponse = new ArrayList<>(); + + public V1BulkDeleteRecordResponse() { + } + + public V1BulkDeleteRecordResponse recordIDResponse(List recordIDResponse) { + this.recordIDResponse = recordIDResponse; + return this; + } + + public V1BulkDeleteRecordResponse addRecordIDResponseItem(String recordIDResponseItem) { + if (this.recordIDResponse == null) { + this.recordIDResponse = new ArrayList<>(); + } + this.recordIDResponse.add(recordIDResponseItem); + return this; + } + + /** + * IDs for the deleted records, or `*` if all records were deleted. + * @return recordIDResponse + */ + @javax.annotation.Nullable + public List getRecordIDResponse() { + return recordIDResponse; + } + + public void setRecordIDResponse(List recordIDResponse) { + this.recordIDResponse = recordIDResponse; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1BulkDeleteRecordResponse v1BulkDeleteRecordResponse = (V1BulkDeleteRecordResponse) o; + return Objects.equals(this.recordIDResponse, v1BulkDeleteRecordResponse.recordIDResponse); + } + + @Override + public int hashCode() { + return Objects.hash(recordIDResponse); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1BulkDeleteRecordResponse {\n"); + sb.append(" recordIDResponse: ").append(toIndentedString(recordIDResponse)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("RecordIDResponse"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1BulkDeleteRecordResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1BulkDeleteRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1BulkDeleteRecordResponse is not found in the empty JSON string", V1BulkDeleteRecordResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1BulkDeleteRecordResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1BulkDeleteRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // ensure the optional json data is an array if present + if (jsonObj.get("RecordIDResponse") != null && !jsonObj.get("RecordIDResponse").isJsonNull() && !jsonObj.get("RecordIDResponse").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `RecordIDResponse` to be an array in the JSON string but got `%s`", jsonObj.get("RecordIDResponse").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1BulkDeleteRecordResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1BulkDeleteRecordResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1BulkDeleteRecordResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1BulkDeleteRecordResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1BulkDeleteRecordResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1BulkDeleteRecordResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1BulkDeleteRecordResponse + * @throws IOException if the JSON string is invalid with respect to V1BulkDeleteRecordResponse + */ + public static V1BulkDeleteRecordResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1BulkDeleteRecordResponse.class); + } + + /** + * Convert an instance of V1BulkDeleteRecordResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java new file mode 100644 index 00000000..2a935fe9 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java @@ -0,0 +1,227 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1FieldRecords; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1BulkGetRecordResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1BulkGetRecordResponse { + public static final String SERIALIZED_NAME_RECORDS = "records"; + @SerializedName(SERIALIZED_NAME_RECORDS) + private List records = new ArrayList<>(); + + public V1BulkGetRecordResponse() { + } + + public V1BulkGetRecordResponse records(List records) { + this.records = records; + return this; + } + + public V1BulkGetRecordResponse addRecordsItem(V1FieldRecords recordsItem) { + if (this.records == null) { + this.records = new ArrayList<>(); + } + this.records.add(recordsItem); + return this; + } + + /** + * The specified records. + * @return records + */ + @javax.annotation.Nullable + public List getRecords() { + return records; + } + + public void setRecords(List records) { + this.records = records; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1BulkGetRecordResponse v1BulkGetRecordResponse = (V1BulkGetRecordResponse) o; + return Objects.equals(this.records, v1BulkGetRecordResponse.records); + } + + @Override + public int hashCode() { + return Objects.hash(records); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1BulkGetRecordResponse {\n"); + sb.append(" records: ").append(toIndentedString(records)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("records"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1BulkGetRecordResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1BulkGetRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1BulkGetRecordResponse is not found in the empty JSON string", V1BulkGetRecordResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1BulkGetRecordResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1BulkGetRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { + JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); + if (jsonArrayrecords != null) { + // ensure the json data is an array + if (!jsonObj.get("records").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); + } + + // validate the optional field `records` (array) + for (int i = 0; i < jsonArrayrecords.size(); i++) { + V1FieldRecords.validateJsonElement(jsonArrayrecords.get(i)); + }; + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1BulkGetRecordResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1BulkGetRecordResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1BulkGetRecordResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1BulkGetRecordResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1BulkGetRecordResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1BulkGetRecordResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1BulkGetRecordResponse + * @throws IOException if the JSON string is invalid with respect to V1BulkGetRecordResponse + */ + public static V1BulkGetRecordResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1BulkGetRecordResponse.class); + } + + /** + * Convert an instance of V1BulkGetRecordResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1Card.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1Card.java new file mode 100644 index 00000000..5c8fb3cc --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1Card.java @@ -0,0 +1,437 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * Card metadata of the requested BIN. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1Card { + public static final String SERIALIZED_NAME_B_I_N = "BIN"; + @SerializedName(SERIALIZED_NAME_B_I_N) + private String BIN; + + public static final String SERIALIZED_NAME_ISSUER_NAME = "issuer_name"; + @SerializedName(SERIALIZED_NAME_ISSUER_NAME) + private String issuerName; + + public static final String SERIALIZED_NAME_COUNTRY_CODE = "country_code"; + @SerializedName(SERIALIZED_NAME_COUNTRY_CODE) + private String countryCode; + + public static final String SERIALIZED_NAME_CURRENCY = "currency"; + @SerializedName(SERIALIZED_NAME_CURRENCY) + private String currency; + + public static final String SERIALIZED_NAME_CARD_TYPE = "card_type"; + @SerializedName(SERIALIZED_NAME_CARD_TYPE) + private String cardType; + + public static final String SERIALIZED_NAME_CARD_CATEGORY = "card_category"; + @SerializedName(SERIALIZED_NAME_CARD_CATEGORY) + private String cardCategory; + + public static final String SERIALIZED_NAME_CARD_SCHEME = "card_scheme"; + @SerializedName(SERIALIZED_NAME_CARD_SCHEME) + private String cardScheme; + + public static final String SERIALIZED_NAME_CARD_LAST_FOUR_DIGITS = "card_last_four_digits"; + @SerializedName(SERIALIZED_NAME_CARD_LAST_FOUR_DIGITS) + private String cardLastFourDigits; + + public static final String SERIALIZED_NAME_CARD_EXPIRY = "card_expiry"; + @SerializedName(SERIALIZED_NAME_CARD_EXPIRY) + private String cardExpiry; + + public V1Card() { + } + + public V1Card BIN(String BIN) { + this.BIN = BIN; + return this; + } + + /** + * BIN of the card. + * @return BIN + */ + @javax.annotation.Nullable + public String getBIN() { + return BIN; + } + + public void setBIN(String BIN) { + this.BIN = BIN; + } + + + public V1Card issuerName(String issuerName) { + this.issuerName = issuerName; + return this; + } + + /** + * Name of the card issuer bank. + * @return issuerName + */ + @javax.annotation.Nullable + public String getIssuerName() { + return issuerName; + } + + public void setIssuerName(String issuerName) { + this.issuerName = issuerName; + } + + + public V1Card countryCode(String countryCode) { + this.countryCode = countryCode; + return this; + } + + /** + * Country code of the card. + * @return countryCode + */ + @javax.annotation.Nullable + public String getCountryCode() { + return countryCode; + } + + public void setCountryCode(String countryCode) { + this.countryCode = countryCode; + } + + + public V1Card currency(String currency) { + this.currency = currency; + return this; + } + + /** + * Currency of the card. + * @return currency + */ + @javax.annotation.Nullable + public String getCurrency() { + return currency; + } + + public void setCurrency(String currency) { + this.currency = currency; + } + + + public V1Card cardType(String cardType) { + this.cardType = cardType; + return this; + } + + /** + * Type of the card. + * @return cardType + */ + @javax.annotation.Nullable + public String getCardType() { + return cardType; + } + + public void setCardType(String cardType) { + this.cardType = cardType; + } + + + public V1Card cardCategory(String cardCategory) { + this.cardCategory = cardCategory; + return this; + } + + /** + * Category of the card. + * @return cardCategory + */ + @javax.annotation.Nullable + public String getCardCategory() { + return cardCategory; + } + + public void setCardCategory(String cardCategory) { + this.cardCategory = cardCategory; + } + + + public V1Card cardScheme(String cardScheme) { + this.cardScheme = cardScheme; + return this; + } + + /** + * Scheme of the card. + * @return cardScheme + */ + @javax.annotation.Nullable + public String getCardScheme() { + return cardScheme; + } + + public void setCardScheme(String cardScheme) { + this.cardScheme = cardScheme; + } + + + public V1Card cardLastFourDigits(String cardLastFourDigits) { + this.cardLastFourDigits = cardLastFourDigits; + return this; + } + + /** + * Last four digits of the card number. + * @return cardLastFourDigits + */ + @javax.annotation.Nullable + public String getCardLastFourDigits() { + return cardLastFourDigits; + } + + public void setCardLastFourDigits(String cardLastFourDigits) { + this.cardLastFourDigits = cardLastFourDigits; + } + + + public V1Card cardExpiry(String cardExpiry) { + this.cardExpiry = cardExpiry; + return this; + } + + /** + * Expiry date of the card. + * @return cardExpiry + */ + @javax.annotation.Nullable + public String getCardExpiry() { + return cardExpiry; + } + + public void setCardExpiry(String cardExpiry) { + this.cardExpiry = cardExpiry; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1Card v1Card = (V1Card) o; + return Objects.equals(this.BIN, v1Card.BIN) && + Objects.equals(this.issuerName, v1Card.issuerName) && + Objects.equals(this.countryCode, v1Card.countryCode) && + Objects.equals(this.currency, v1Card.currency) && + Objects.equals(this.cardType, v1Card.cardType) && + Objects.equals(this.cardCategory, v1Card.cardCategory) && + Objects.equals(this.cardScheme, v1Card.cardScheme) && + Objects.equals(this.cardLastFourDigits, v1Card.cardLastFourDigits) && + Objects.equals(this.cardExpiry, v1Card.cardExpiry); + } + + @Override + public int hashCode() { + return Objects.hash(BIN, issuerName, countryCode, currency, cardType, cardCategory, cardScheme, cardLastFourDigits, cardExpiry); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1Card {\n"); + sb.append(" BIN: ").append(toIndentedString(BIN)).append("\n"); + sb.append(" issuerName: ").append(toIndentedString(issuerName)).append("\n"); + sb.append(" countryCode: ").append(toIndentedString(countryCode)).append("\n"); + sb.append(" currency: ").append(toIndentedString(currency)).append("\n"); + sb.append(" cardType: ").append(toIndentedString(cardType)).append("\n"); + sb.append(" cardCategory: ").append(toIndentedString(cardCategory)).append("\n"); + sb.append(" cardScheme: ").append(toIndentedString(cardScheme)).append("\n"); + sb.append(" cardLastFourDigits: ").append(toIndentedString(cardLastFourDigits)).append("\n"); + sb.append(" cardExpiry: ").append(toIndentedString(cardExpiry)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("BIN"); + openapiFields.add("issuer_name"); + openapiFields.add("country_code"); + openapiFields.add("currency"); + openapiFields.add("card_type"); + openapiFields.add("card_category"); + openapiFields.add("card_scheme"); + openapiFields.add("card_last_four_digits"); + openapiFields.add("card_expiry"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1Card + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1Card.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1Card is not found in the empty JSON string", V1Card.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1Card.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1Card` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("BIN") != null && !jsonObj.get("BIN").isJsonNull()) && !jsonObj.get("BIN").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `BIN` to be a primitive type in the JSON string but got `%s`", jsonObj.get("BIN").toString())); + } + if ((jsonObj.get("issuer_name") != null && !jsonObj.get("issuer_name").isJsonNull()) && !jsonObj.get("issuer_name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `issuer_name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("issuer_name").toString())); + } + if ((jsonObj.get("country_code") != null && !jsonObj.get("country_code").isJsonNull()) && !jsonObj.get("country_code").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `country_code` to be a primitive type in the JSON string but got `%s`", jsonObj.get("country_code").toString())); + } + if ((jsonObj.get("currency") != null && !jsonObj.get("currency").isJsonNull()) && !jsonObj.get("currency").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `currency` to be a primitive type in the JSON string but got `%s`", jsonObj.get("currency").toString())); + } + if ((jsonObj.get("card_type") != null && !jsonObj.get("card_type").isJsonNull()) && !jsonObj.get("card_type").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `card_type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_type").toString())); + } + if ((jsonObj.get("card_category") != null && !jsonObj.get("card_category").isJsonNull()) && !jsonObj.get("card_category").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `card_category` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_category").toString())); + } + if ((jsonObj.get("card_scheme") != null && !jsonObj.get("card_scheme").isJsonNull()) && !jsonObj.get("card_scheme").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `card_scheme` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_scheme").toString())); + } + if ((jsonObj.get("card_last_four_digits") != null && !jsonObj.get("card_last_four_digits").isJsonNull()) && !jsonObj.get("card_last_four_digits").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `card_last_four_digits` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_last_four_digits").toString())); + } + if ((jsonObj.get("card_expiry") != null && !jsonObj.get("card_expiry").isJsonNull()) && !jsonObj.get("card_expiry").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `card_expiry` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_expiry").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1Card.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1Card' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1Card.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1Card value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1Card read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1Card given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1Card + * @throws IOException if the JSON string is invalid with respect to V1Card + */ + public static V1Card fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1Card.class); + } + + /** + * Convert an instance of V1Card to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java new file mode 100644 index 00000000..9a3c2cb4 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java @@ -0,0 +1,231 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1DeleteFileResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1DeleteFileResponse { + public static final String SERIALIZED_NAME_SKYFLOW_ID = "skyflow_id"; + @SerializedName(SERIALIZED_NAME_SKYFLOW_ID) + private String skyflowId; + + public static final String SERIALIZED_NAME_DELETED = "deleted"; + @SerializedName(SERIALIZED_NAME_DELETED) + private Boolean deleted; + + public V1DeleteFileResponse() { + } + + public V1DeleteFileResponse skyflowId(String skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + /** + * ID of the record. + * @return skyflowId + */ + @javax.annotation.Nullable + public String getSkyflowId() { + return skyflowId; + } + + public void setSkyflowId(String skyflowId) { + this.skyflowId = skyflowId; + } + + + public V1DeleteFileResponse deleted(Boolean deleted) { + this.deleted = deleted; + return this; + } + + /** + * If `true`, the file was deleted. + * @return deleted + */ + @javax.annotation.Nullable + public Boolean getDeleted() { + return deleted; + } + + public void setDeleted(Boolean deleted) { + this.deleted = deleted; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1DeleteFileResponse v1DeleteFileResponse = (V1DeleteFileResponse) o; + return Objects.equals(this.skyflowId, v1DeleteFileResponse.skyflowId) && + Objects.equals(this.deleted, v1DeleteFileResponse.deleted); + } + + @Override + public int hashCode() { + return Objects.hash(skyflowId, deleted); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1DeleteFileResponse {\n"); + sb.append(" skyflowId: ").append(toIndentedString(skyflowId)).append("\n"); + sb.append(" deleted: ").append(toIndentedString(deleted)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("skyflow_id"); + openapiFields.add("deleted"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1DeleteFileResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1DeleteFileResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1DeleteFileResponse is not found in the empty JSON string", V1DeleteFileResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1DeleteFileResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1DeleteFileResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("skyflow_id") != null && !jsonObj.get("skyflow_id").isJsonNull()) && !jsonObj.get("skyflow_id").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `skyflow_id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("skyflow_id").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1DeleteFileResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1DeleteFileResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1DeleteFileResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1DeleteFileResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1DeleteFileResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1DeleteFileResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1DeleteFileResponse + * @throws IOException if the JSON string is invalid with respect to V1DeleteFileResponse + */ + public static V1DeleteFileResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1DeleteFileResponse.class); + } + + /** + * Convert an instance of V1DeleteFileResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java new file mode 100644 index 00000000..8ebf5c35 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java @@ -0,0 +1,231 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1DeleteRecordResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1DeleteRecordResponse { + public static final String SERIALIZED_NAME_SKYFLOW_ID = "skyflow_id"; + @SerializedName(SERIALIZED_NAME_SKYFLOW_ID) + private String skyflowId; + + public static final String SERIALIZED_NAME_DELETED = "deleted"; + @SerializedName(SERIALIZED_NAME_DELETED) + private Boolean deleted; + + public V1DeleteRecordResponse() { + } + + public V1DeleteRecordResponse skyflowId(String skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + /** + * ID of the deleted record. + * @return skyflowId + */ + @javax.annotation.Nullable + public String getSkyflowId() { + return skyflowId; + } + + public void setSkyflowId(String skyflowId) { + this.skyflowId = skyflowId; + } + + + public V1DeleteRecordResponse deleted(Boolean deleted) { + this.deleted = deleted; + return this; + } + + /** + * If `true`, the record was deleted. + * @return deleted + */ + @javax.annotation.Nullable + public Boolean getDeleted() { + return deleted; + } + + public void setDeleted(Boolean deleted) { + this.deleted = deleted; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1DeleteRecordResponse v1DeleteRecordResponse = (V1DeleteRecordResponse) o; + return Objects.equals(this.skyflowId, v1DeleteRecordResponse.skyflowId) && + Objects.equals(this.deleted, v1DeleteRecordResponse.deleted); + } + + @Override + public int hashCode() { + return Objects.hash(skyflowId, deleted); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1DeleteRecordResponse {\n"); + sb.append(" skyflowId: ").append(toIndentedString(skyflowId)).append("\n"); + sb.append(" deleted: ").append(toIndentedString(deleted)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("skyflow_id"); + openapiFields.add("deleted"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1DeleteRecordResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1DeleteRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1DeleteRecordResponse is not found in the empty JSON string", V1DeleteRecordResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1DeleteRecordResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1DeleteRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("skyflow_id") != null && !jsonObj.get("skyflow_id").isJsonNull()) && !jsonObj.get("skyflow_id").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `skyflow_id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("skyflow_id").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1DeleteRecordResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1DeleteRecordResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1DeleteRecordResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1DeleteRecordResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1DeleteRecordResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1DeleteRecordResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1DeleteRecordResponse + * @throws IOException if the JSON string is invalid with respect to V1DeleteRecordResponse + */ + public static V1DeleteRecordResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1DeleteRecordResponse.class); + } + + /** + * Convert an instance of V1DeleteRecordResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java new file mode 100644 index 00000000..fdc5c52e --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java @@ -0,0 +1,279 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1DetokenizeRecordRequest; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1DetokenizePayload + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1DetokenizePayload { + public static final String SERIALIZED_NAME_DETOKENIZATION_PARAMETERS = "detokenizationParameters"; + @SerializedName(SERIALIZED_NAME_DETOKENIZATION_PARAMETERS) + private List detokenizationParameters = new ArrayList<>(); + + public static final String SERIALIZED_NAME_DOWNLOAD_U_R_L = "downloadURL"; + @SerializedName(SERIALIZED_NAME_DOWNLOAD_U_R_L) + private Boolean downloadURL; + + public static final String SERIALIZED_NAME_CONTINUE_ON_ERROR = "continueOnError"; + @SerializedName(SERIALIZED_NAME_CONTINUE_ON_ERROR) + private Boolean continueOnError = false; + + public V1DetokenizePayload() { + } + + public V1DetokenizePayload detokenizationParameters(List detokenizationParameters) { + this.detokenizationParameters = detokenizationParameters; + return this; + } + + public V1DetokenizePayload addDetokenizationParametersItem(V1DetokenizeRecordRequest detokenizationParametersItem) { + if (this.detokenizationParameters == null) { + this.detokenizationParameters = new ArrayList<>(); + } + this.detokenizationParameters.add(detokenizationParametersItem); + return this; + } + + /** + * Detokenization details. + * @return detokenizationParameters + */ + @javax.annotation.Nullable + public List getDetokenizationParameters() { + return detokenizationParameters; + } + + public void setDetokenizationParameters(List detokenizationParameters) { + this.detokenizationParameters = detokenizationParameters; + } + + + public V1DetokenizePayload downloadURL(Boolean downloadURL) { + this.downloadURL = downloadURL; + return this; + } + + /** + * If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + * @return downloadURL + */ + @javax.annotation.Nullable + public Boolean getDownloadURL() { + return downloadURL; + } + + public void setDownloadURL(Boolean downloadURL) { + this.downloadURL = downloadURL; + } + + + public V1DetokenizePayload continueOnError(Boolean continueOnError) { + this.continueOnError = continueOnError; + return this; + } + + /** + * If `true`, the detokenization request continues even if an error occurs. + * @return continueOnError + */ + @javax.annotation.Nullable + public Boolean getContinueOnError() { + return continueOnError; + } + + public void setContinueOnError(Boolean continueOnError) { + this.continueOnError = continueOnError; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1DetokenizePayload v1DetokenizePayload = (V1DetokenizePayload) o; + return Objects.equals(this.detokenizationParameters, v1DetokenizePayload.detokenizationParameters) && + Objects.equals(this.downloadURL, v1DetokenizePayload.downloadURL) && + Objects.equals(this.continueOnError, v1DetokenizePayload.continueOnError); + } + + @Override + public int hashCode() { + return Objects.hash(detokenizationParameters, downloadURL, continueOnError); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1DetokenizePayload {\n"); + sb.append(" detokenizationParameters: ").append(toIndentedString(detokenizationParameters)).append("\n"); + sb.append(" downloadURL: ").append(toIndentedString(downloadURL)).append("\n"); + sb.append(" continueOnError: ").append(toIndentedString(continueOnError)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("detokenizationParameters"); + openapiFields.add("downloadURL"); + openapiFields.add("continueOnError"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1DetokenizePayload + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1DetokenizePayload.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1DetokenizePayload is not found in the empty JSON string", V1DetokenizePayload.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1DetokenizePayload.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1DetokenizePayload` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (jsonObj.get("detokenizationParameters") != null && !jsonObj.get("detokenizationParameters").isJsonNull()) { + JsonArray jsonArraydetokenizationParameters = jsonObj.getAsJsonArray("detokenizationParameters"); + if (jsonArraydetokenizationParameters != null) { + // ensure the json data is an array + if (!jsonObj.get("detokenizationParameters").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `detokenizationParameters` to be an array in the JSON string but got `%s`", jsonObj.get("detokenizationParameters").toString())); + } + + // validate the optional field `detokenizationParameters` (array) + for (int i = 0; i < jsonArraydetokenizationParameters.size(); i++) { + V1DetokenizeRecordRequest.validateJsonElement(jsonArraydetokenizationParameters.get(i)); + }; + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1DetokenizePayload.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1DetokenizePayload' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1DetokenizePayload.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1DetokenizePayload value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1DetokenizePayload read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1DetokenizePayload given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1DetokenizePayload + * @throws IOException if the JSON string is invalid with respect to V1DetokenizePayload + */ + public static V1DetokenizePayload fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1DetokenizePayload.class); + } + + /** + * Convert an instance of V1DetokenizePayload to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java new file mode 100644 index 00000000..391fa2fc --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java @@ -0,0 +1,236 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.RedactionEnumREDACTION; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1DetokenizeRecordRequest + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1DetokenizeRecordRequest { + public static final String SERIALIZED_NAME_TOKEN = "token"; + @SerializedName(SERIALIZED_NAME_TOKEN) + private String token; + + public static final String SERIALIZED_NAME_REDACTION = "redaction"; + @SerializedName(SERIALIZED_NAME_REDACTION) + private RedactionEnumREDACTION redaction = RedactionEnumREDACTION.DEFAULT; + + public V1DetokenizeRecordRequest() { + } + + public V1DetokenizeRecordRequest token(String token) { + this.token = token; + return this; + } + + /** + * Token that identifies the record to detokenize. + * @return token + */ + @javax.annotation.Nullable + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + + public V1DetokenizeRecordRequest redaction(RedactionEnumREDACTION redaction) { + this.redaction = redaction; + return this; + } + + /** + * Get redaction + * @return redaction + */ + @javax.annotation.Nullable + public RedactionEnumREDACTION getRedaction() { + return redaction; + } + + public void setRedaction(RedactionEnumREDACTION redaction) { + this.redaction = redaction; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1DetokenizeRecordRequest v1DetokenizeRecordRequest = (V1DetokenizeRecordRequest) o; + return Objects.equals(this.token, v1DetokenizeRecordRequest.token) && + Objects.equals(this.redaction, v1DetokenizeRecordRequest.redaction); + } + + @Override + public int hashCode() { + return Objects.hash(token, redaction); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1DetokenizeRecordRequest {\n"); + sb.append(" token: ").append(toIndentedString(token)).append("\n"); + sb.append(" redaction: ").append(toIndentedString(redaction)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("token"); + openapiFields.add("redaction"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1DetokenizeRecordRequest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1DetokenizeRecordRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1DetokenizeRecordRequest is not found in the empty JSON string", V1DetokenizeRecordRequest.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1DetokenizeRecordRequest.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1DetokenizeRecordRequest` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("token") != null && !jsonObj.get("token").isJsonNull()) && !jsonObj.get("token").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `token` to be a primitive type in the JSON string but got `%s`", jsonObj.get("token").toString())); + } + // validate the optional field `redaction` + if (jsonObj.get("redaction") != null && !jsonObj.get("redaction").isJsonNull()) { + RedactionEnumREDACTION.validateJsonElement(jsonObj.get("redaction")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1DetokenizeRecordRequest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1DetokenizeRecordRequest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1DetokenizeRecordRequest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1DetokenizeRecordRequest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1DetokenizeRecordRequest read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1DetokenizeRecordRequest given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1DetokenizeRecordRequest + * @throws IOException if the JSON string is invalid with respect to V1DetokenizeRecordRequest + */ + public static V1DetokenizeRecordRequest fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1DetokenizeRecordRequest.class); + } + + /** + * Convert an instance of V1DetokenizeRecordRequest to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java new file mode 100644 index 00000000..5c223793 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java @@ -0,0 +1,294 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.DetokenizeRecordResponseValueType; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1DetokenizeRecordResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1DetokenizeRecordResponse { + public static final String SERIALIZED_NAME_TOKEN = "token"; + @SerializedName(SERIALIZED_NAME_TOKEN) + private String token; + + public static final String SERIALIZED_NAME_VALUE_TYPE = "valueType"; + @SerializedName(SERIALIZED_NAME_VALUE_TYPE) + private DetokenizeRecordResponseValueType valueType = DetokenizeRecordResponseValueType.NONE; + + public static final String SERIALIZED_NAME_VALUE = "value"; + @SerializedName(SERIALIZED_NAME_VALUE) + private String value; + + public static final String SERIALIZED_NAME_ERROR = "error"; + @SerializedName(SERIALIZED_NAME_ERROR) + private String error; + + public V1DetokenizeRecordResponse() { + } + + public V1DetokenizeRecordResponse token(String token) { + this.token = token; + return this; + } + + /** + * Token of the record. + * @return token + */ + @javax.annotation.Nullable + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + + public V1DetokenizeRecordResponse valueType(DetokenizeRecordResponseValueType valueType) { + this.valueType = valueType; + return this; + } + + /** + * Get valueType + * @return valueType + */ + @javax.annotation.Nullable + public DetokenizeRecordResponseValueType getValueType() { + return valueType; + } + + public void setValueType(DetokenizeRecordResponseValueType valueType) { + this.valueType = valueType; + } + + + public V1DetokenizeRecordResponse value(String value) { + this.value = value; + return this; + } + + /** + * Data corresponding to the token. + * @return value + */ + @javax.annotation.Nullable + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + + public V1DetokenizeRecordResponse error(String error) { + this.error = error; + return this; + } + + /** + * Error if token isn't found. + * @return error + */ + @javax.annotation.Nullable + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1DetokenizeRecordResponse v1DetokenizeRecordResponse = (V1DetokenizeRecordResponse) o; + return Objects.equals(this.token, v1DetokenizeRecordResponse.token) && + Objects.equals(this.valueType, v1DetokenizeRecordResponse.valueType) && + Objects.equals(this.value, v1DetokenizeRecordResponse.value) && + Objects.equals(this.error, v1DetokenizeRecordResponse.error); + } + + @Override + public int hashCode() { + return Objects.hash(token, valueType, value, error); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1DetokenizeRecordResponse {\n"); + sb.append(" token: ").append(toIndentedString(token)).append("\n"); + sb.append(" valueType: ").append(toIndentedString(valueType)).append("\n"); + sb.append(" value: ").append(toIndentedString(value)).append("\n"); + sb.append(" error: ").append(toIndentedString(error)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("token"); + openapiFields.add("valueType"); + openapiFields.add("value"); + openapiFields.add("error"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1DetokenizeRecordResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1DetokenizeRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1DetokenizeRecordResponse is not found in the empty JSON string", V1DetokenizeRecordResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1DetokenizeRecordResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1DetokenizeRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("token") != null && !jsonObj.get("token").isJsonNull()) && !jsonObj.get("token").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `token` to be a primitive type in the JSON string but got `%s`", jsonObj.get("token").toString())); + } + // validate the optional field `valueType` + if (jsonObj.get("valueType") != null && !jsonObj.get("valueType").isJsonNull()) { + DetokenizeRecordResponseValueType.validateJsonElement(jsonObj.get("valueType")); + } + if ((jsonObj.get("value") != null && !jsonObj.get("value").isJsonNull()) && !jsonObj.get("value").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `value` to be a primitive type in the JSON string but got `%s`", jsonObj.get("value").toString())); + } + if ((jsonObj.get("error") != null && !jsonObj.get("error").isJsonNull()) && !jsonObj.get("error").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `error` to be a primitive type in the JSON string but got `%s`", jsonObj.get("error").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1DetokenizeRecordResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1DetokenizeRecordResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1DetokenizeRecordResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1DetokenizeRecordResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1DetokenizeRecordResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1DetokenizeRecordResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1DetokenizeRecordResponse + * @throws IOException if the JSON string is invalid with respect to V1DetokenizeRecordResponse + */ + public static V1DetokenizeRecordResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1DetokenizeRecordResponse.class); + } + + /** + * Convert an instance of V1DetokenizeRecordResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java new file mode 100644 index 00000000..ed996183 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java @@ -0,0 +1,227 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1DetokenizeRecordResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1DetokenizeResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1DetokenizeResponse { + public static final String SERIALIZED_NAME_RECORDS = "records"; + @SerializedName(SERIALIZED_NAME_RECORDS) + private List records = new ArrayList<>(); + + public V1DetokenizeResponse() { + } + + public V1DetokenizeResponse records(List records) { + this.records = records; + return this; + } + + public V1DetokenizeResponse addRecordsItem(V1DetokenizeRecordResponse recordsItem) { + if (this.records == null) { + this.records = new ArrayList<>(); + } + this.records.add(recordsItem); + return this; + } + + /** + * Records corresponding to the specified tokens. + * @return records + */ + @javax.annotation.Nullable + public List getRecords() { + return records; + } + + public void setRecords(List records) { + this.records = records; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1DetokenizeResponse v1DetokenizeResponse = (V1DetokenizeResponse) o; + return Objects.equals(this.records, v1DetokenizeResponse.records); + } + + @Override + public int hashCode() { + return Objects.hash(records); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1DetokenizeResponse {\n"); + sb.append(" records: ").append(toIndentedString(records)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("records"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1DetokenizeResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1DetokenizeResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1DetokenizeResponse is not found in the empty JSON string", V1DetokenizeResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1DetokenizeResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1DetokenizeResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { + JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); + if (jsonArrayrecords != null) { + // ensure the json data is an array + if (!jsonObj.get("records").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); + } + + // validate the optional field `records` (array) + for (int i = 0; i < jsonArrayrecords.size(); i++) { + V1DetokenizeRecordResponse.validateJsonElement(jsonArrayrecords.get(i)); + }; + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1DetokenizeResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1DetokenizeResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1DetokenizeResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1DetokenizeResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1DetokenizeResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1DetokenizeResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1DetokenizeResponse + * @throws IOException if the JSON string is invalid with respect to V1DetokenizeResponse + */ + public static V1DetokenizeResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1DetokenizeResponse.class); + } + + /** + * Convert an instance of V1DetokenizeResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java new file mode 100644 index 00000000..9efada66 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java @@ -0,0 +1,228 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * Record values and tokens. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1FieldRecords { + public static final String SERIALIZED_NAME_FIELDS = "fields"; + @SerializedName(SERIALIZED_NAME_FIELDS) + private Object fields; + + public static final String SERIALIZED_NAME_TOKENS = "tokens"; + @SerializedName(SERIALIZED_NAME_TOKENS) + private Object tokens; + + public V1FieldRecords() { + } + + public V1FieldRecords fields(Object fields) { + this.fields = fields; + return this; + } + + /** + * Fields and values for the record. For example, `{'field_1':'value_1', 'field_2':'value_2'}`. + * @return fields + */ + @javax.annotation.Nullable + public Object getFields() { + return fields; + } + + public void setFields(Object fields) { + this.fields = fields; + } + + + public V1FieldRecords tokens(Object tokens) { + this.tokens = tokens; + return this; + } + + /** + * Fields and tokens for the record. For example, `{'field_1':'token_1', 'field_2':'token_2'}`. + * @return tokens + */ + @javax.annotation.Nullable + public Object getTokens() { + return tokens; + } + + public void setTokens(Object tokens) { + this.tokens = tokens; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1FieldRecords v1FieldRecords = (V1FieldRecords) o; + return Objects.equals(this.fields, v1FieldRecords.fields) && + Objects.equals(this.tokens, v1FieldRecords.tokens); + } + + @Override + public int hashCode() { + return Objects.hash(fields, tokens); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1FieldRecords {\n"); + sb.append(" fields: ").append(toIndentedString(fields)).append("\n"); + sb.append(" tokens: ").append(toIndentedString(tokens)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("fields"); + openapiFields.add("tokens"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1FieldRecords + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1FieldRecords.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1FieldRecords is not found in the empty JSON string", V1FieldRecords.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1FieldRecords.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1FieldRecords` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1FieldRecords.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1FieldRecords' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1FieldRecords.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1FieldRecords value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1FieldRecords read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1FieldRecords given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1FieldRecords + * @throws IOException if the JSON string is invalid with respect to V1FieldRecords + */ + public static V1FieldRecords fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1FieldRecords.class); + } + + /** + * Convert an instance of V1FieldRecords to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java new file mode 100644 index 00000000..af3f490f --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java @@ -0,0 +1,92 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Anti-virus scan status of the file. + */ +@JsonAdapter(V1FileAVScanStatus.Adapter.class) +public enum V1FileAVScanStatus { + + NONE("SCAN_NONE"), + + CLEAN("SCAN_CLEAN"), + + INFECTED("SCAN_INFECTED"), + + DELETED("SCAN_DELETED"), + + ERROR("SCAN_ERROR"), + + PENDING("SCAN_PENDING"), + + UNSCANNABLE("SCAN_UNSCANNABLE"), + + FILE_NOT_FOUND("SCAN_FILE_NOT_FOUND"), + + INVALID("SCAN_INVALID"); + + private String value; + + V1FileAVScanStatus(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static V1FileAVScanStatus fromValue(String value) { + for (V1FileAVScanStatus b : V1FileAVScanStatus.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final V1FileAVScanStatus enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public V1FileAVScanStatus read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return V1FileAVScanStatus.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + V1FileAVScanStatus.fromValue(value); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java new file mode 100644 index 00000000..c2d6bf1d --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java @@ -0,0 +1,359 @@ +/* + * Skyflow Management API + * # Management API This API controls aspects of your account and schema, including workspaces, vaults, keys, users, permissions, and more. The Management API is available from two base URIs:
  • Sandbox: https://manage.skyflowapis-preview.com
  • Production: https://manage.skyflowapis.com
When you make an API call, you need to add two headers:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
X-SKYFLOW-ACCOUNT-IDYour Skyflow account ID.X-SKYFLOW-ACCOUNT-ID: h451b763713e4424a7jke1bbkbbc84ef
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1GetAuthTokenRequest + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-10-03T10:28:16.037563+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1GetAuthTokenRequest { + public static final String SERIALIZED_NAME_GRANT_TYPE = "grant_type"; + @SerializedName(SERIALIZED_NAME_GRANT_TYPE) + private String grantType; + + public static final String SERIALIZED_NAME_ASSERTION = "assertion"; + @SerializedName(SERIALIZED_NAME_ASSERTION) + private String assertion; + + public static final String SERIALIZED_NAME_SUBJECT_TOKEN = "subject_token"; + @SerializedName(SERIALIZED_NAME_SUBJECT_TOKEN) + private String subjectToken; + + public static final String SERIALIZED_NAME_SUBJECT_TOKEN_TYPE = "subject_token_type"; + @SerializedName(SERIALIZED_NAME_SUBJECT_TOKEN_TYPE) + private String subjectTokenType; + + public static final String SERIALIZED_NAME_REQUESTED_TOKEN_USE = "requested_token_use"; + @SerializedName(SERIALIZED_NAME_REQUESTED_TOKEN_USE) + private String requestedTokenUse; + + public static final String SERIALIZED_NAME_SCOPE = "scope"; + @SerializedName(SERIALIZED_NAME_SCOPE) + private String scope; + + public V1GetAuthTokenRequest() { + } + + public V1GetAuthTokenRequest grantType(String grantType) { + this.grantType = grantType; + return this; + } + + /** + * Grant type of the request. Set this to `urn:ietf:params:oauth:grant-type:jwt-bearer`. + * @return grantType + */ + @javax.annotation.Nonnull + public String getGrantType() { + return grantType; + } + + public void setGrantType(String grantType) { + this.grantType = grantType; + } + + + public V1GetAuthTokenRequest assertion(String assertion) { + this.assertion = assertion; + return this; + } + + /** + * User-signed JWT token that contains the following fields: <br/> <ul><li><code>iss</code>: Issuer of the JWT.</li><li><code>key</code>: Unique identifier for the key.</li><li><code>aud</code>: Recipient the JWT is intended for.</li><li><code>exp</code>: Time the JWT expires.</li><li><code>sub</code>: Subject of the JWT.</li><li><code>ctx</code>: (Optional) Value for <a href='/context-aware-overview/'>Context-aware authorization</a>.</li></ul> + * @return assertion + */ + @javax.annotation.Nonnull + public String getAssertion() { + return assertion; + } + + public void setAssertion(String assertion) { + this.assertion = assertion; + } + + + public V1GetAuthTokenRequest subjectToken(String subjectToken) { + this.subjectToken = subjectToken; + return this; + } + + /** + * Subject token. + * @return subjectToken + */ + @javax.annotation.Nullable + public String getSubjectToken() { + return subjectToken; + } + + public void setSubjectToken(String subjectToken) { + this.subjectToken = subjectToken; + } + + + public V1GetAuthTokenRequest subjectTokenType(String subjectTokenType) { + this.subjectTokenType = subjectTokenType; + return this; + } + + /** + * Subject token type. + * @return subjectTokenType + */ + @javax.annotation.Nullable + public String getSubjectTokenType() { + return subjectTokenType; + } + + public void setSubjectTokenType(String subjectTokenType) { + this.subjectTokenType = subjectTokenType; + } + + + public V1GetAuthTokenRequest requestedTokenUse(String requestedTokenUse) { + this.requestedTokenUse = requestedTokenUse; + return this; + } + + /** + * Token use type. Either `delegation` or `impersonation`. + * @return requestedTokenUse + */ + @javax.annotation.Nullable + public String getRequestedTokenUse() { + return requestedTokenUse; + } + + public void setRequestedTokenUse(String requestedTokenUse) { + this.requestedTokenUse = requestedTokenUse; + } + + + public V1GetAuthTokenRequest scope(String scope) { + this.scope = scope; + return this; + } + + /** + * Subset of available <a href='#Roles'>roles</a> to associate with the requested token. Uses the format \"role:\\<roleID1\\> role:\\<roleID2\\>\". + * @return scope + */ + @javax.annotation.Nullable + public String getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1GetAuthTokenRequest v1GetAuthTokenRequest = (V1GetAuthTokenRequest) o; + return Objects.equals(this.grantType, v1GetAuthTokenRequest.grantType) && + Objects.equals(this.assertion, v1GetAuthTokenRequest.assertion) && + Objects.equals(this.subjectToken, v1GetAuthTokenRequest.subjectToken) && + Objects.equals(this.subjectTokenType, v1GetAuthTokenRequest.subjectTokenType) && + Objects.equals(this.requestedTokenUse, v1GetAuthTokenRequest.requestedTokenUse) && + Objects.equals(this.scope, v1GetAuthTokenRequest.scope); + } + + @Override + public int hashCode() { + return Objects.hash(grantType, assertion, subjectToken, subjectTokenType, requestedTokenUse, scope); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1GetAuthTokenRequest {\n"); + sb.append(" grantType: ").append(toIndentedString(grantType)).append("\n"); + sb.append(" assertion: ").append(toIndentedString(assertion)).append("\n"); + sb.append(" subjectToken: ").append(toIndentedString(subjectToken)).append("\n"); + sb.append(" subjectTokenType: ").append(toIndentedString(subjectTokenType)).append("\n"); + sb.append(" requestedTokenUse: ").append(toIndentedString(requestedTokenUse)).append("\n"); + sb.append(" scope: ").append(toIndentedString(scope)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("grant_type"); + openapiFields.add("assertion"); + openapiFields.add("subject_token"); + openapiFields.add("subject_token_type"); + openapiFields.add("requested_token_use"); + openapiFields.add("scope"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("grant_type"); + openapiRequiredFields.add("assertion"); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1GetAuthTokenRequest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1GetAuthTokenRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1GetAuthTokenRequest is not found in the empty JSON string", V1GetAuthTokenRequest.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1GetAuthTokenRequest.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1GetAuthTokenRequest` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : V1GetAuthTokenRequest.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("grant_type").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `grant_type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("grant_type").toString())); + } + if (!jsonObj.get("assertion").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `assertion` to be a primitive type in the JSON string but got `%s`", jsonObj.get("assertion").toString())); + } + if ((jsonObj.get("subject_token") != null && !jsonObj.get("subject_token").isJsonNull()) && !jsonObj.get("subject_token").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `subject_token` to be a primitive type in the JSON string but got `%s`", jsonObj.get("subject_token").toString())); + } + if ((jsonObj.get("subject_token_type") != null && !jsonObj.get("subject_token_type").isJsonNull()) && !jsonObj.get("subject_token_type").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `subject_token_type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("subject_token_type").toString())); + } + if ((jsonObj.get("requested_token_use") != null && !jsonObj.get("requested_token_use").isJsonNull()) && !jsonObj.get("requested_token_use").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `requested_token_use` to be a primitive type in the JSON string but got `%s`", jsonObj.get("requested_token_use").toString())); + } + if ((jsonObj.get("scope") != null && !jsonObj.get("scope").isJsonNull()) && !jsonObj.get("scope").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `scope` to be a primitive type in the JSON string but got `%s`", jsonObj.get("scope").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1GetAuthTokenRequest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1GetAuthTokenRequest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1GetAuthTokenRequest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1GetAuthTokenRequest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1GetAuthTokenRequest read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1GetAuthTokenRequest given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1GetAuthTokenRequest + * @throws IOException if the JSON string is invalid with respect to V1GetAuthTokenRequest + */ + public static V1GetAuthTokenRequest fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1GetAuthTokenRequest.class); + } + + /** + * Convert an instance of V1GetAuthTokenRequest to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java new file mode 100644 index 00000000..d6c0f61f --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java @@ -0,0 +1,234 @@ +/* + * Skyflow Management API + * # Management API This API controls aspects of your account and schema, including workspaces, vaults, keys, users, permissions, and more. The Management API is available from two base URIs:
  • Sandbox: https://manage.skyflowapis-preview.com
  • Production: https://manage.skyflowapis.com
When you make an API call, you need to add two headers:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
X-SKYFLOW-ACCOUNT-IDYour Skyflow account ID.X-SKYFLOW-ACCOUNT-ID: h451b763713e4424a7jke1bbkbbc84ef
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1GetAuthTokenResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-10-03T10:28:16.037563+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1GetAuthTokenResponse { + public static final String SERIALIZED_NAME_ACCESS_TOKEN = "accessToken"; + @SerializedName(SERIALIZED_NAME_ACCESS_TOKEN) + private String accessToken; + + public static final String SERIALIZED_NAME_TOKEN_TYPE = "tokenType"; + @SerializedName(SERIALIZED_NAME_TOKEN_TYPE) + private String tokenType; + + public V1GetAuthTokenResponse() { + } + + public V1GetAuthTokenResponse accessToken(String accessToken) { + this.accessToken = accessToken; + return this; + } + + /** + * AccessToken. + * @return accessToken + */ + @javax.annotation.Nullable + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + + public V1GetAuthTokenResponse tokenType(String tokenType) { + this.tokenType = tokenType; + return this; + } + + /** + * TokenType : Bearer. + * @return tokenType + */ + @javax.annotation.Nullable + public String getTokenType() { + return tokenType; + } + + public void setTokenType(String tokenType) { + this.tokenType = tokenType; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1GetAuthTokenResponse v1GetAuthTokenResponse = (V1GetAuthTokenResponse) o; + return Objects.equals(this.accessToken, v1GetAuthTokenResponse.accessToken) && + Objects.equals(this.tokenType, v1GetAuthTokenResponse.tokenType); + } + + @Override + public int hashCode() { + return Objects.hash(accessToken, tokenType); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1GetAuthTokenResponse {\n"); + sb.append(" accessToken: ").append(toIndentedString(accessToken)).append("\n"); + sb.append(" tokenType: ").append(toIndentedString(tokenType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("accessToken"); + openapiFields.add("tokenType"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1GetAuthTokenResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1GetAuthTokenResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1GetAuthTokenResponse is not found in the empty JSON string", V1GetAuthTokenResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1GetAuthTokenResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1GetAuthTokenResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("accessToken") != null && !jsonObj.get("accessToken").isJsonNull()) && !jsonObj.get("accessToken").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `accessToken` to be a primitive type in the JSON string but got `%s`", jsonObj.get("accessToken").toString())); + } + if ((jsonObj.get("tokenType") != null && !jsonObj.get("tokenType").isJsonNull()) && !jsonObj.get("tokenType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `tokenType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("tokenType").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1GetAuthTokenResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1GetAuthTokenResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1GetAuthTokenResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1GetAuthTokenResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1GetAuthTokenResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1GetAuthTokenResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1GetAuthTokenResponse + * @throws IOException if the JSON string is invalid with respect to V1GetAuthTokenResponse + */ + public static V1GetAuthTokenResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1GetAuthTokenResponse.class); + } + + /** + * Convert an instance of V1GetAuthTokenResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java new file mode 100644 index 00000000..4bce5d74 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java @@ -0,0 +1,207 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1FileAVScanStatus; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1GetFileScanStatusResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1GetFileScanStatusResponse { + public static final String SERIALIZED_NAME_AV_SCAN_STATUS = "av_scan_status"; + @SerializedName(SERIALIZED_NAME_AV_SCAN_STATUS) + private V1FileAVScanStatus avScanStatus = V1FileAVScanStatus.NONE; + + public V1GetFileScanStatusResponse() { + } + + public V1GetFileScanStatusResponse avScanStatus(V1FileAVScanStatus avScanStatus) { + this.avScanStatus = avScanStatus; + return this; + } + + /** + * Get avScanStatus + * @return avScanStatus + */ + @javax.annotation.Nullable + public V1FileAVScanStatus getAvScanStatus() { + return avScanStatus; + } + + public void setAvScanStatus(V1FileAVScanStatus avScanStatus) { + this.avScanStatus = avScanStatus; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1GetFileScanStatusResponse v1GetFileScanStatusResponse = (V1GetFileScanStatusResponse) o; + return Objects.equals(this.avScanStatus, v1GetFileScanStatusResponse.avScanStatus); + } + + @Override + public int hashCode() { + return Objects.hash(avScanStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1GetFileScanStatusResponse {\n"); + sb.append(" avScanStatus: ").append(toIndentedString(avScanStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("av_scan_status"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1GetFileScanStatusResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1GetFileScanStatusResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1GetFileScanStatusResponse is not found in the empty JSON string", V1GetFileScanStatusResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1GetFileScanStatusResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1GetFileScanStatusResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `av_scan_status` + if (jsonObj.get("av_scan_status") != null && !jsonObj.get("av_scan_status").isJsonNull()) { + V1FileAVScanStatus.validateJsonElement(jsonObj.get("av_scan_status")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1GetFileScanStatusResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1GetFileScanStatusResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1GetFileScanStatusResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1GetFileScanStatusResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1GetFileScanStatusResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1GetFileScanStatusResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1GetFileScanStatusResponse + * @throws IOException if the JSON string is invalid with respect to V1GetFileScanStatusResponse + */ + public static V1GetFileScanStatusResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1GetFileScanStatusResponse.class); + } + + /** + * Convert an instance of V1GetFileScanStatusResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java new file mode 100644 index 00000000..2ff57e57 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java @@ -0,0 +1,227 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1FieldRecords; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1GetQueryResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1GetQueryResponse { + public static final String SERIALIZED_NAME_RECORDS = "records"; + @SerializedName(SERIALIZED_NAME_RECORDS) + private List records = new ArrayList<>(); + + public V1GetQueryResponse() { + } + + public V1GetQueryResponse records(List records) { + this.records = records; + return this; + } + + public V1GetQueryResponse addRecordsItem(V1FieldRecords recordsItem) { + if (this.records == null) { + this.records = new ArrayList<>(); + } + this.records.add(recordsItem); + return this; + } + + /** + * Records returned by the query. + * @return records + */ + @javax.annotation.Nullable + public List getRecords() { + return records; + } + + public void setRecords(List records) { + this.records = records; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1GetQueryResponse v1GetQueryResponse = (V1GetQueryResponse) o; + return Objects.equals(this.records, v1GetQueryResponse.records); + } + + @Override + public int hashCode() { + return Objects.hash(records); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1GetQueryResponse {\n"); + sb.append(" records: ").append(toIndentedString(records)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("records"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1GetQueryResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1GetQueryResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1GetQueryResponse is not found in the empty JSON string", V1GetQueryResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1GetQueryResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1GetQueryResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { + JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); + if (jsonArrayrecords != null) { + // ensure the json data is an array + if (!jsonObj.get("records").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); + } + + // validate the optional field `records` (array) + for (int i = 0; i < jsonArrayrecords.size(); i++) { + V1FieldRecords.validateJsonElement(jsonArrayrecords.get(i)); + }; + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1GetQueryResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1GetQueryResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1GetQueryResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1GetQueryResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1GetQueryResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1GetQueryResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1GetQueryResponse + * @throws IOException if the JSON string is invalid with respect to V1GetQueryResponse + */ + public static V1GetQueryResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1GetQueryResponse.class); + } + + /** + * Convert an instance of V1GetQueryResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java new file mode 100644 index 00000000..f4f432b3 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java @@ -0,0 +1,227 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1RecordMetaProperties; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1InsertRecordResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1InsertRecordResponse { + public static final String SERIALIZED_NAME_RECORDS = "records"; + @SerializedName(SERIALIZED_NAME_RECORDS) + private List records = new ArrayList<>(); + + public V1InsertRecordResponse() { + } + + public V1InsertRecordResponse records(List records) { + this.records = records; + return this; + } + + public V1InsertRecordResponse addRecordsItem(V1RecordMetaProperties recordsItem) { + if (this.records == null) { + this.records = new ArrayList<>(); + } + this.records.add(recordsItem); + return this; + } + + /** + * Identifiers for the inserted records. + * @return records + */ + @javax.annotation.Nullable + public List getRecords() { + return records; + } + + public void setRecords(List records) { + this.records = records; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1InsertRecordResponse v1InsertRecordResponse = (V1InsertRecordResponse) o; + return Objects.equals(this.records, v1InsertRecordResponse.records); + } + + @Override + public int hashCode() { + return Objects.hash(records); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1InsertRecordResponse {\n"); + sb.append(" records: ").append(toIndentedString(records)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("records"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1InsertRecordResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1InsertRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1InsertRecordResponse is not found in the empty JSON string", V1InsertRecordResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1InsertRecordResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1InsertRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { + JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); + if (jsonArrayrecords != null) { + // ensure the json data is an array + if (!jsonObj.get("records").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); + } + + // validate the optional field `records` (array) + for (int i = 0; i < jsonArrayrecords.size(); i++) { + V1RecordMetaProperties.validateJsonElement(jsonArrayrecords.get(i)); + }; + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1InsertRecordResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1InsertRecordResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1InsertRecordResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1InsertRecordResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1InsertRecordResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1InsertRecordResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1InsertRecordResponse + * @throws IOException if the JSON string is invalid with respect to V1InsertRecordResponse + */ + public static V1InsertRecordResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1InsertRecordResponse.class); + } + + /** + * Convert an instance of V1InsertRecordResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1MemberType.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1MemberType.java new file mode 100644 index 00000000..5cb1ce8b --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1MemberType.java @@ -0,0 +1,80 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Type of the member. + */ +@JsonAdapter(V1MemberType.Adapter.class) +public enum V1MemberType { + + NONE("NONE"), + + USER("USER"), + + SERVICE_ACCOUNT("SERVICE_ACCOUNT"); + + private String value; + + V1MemberType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static V1MemberType fromValue(String value) { + for (V1MemberType b : V1MemberType.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final V1MemberType enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public V1MemberType read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return V1MemberType.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + V1MemberType.fromValue(value); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java new file mode 100644 index 00000000..e0aaf47e --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java @@ -0,0 +1,231 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1RecordMetaProperties + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1RecordMetaProperties { + public static final String SERIALIZED_NAME_SKYFLOW_ID = "skyflow_id"; + @SerializedName(SERIALIZED_NAME_SKYFLOW_ID) + private String skyflowId; + + public static final String SERIALIZED_NAME_TOKENS = "tokens"; + @SerializedName(SERIALIZED_NAME_TOKENS) + private Object tokens; + + public V1RecordMetaProperties() { + } + + public V1RecordMetaProperties skyflowId(String skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + /** + * ID of the inserted record. + * @return skyflowId + */ + @javax.annotation.Nullable + public String getSkyflowId() { + return skyflowId; + } + + public void setSkyflowId(String skyflowId) { + this.skyflowId = skyflowId; + } + + + public V1RecordMetaProperties tokens(Object tokens) { + this.tokens = tokens; + return this; + } + + /** + * Tokens for the record. + * @return tokens + */ + @javax.annotation.Nullable + public Object getTokens() { + return tokens; + } + + public void setTokens(Object tokens) { + this.tokens = tokens; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1RecordMetaProperties v1RecordMetaProperties = (V1RecordMetaProperties) o; + return Objects.equals(this.skyflowId, v1RecordMetaProperties.skyflowId) && + Objects.equals(this.tokens, v1RecordMetaProperties.tokens); + } + + @Override + public int hashCode() { + return Objects.hash(skyflowId, tokens); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1RecordMetaProperties {\n"); + sb.append(" skyflowId: ").append(toIndentedString(skyflowId)).append("\n"); + sb.append(" tokens: ").append(toIndentedString(tokens)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("skyflow_id"); + openapiFields.add("tokens"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1RecordMetaProperties + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1RecordMetaProperties.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1RecordMetaProperties is not found in the empty JSON string", V1RecordMetaProperties.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1RecordMetaProperties.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1RecordMetaProperties` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("skyflow_id") != null && !jsonObj.get("skyflow_id").isJsonNull()) && !jsonObj.get("skyflow_id").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `skyflow_id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("skyflow_id").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1RecordMetaProperties.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1RecordMetaProperties' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1RecordMetaProperties.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1RecordMetaProperties value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1RecordMetaProperties read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1RecordMetaProperties given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1RecordMetaProperties + * @throws IOException if the JSON string is invalid with respect to V1RecordMetaProperties + */ + public static V1RecordMetaProperties fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1RecordMetaProperties.class); + } + + /** + * Convert an instance of V1RecordMetaProperties to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java new file mode 100644 index 00000000..74936451 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java @@ -0,0 +1,227 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1TokenizeRecordRequest; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1TokenizePayload + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1TokenizePayload { + public static final String SERIALIZED_NAME_TOKENIZATION_PARAMETERS = "tokenizationParameters"; + @SerializedName(SERIALIZED_NAME_TOKENIZATION_PARAMETERS) + private List tokenizationParameters = new ArrayList<>(); + + public V1TokenizePayload() { + } + + public V1TokenizePayload tokenizationParameters(List tokenizationParameters) { + this.tokenizationParameters = tokenizationParameters; + return this; + } + + public V1TokenizePayload addTokenizationParametersItem(V1TokenizeRecordRequest tokenizationParametersItem) { + if (this.tokenizationParameters == null) { + this.tokenizationParameters = new ArrayList<>(); + } + this.tokenizationParameters.add(tokenizationParametersItem); + return this; + } + + /** + * Tokenization details. + * @return tokenizationParameters + */ + @javax.annotation.Nullable + public List getTokenizationParameters() { + return tokenizationParameters; + } + + public void setTokenizationParameters(List tokenizationParameters) { + this.tokenizationParameters = tokenizationParameters; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1TokenizePayload v1TokenizePayload = (V1TokenizePayload) o; + return Objects.equals(this.tokenizationParameters, v1TokenizePayload.tokenizationParameters); + } + + @Override + public int hashCode() { + return Objects.hash(tokenizationParameters); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1TokenizePayload {\n"); + sb.append(" tokenizationParameters: ").append(toIndentedString(tokenizationParameters)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("tokenizationParameters"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1TokenizePayload + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1TokenizePayload.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1TokenizePayload is not found in the empty JSON string", V1TokenizePayload.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1TokenizePayload.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1TokenizePayload` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (jsonObj.get("tokenizationParameters") != null && !jsonObj.get("tokenizationParameters").isJsonNull()) { + JsonArray jsonArraytokenizationParameters = jsonObj.getAsJsonArray("tokenizationParameters"); + if (jsonArraytokenizationParameters != null) { + // ensure the json data is an array + if (!jsonObj.get("tokenizationParameters").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `tokenizationParameters` to be an array in the JSON string but got `%s`", jsonObj.get("tokenizationParameters").toString())); + } + + // validate the optional field `tokenizationParameters` (array) + for (int i = 0; i < jsonArraytokenizationParameters.size(); i++) { + V1TokenizeRecordRequest.validateJsonElement(jsonArraytokenizationParameters.get(i)); + }; + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1TokenizePayload.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1TokenizePayload' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1TokenizePayload.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1TokenizePayload value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1TokenizePayload read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1TokenizePayload given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1TokenizePayload + * @throws IOException if the JSON string is invalid with respect to V1TokenizePayload + */ + public static V1TokenizePayload fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1TokenizePayload.class); + } + + /** + * Convert an instance of V1TokenizePayload to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java new file mode 100644 index 00000000..1de790c5 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java @@ -0,0 +1,234 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1TokenizeRecordRequest + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1TokenizeRecordRequest { + public static final String SERIALIZED_NAME_VALUE = "value"; + @SerializedName(SERIALIZED_NAME_VALUE) + private String value; + + public static final String SERIALIZED_NAME_COLUMN_GROUP = "columnGroup"; + @SerializedName(SERIALIZED_NAME_COLUMN_GROUP) + private String columnGroup; + + public V1TokenizeRecordRequest() { + } + + public V1TokenizeRecordRequest value(String value) { + this.value = value; + return this; + } + + /** + * Existing value to return a token for. + * @return value + */ + @javax.annotation.Nullable + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + + public V1TokenizeRecordRequest columnGroup(String columnGroup) { + this.columnGroup = columnGroup; + return this; + } + + /** + * Name of the column group that the value belongs to. + * @return columnGroup + */ + @javax.annotation.Nullable + public String getColumnGroup() { + return columnGroup; + } + + public void setColumnGroup(String columnGroup) { + this.columnGroup = columnGroup; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1TokenizeRecordRequest v1TokenizeRecordRequest = (V1TokenizeRecordRequest) o; + return Objects.equals(this.value, v1TokenizeRecordRequest.value) && + Objects.equals(this.columnGroup, v1TokenizeRecordRequest.columnGroup); + } + + @Override + public int hashCode() { + return Objects.hash(value, columnGroup); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1TokenizeRecordRequest {\n"); + sb.append(" value: ").append(toIndentedString(value)).append("\n"); + sb.append(" columnGroup: ").append(toIndentedString(columnGroup)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("value"); + openapiFields.add("columnGroup"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1TokenizeRecordRequest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1TokenizeRecordRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1TokenizeRecordRequest is not found in the empty JSON string", V1TokenizeRecordRequest.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1TokenizeRecordRequest.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1TokenizeRecordRequest` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("value") != null && !jsonObj.get("value").isJsonNull()) && !jsonObj.get("value").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `value` to be a primitive type in the JSON string but got `%s`", jsonObj.get("value").toString())); + } + if ((jsonObj.get("columnGroup") != null && !jsonObj.get("columnGroup").isJsonNull()) && !jsonObj.get("columnGroup").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `columnGroup` to be a primitive type in the JSON string but got `%s`", jsonObj.get("columnGroup").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1TokenizeRecordRequest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1TokenizeRecordRequest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1TokenizeRecordRequest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1TokenizeRecordRequest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1TokenizeRecordRequest read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1TokenizeRecordRequest given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1TokenizeRecordRequest + * @throws IOException if the JSON string is invalid with respect to V1TokenizeRecordRequest + */ + public static V1TokenizeRecordRequest fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1TokenizeRecordRequest.class); + } + + /** + * Convert an instance of V1TokenizeRecordRequest to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java new file mode 100644 index 00000000..290d7403 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java @@ -0,0 +1,205 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1TokenizeRecordResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1TokenizeRecordResponse { + public static final String SERIALIZED_NAME_TOKEN = "token"; + @SerializedName(SERIALIZED_NAME_TOKEN) + private String token; + + public V1TokenizeRecordResponse() { + } + + public V1TokenizeRecordResponse token(String token) { + this.token = token; + return this; + } + + /** + * Token corresponding to a value. + * @return token + */ + @javax.annotation.Nullable + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1TokenizeRecordResponse v1TokenizeRecordResponse = (V1TokenizeRecordResponse) o; + return Objects.equals(this.token, v1TokenizeRecordResponse.token); + } + + @Override + public int hashCode() { + return Objects.hash(token); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1TokenizeRecordResponse {\n"); + sb.append(" token: ").append(toIndentedString(token)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("token"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1TokenizeRecordResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1TokenizeRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1TokenizeRecordResponse is not found in the empty JSON string", V1TokenizeRecordResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1TokenizeRecordResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1TokenizeRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("token") != null && !jsonObj.get("token").isJsonNull()) && !jsonObj.get("token").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `token` to be a primitive type in the JSON string but got `%s`", jsonObj.get("token").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1TokenizeRecordResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1TokenizeRecordResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1TokenizeRecordResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1TokenizeRecordResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1TokenizeRecordResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1TokenizeRecordResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1TokenizeRecordResponse + * @throws IOException if the JSON string is invalid with respect to V1TokenizeRecordResponse + */ + public static V1TokenizeRecordResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1TokenizeRecordResponse.class); + } + + /** + * Convert an instance of V1TokenizeRecordResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java new file mode 100644 index 00000000..3885c9a5 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java @@ -0,0 +1,227 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1TokenizeRecordResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1TokenizeResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1TokenizeResponse { + public static final String SERIALIZED_NAME_RECORDS = "records"; + @SerializedName(SERIALIZED_NAME_RECORDS) + private List records = new ArrayList<>(); + + public V1TokenizeResponse() { + } + + public V1TokenizeResponse records(List records) { + this.records = records; + return this; + } + + public V1TokenizeResponse addRecordsItem(V1TokenizeRecordResponse recordsItem) { + if (this.records == null) { + this.records = new ArrayList<>(); + } + this.records.add(recordsItem); + return this; + } + + /** + * Tokens corresponding to the specified values. + * @return records + */ + @javax.annotation.Nullable + public List getRecords() { + return records; + } + + public void setRecords(List records) { + this.records = records; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1TokenizeResponse v1TokenizeResponse = (V1TokenizeResponse) o; + return Objects.equals(this.records, v1TokenizeResponse.records); + } + + @Override + public int hashCode() { + return Objects.hash(records); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1TokenizeResponse {\n"); + sb.append(" records: ").append(toIndentedString(records)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("records"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1TokenizeResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1TokenizeResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1TokenizeResponse is not found in the empty JSON string", V1TokenizeResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1TokenizeResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1TokenizeResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { + JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); + if (jsonArrayrecords != null) { + // ensure the json data is an array + if (!jsonObj.get("records").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); + } + + // validate the optional field `records` (array) + for (int i = 0; i < jsonArrayrecords.size(); i++) { + V1TokenizeRecordResponse.validateJsonElement(jsonArrayrecords.get(i)); + }; + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1TokenizeResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1TokenizeResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1TokenizeResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1TokenizeResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1TokenizeResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1TokenizeResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1TokenizeResponse + * @throws IOException if the JSON string is invalid with respect to V1TokenizeResponse + */ + public static V1TokenizeResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1TokenizeResponse.class); + } + + /** + * Convert an instance of V1TokenizeResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java new file mode 100644 index 00000000..b731dd12 --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java @@ -0,0 +1,231 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * V1UpdateRecordResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1UpdateRecordResponse { + public static final String SERIALIZED_NAME_SKYFLOW_ID = "skyflow_id"; + @SerializedName(SERIALIZED_NAME_SKYFLOW_ID) + private String skyflowId; + + public static final String SERIALIZED_NAME_TOKENS = "tokens"; + @SerializedName(SERIALIZED_NAME_TOKENS) + private Object tokens; + + public V1UpdateRecordResponse() { + } + + public V1UpdateRecordResponse skyflowId(String skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + /** + * ID of the updated record. + * @return skyflowId + */ + @javax.annotation.Nullable + public String getSkyflowId() { + return skyflowId; + } + + public void setSkyflowId(String skyflowId) { + this.skyflowId = skyflowId; + } + + + public V1UpdateRecordResponse tokens(Object tokens) { + this.tokens = tokens; + return this; + } + + /** + * Tokens for the record. + * @return tokens + */ + @javax.annotation.Nullable + public Object getTokens() { + return tokens; + } + + public void setTokens(Object tokens) { + this.tokens = tokens; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1UpdateRecordResponse v1UpdateRecordResponse = (V1UpdateRecordResponse) o; + return Objects.equals(this.skyflowId, v1UpdateRecordResponse.skyflowId) && + Objects.equals(this.tokens, v1UpdateRecordResponse.tokens); + } + + @Override + public int hashCode() { + return Objects.hash(skyflowId, tokens); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1UpdateRecordResponse {\n"); + sb.append(" skyflowId: ").append(toIndentedString(skyflowId)).append("\n"); + sb.append(" tokens: ").append(toIndentedString(tokens)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("skyflow_id"); + openapiFields.add("tokens"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1UpdateRecordResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1UpdateRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1UpdateRecordResponse is not found in the empty JSON string", V1UpdateRecordResponse.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1UpdateRecordResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1UpdateRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("skyflow_id") != null && !jsonObj.get("skyflow_id").isJsonNull()) && !jsonObj.get("skyflow_id").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `skyflow_id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("skyflow_id").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1UpdateRecordResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1UpdateRecordResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1UpdateRecordResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1UpdateRecordResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1UpdateRecordResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1UpdateRecordResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1UpdateRecordResponse + * @throws IOException if the JSON string is invalid with respect to V1UpdateRecordResponse + */ + public static V1UpdateRecordResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1UpdateRecordResponse.class); + } + + /** + * Convert an instance of V1UpdateRecordResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java new file mode 100644 index 00000000..582a53fd --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java @@ -0,0 +1,263 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * Mapping of the fields in the vault to the fields to use for the lookup. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1VaultFieldMapping { + public static final String SERIALIZED_NAME_CARD_NUMBER = "card_number"; + @SerializedName(SERIALIZED_NAME_CARD_NUMBER) + private String cardNumber; + + public static final String SERIALIZED_NAME_CARD_LAST_FOUR_DIGITS = "card_last_four_digits"; + @SerializedName(SERIALIZED_NAME_CARD_LAST_FOUR_DIGITS) + private String cardLastFourDigits; + + public static final String SERIALIZED_NAME_CARD_EXPIRY = "card_expiry"; + @SerializedName(SERIALIZED_NAME_CARD_EXPIRY) + private String cardExpiry; + + public V1VaultFieldMapping() { + } + + public V1VaultFieldMapping cardNumber(String cardNumber) { + this.cardNumber = cardNumber; + return this; + } + + /** + * Name of the column that stores the card number. + * @return cardNumber + */ + @javax.annotation.Nullable + public String getCardNumber() { + return cardNumber; + } + + public void setCardNumber(String cardNumber) { + this.cardNumber = cardNumber; + } + + + public V1VaultFieldMapping cardLastFourDigits(String cardLastFourDigits) { + this.cardLastFourDigits = cardLastFourDigits; + return this; + } + + /** + * Name of the column that stores the card number suffix. + * @return cardLastFourDigits + */ + @javax.annotation.Nullable + public String getCardLastFourDigits() { + return cardLastFourDigits; + } + + public void setCardLastFourDigits(String cardLastFourDigits) { + this.cardLastFourDigits = cardLastFourDigits; + } + + + public V1VaultFieldMapping cardExpiry(String cardExpiry) { + this.cardExpiry = cardExpiry; + return this; + } + + /** + * Name of the column that stores the expiry date. + * @return cardExpiry + */ + @javax.annotation.Nullable + public String getCardExpiry() { + return cardExpiry; + } + + public void setCardExpiry(String cardExpiry) { + this.cardExpiry = cardExpiry; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1VaultFieldMapping v1VaultFieldMapping = (V1VaultFieldMapping) o; + return Objects.equals(this.cardNumber, v1VaultFieldMapping.cardNumber) && + Objects.equals(this.cardLastFourDigits, v1VaultFieldMapping.cardLastFourDigits) && + Objects.equals(this.cardExpiry, v1VaultFieldMapping.cardExpiry); + } + + @Override + public int hashCode() { + return Objects.hash(cardNumber, cardLastFourDigits, cardExpiry); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1VaultFieldMapping {\n"); + sb.append(" cardNumber: ").append(toIndentedString(cardNumber)).append("\n"); + sb.append(" cardLastFourDigits: ").append(toIndentedString(cardLastFourDigits)).append("\n"); + sb.append(" cardExpiry: ").append(toIndentedString(cardExpiry)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("card_number"); + openapiFields.add("card_last_four_digits"); + openapiFields.add("card_expiry"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1VaultFieldMapping + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1VaultFieldMapping.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1VaultFieldMapping is not found in the empty JSON string", V1VaultFieldMapping.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1VaultFieldMapping.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1VaultFieldMapping` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("card_number") != null && !jsonObj.get("card_number").isJsonNull()) && !jsonObj.get("card_number").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `card_number` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_number").toString())); + } + if ((jsonObj.get("card_last_four_digits") != null && !jsonObj.get("card_last_four_digits").isJsonNull()) && !jsonObj.get("card_last_four_digits").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `card_last_four_digits` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_last_four_digits").toString())); + } + if ((jsonObj.get("card_expiry") != null && !jsonObj.get("card_expiry").isJsonNull()) && !jsonObj.get("card_expiry").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `card_expiry` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_expiry").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1VaultFieldMapping.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1VaultFieldMapping' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1VaultFieldMapping.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1VaultFieldMapping value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1VaultFieldMapping read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1VaultFieldMapping given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1VaultFieldMapping + * @throws IOException if the JSON string is invalid with respect to V1VaultFieldMapping + */ + public static V1VaultFieldMapping fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1VaultFieldMapping.class); + } + + /** + * Convert an instance of V1VaultFieldMapping to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java b/v2/src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java new file mode 100644 index 00000000..58ac97ef --- /dev/null +++ b/v2/src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java @@ -0,0 +1,265 @@ +/* + * Skyflow Data API + * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
+ * + * The version of the OpenAPI document: v1 + * Contact: support@skyflow.com + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package com.skyflow.generated.rest.models; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.skyflow.generated.rest.models.V1VaultFieldMapping; +import java.io.IOException; +import java.util.Arrays; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.skyflow.generated.rest.JSON; + +/** + * Details of the vault that stores additional card details. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") +public class V1VaultSchemaConfig { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + private String id; + + public static final String SERIALIZED_NAME_TABLE_NAME = "table_name"; + @SerializedName(SERIALIZED_NAME_TABLE_NAME) + private String tableName; + + public static final String SERIALIZED_NAME_MAPPING = "mapping"; + @SerializedName(SERIALIZED_NAME_MAPPING) + private V1VaultFieldMapping mapping; + + public V1VaultSchemaConfig() { + } + + public V1VaultSchemaConfig id(String id) { + this.id = id; + return this; + } + + /** + * ID of the vault that stores card details. + * @return id + */ + @javax.annotation.Nullable + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + + public V1VaultSchemaConfig tableName(String tableName) { + this.tableName = tableName; + return this; + } + + /** + * Name of the table that stores card details. + * @return tableName + */ + @javax.annotation.Nullable + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + + public V1VaultSchemaConfig mapping(V1VaultFieldMapping mapping) { + this.mapping = mapping; + return this; + } + + /** + * Get mapping + * @return mapping + */ + @javax.annotation.Nullable + public V1VaultFieldMapping getMapping() { + return mapping; + } + + public void setMapping(V1VaultFieldMapping mapping) { + this.mapping = mapping; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + V1VaultSchemaConfig v1VaultSchemaConfig = (V1VaultSchemaConfig) o; + return Objects.equals(this.id, v1VaultSchemaConfig.id) && + Objects.equals(this.tableName, v1VaultSchemaConfig.tableName) && + Objects.equals(this.mapping, v1VaultSchemaConfig.mapping); + } + + @Override + public int hashCode() { + return Objects.hash(id, tableName, mapping); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class V1VaultSchemaConfig {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" tableName: ").append(toIndentedString(tableName)).append("\n"); + sb.append(" mapping: ").append(toIndentedString(mapping)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("id"); + openapiFields.add("table_name"); + openapiFields.add("mapping"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to V1VaultSchemaConfig + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!V1VaultSchemaConfig.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in V1VaultSchemaConfig is not found in the empty JSON string", V1VaultSchemaConfig.openapiRequiredFields.toString())); + } + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!V1VaultSchemaConfig.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1VaultSchemaConfig` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("id") != null && !jsonObj.get("id").isJsonNull()) && !jsonObj.get("id").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("id").toString())); + } + if ((jsonObj.get("table_name") != null && !jsonObj.get("table_name").isJsonNull()) && !jsonObj.get("table_name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `table_name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("table_name").toString())); + } + // validate the optional field `mapping` + if (jsonObj.get("mapping") != null && !jsonObj.get("mapping").isJsonNull()) { + V1VaultFieldMapping.validateJsonElement(jsonObj.get("mapping")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!V1VaultSchemaConfig.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'V1VaultSchemaConfig' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(V1VaultSchemaConfig.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, V1VaultSchemaConfig value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public V1VaultSchemaConfig read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of V1VaultSchemaConfig given an JSON string + * + * @param jsonString JSON string + * @return An instance of V1VaultSchemaConfig + * @throws IOException if the JSON string is invalid with respect to V1VaultSchemaConfig + */ + public static V1VaultSchemaConfig fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, V1VaultSchemaConfig.class); + } + + /** + * Convert an instance of V1VaultSchemaConfig to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + From 54cf3694d1d7fe26fb51226fcb93d8cd50b8779d Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 8 Oct 2024 10:51:47 +0530 Subject: [PATCH 014/126] SK-1664 Public interfaces for vault APIs - SK-1703 Implemented public interfaces for detokenize --- v2/src/main/java/com/skyflow/VaultClient.java | 15 ++++ .../java/com/skyflow/utils/Constants.java | 2 +- v2/src/main/java/com/skyflow/utils/Utils.java | 15 +--- .../utils/validations/Validations.java | 28 +++++++- .../vault/controller/VaultController.java | 13 ++-- .../tokens/DetokenizeRecordResponse.java | 54 +++++++++++++++ .../vault/tokens/DetokenizeRequest.java | 14 ---- .../vault/tokens/DetokenizeResponse.java | 69 ++++++++----------- 8 files changed, 136 insertions(+), 74 deletions(-) create mode 100644 v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/v2/src/main/java/com/skyflow/VaultClient.java index 75eda5af..87d64091 100644 --- a/v2/src/main/java/com/skyflow/VaultClient.java +++ b/v2/src/main/java/com/skyflow/VaultClient.java @@ -5,7 +5,10 @@ import com.skyflow.generated.rest.ApiClient; import com.skyflow.generated.rest.api.RecordsApi; import com.skyflow.generated.rest.api.TokensApi; +import com.skyflow.generated.rest.models.V1DetokenizePayload; +import com.skyflow.generated.rest.models.V1DetokenizeRecordRequest; import com.skyflow.utils.Utils; +import com.skyflow.vault.tokens.DetokenizeRequest; import io.github.cdimascio.dotenv.Dotenv; public class VaultClient { @@ -57,6 +60,18 @@ protected void updateVaultConfig() { prioritiseCredentials(); } + protected V1DetokenizePayload getDetokenizePayload(DetokenizeRequest request) { + V1DetokenizePayload payload = new V1DetokenizePayload(); + payload.setContinueOnError(request.getContinueOnError()); + for (String token : request.getTokens()) { + V1DetokenizeRecordRequest recordRequest = new V1DetokenizeRecordRequest(); + recordRequest.setToken(token); + recordRequest.setRedaction(request.getRedactionType().getRedaction()); + payload.addDetokenizationParametersItem(recordRequest); + } + return payload; + } + private void updateVaultURL() { String vaultURL = Utils.getVaultURL(this.vaultConfig.getClusterId(), this.vaultConfig.getEnv()); this.apiClient.setBasePath(vaultURL); diff --git a/v2/src/main/java/com/skyflow/utils/Constants.java b/v2/src/main/java/com/skyflow/utils/Constants.java index 8aacabe2..563b5ca5 100644 --- a/v2/src/main/java/com/skyflow/utils/Constants.java +++ b/v2/src/main/java/com/skyflow/utils/Constants.java @@ -1,6 +1,6 @@ package com.skyflow.utils; -public class Constants { +public final class Constants { public static final String SECURE_PROTOCOL = "https://"; public static final String DEV_DOMAIN = ".vault.skyflowapis.dev"; public static final String STAGE_DOMAIN = ".vault.skyflowapis.tech"; diff --git a/v2/src/main/java/com/skyflow/utils/Utils.java b/v2/src/main/java/com/skyflow/utils/Utils.java index c3ddf355..740e78e1 100644 --- a/v2/src/main/java/com/skyflow/utils/Utils.java +++ b/v2/src/main/java/com/skyflow/utils/Utils.java @@ -15,7 +15,7 @@ import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; -public class Utils { +public final class Utils { public static String getVaultURL(String clusterId, ENV env) { StringBuilder sb = new StringBuilder(Constants.SECURE_PROTOCOL); sb.append(clusterId); @@ -80,18 +80,7 @@ public static String getBaseURL(String url) throws MalformedURLException { URL parsedUrl = new URL(url); String protocol = parsedUrl.getProtocol(); String host = parsedUrl.getHost(); - return new StringBuilder(protocol).append("://").append(host).toString(); - } - - public static void verifyCredentials(Credentials credentials) throws SkyflowException { - int nonNullMembers = 0; - if (credentials.getPath() != null) nonNullMembers++; - if (credentials.getCredentialsString() != null) nonNullMembers++; - if (credentials.getToken() != null) nonNullMembers++; - - if (nonNullMembers != 1) { - throw new SkyflowException("only one of tokens, path, and credentialsString is allowed"); - } + return String.format("%s://%s", protocol, host); } private static PrivateKey parsePkcs8PrivateKey(byte[] pkcs8Bytes) throws SkyflowException { diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index 600aeb10..1d2468a7 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -1,10 +1,34 @@ package com.skyflow.utils.validations; +import com.skyflow.config.ConnectionConfig; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.DetokenizeRequest; + // Add config and request validations public class Validations { - public static void vaultValidations() { + + public static void validateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { + + } + + public static void validateConnectionConfig(ConnectionConfig connectionConfig) throws SkyflowException { + } - public static void insertValidation() { + public static void validateCredentials(Credentials credentials) throws SkyflowException { + int nonNullMembers = 0; + if (credentials.getPath() != null) nonNullMembers++; + if (credentials.getCredentialsString() != null) nonNullMembers++; + if (credentials.getToken() != null) nonNullMembers++; + + if (nonNullMembers != 1) { + throw new SkyflowException("only one of tokens, path, and credentialsString is allowed"); + } + } + + public static void validateDetokenizeRequest(DetokenizeRequest detokenizeRequest) throws SkyflowException { + } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index 704ab54b..538d2863 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -4,11 +4,13 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.ApiException; import com.skyflow.generated.rest.auth.HttpBearerAuth; import com.skyflow.generated.rest.models.V1DetokenizePayload; import com.skyflow.generated.rest.models.V1DetokenizeResponse; import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Utils; +import com.skyflow.utils.validations.Validations; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.InsertResponse; import com.skyflow.vault.tokens.DetokenizeRequest; @@ -32,14 +34,15 @@ public InsertResponse insert(InsertRequest insertRequest) { return null; } - public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) { + public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws SkyflowException { V1DetokenizeResponse result = null; try { + Validations.validateDetokenizeRequest(detokenizeRequest); setBearerToken(); - V1DetokenizePayload payload = detokenizeRequest.getDetokenizePayload(); + V1DetokenizePayload payload = super.getDetokenizePayload(detokenizeRequest); result = super.getTokensApi().recordServiceDetokenize(super.getVaultConfig().getVaultId(), payload); - } catch (Exception e) { - e.printStackTrace(); + } catch (ApiException e) { + throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } return new DetokenizeResponse(result); } @@ -90,7 +93,7 @@ public DetectController detect() { } private void setBearerToken() throws SkyflowException { - Utils.verifyCredentials(super.getFinalCredentials()); + Validations.validateCredentials(super.getFinalCredentials()); if (token == null || Token.isExpired(token)) { token = Utils.generateBearerToken(super.getFinalCredentials()); } diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java new file mode 100644 index 00000000..a2cbce51 --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java @@ -0,0 +1,54 @@ +package com.skyflow.vault.tokens; + +public class DetokenizeRecordResponse { + private String token; + private String value; + private String type; + private String error; + + public String getError() { + return error; + } + + void setError(String error) { + this.error = error; + } + + public String getToken() { + return token; + } + + void setToken(String token) { + this.token = token; + } + + public String getValue() { + return value; + } + + void setValue(String value) { + this.value = value; + } + + public String getType() { + return type; + } + + void setType(String type) { + this.type = type; + } + + @Override + public String toString() { + StringBuilder response = new StringBuilder("{"); + response.append("\n\t").append("\"token\": \"").append(token).append("\","); + if (error == null) { + response.append("\n\t").append("\"value\": \"").append(value).append("\","); + response.append("\n\t").append("\"type\": \"").append(type).append("\","); + } else { + response.append("\n\t").append("\"error\": \"").append(error).append("\","); + } + response.append("\n}"); + return response.toString(); + } +} \ No newline at end of file diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java index d01cf76f..24dd4e2d 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java @@ -1,8 +1,6 @@ package com.skyflow.vault.tokens; import com.skyflow.enums.RedactionType; -import com.skyflow.generated.rest.models.V1DetokenizePayload; -import com.skyflow.generated.rest.models.V1DetokenizeRecordRequest; import java.util.ArrayList; @@ -29,18 +27,6 @@ public Boolean getContinueOnError() { return this.builder.continueOnError; } - public V1DetokenizePayload getDetokenizePayload() { - V1DetokenizePayload payload = new V1DetokenizePayload(); - payload.setContinueOnError(this.getContinueOnError()); - for (String token : this.getTokens()) { - V1DetokenizeRecordRequest recordRequest = new V1DetokenizeRecordRequest(); - recordRequest.setToken(token); - recordRequest.setRedaction(this.getRedactionType().getRedaction()); - payload.addDetokenizationParametersItem(recordRequest); - } - return payload; - } - public static final class DetokenizeRequestBuilder { private ArrayList tokens; private RedactionType redactionType; diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java index 3ec5eeee..82dd417b 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java @@ -8,65 +8,56 @@ public class DetokenizeResponse { private final V1DetokenizeResponse generatedResponse; - private final ArrayList records; + private final ArrayList detokenizedFields; + private final ArrayList errorRecords; public DetokenizeResponse(V1DetokenizeResponse response) { this.generatedResponse = response; - this.records = new ArrayList<>(); + this.detokenizedFields = new ArrayList<>(); + this.errorRecords = new ArrayList<>(); this.createResponse(); } - public ArrayList getRecords() { - return records; + public ArrayList getDetokenizedFields() { + return detokenizedFields; + } + + public ArrayList getErrors() { + return errorRecords; } private void createResponse() { List records = this.generatedResponse.getRecords(); + if (records != null) { + createSuccessResponse(records); + } + } + + private void createSuccessResponse(List records) { for (V1DetokenizeRecordResponse record : records) { DetokenizeRecordResponse recordResponse = new DetokenizeRecordResponse(); - recordResponse.setValue(record.getValue()); - recordResponse.setType(record.getValueType().getValue()); - this.records.add(recordResponse); + recordResponse.setToken(record.getToken()); + if (record.getError() != null) { + recordResponse.setError(record.getError()); + this.errorRecords.add(recordResponse); + } else { + recordResponse.setValue(record.getValue()); + recordResponse.setType(record.getValueType().getValue()); + this.detokenizedFields.add(recordResponse); + } } } @Override public String toString() { - return "DetokenizeResponse {" + - "\n\t" + toIndentedString(records) + - "\n}"; + StringBuilder response = new StringBuilder("{"); + response.append("\n\t").append("\"detokenizedFields\": ").append(toIndentedString(detokenizedFields)).append("\""); + response.append("\n\t").append("\"errors\": \"").append(toIndentedString(errorRecords)).append("\""); + response.append("\n}"); + return response.toString(); } private String toIndentedString(Object o) { return o.toString().replace("\n", "\n\t"); } - - public class DetokenizeRecordResponse { - private String value; - private String type; - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - @Override - public String toString() { - return "DetokenizeRecordResponse {" + - "\n\t" + "value: '" + value + "'," + - "\n\t" + "type: '" + type + "'," + - "\n}"; - } - } } From c5117740f17143cef02476bd0ef5397bf69e8095 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 8 Oct 2024 20:25:07 +0530 Subject: [PATCH 015/126] SK-1701 Implemented public interfaces for insert vault API --- v2/src/main/java/com/skyflow/VaultClient.java | 27 ++++++ v2/src/main/java/com/skyflow/enums/Byot.java | 24 +++++ .../com/skyflow/errors/SkyflowException.java | 91 ++++++++++++++++++- .../utils/validations/Validations.java | 5 + .../vault/controller/VaultController.java | 16 +++- .../com/skyflow/vault/data/InsertRequest.java | 30 ++++-- .../skyflow/vault/data/InsertResponse.java | 89 +++++++++++++++++- .../vault/tokens/DetokenizeResponse.java | 4 +- 8 files changed, 268 insertions(+), 18 deletions(-) create mode 100644 v2/src/main/java/com/skyflow/enums/Byot.java diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/v2/src/main/java/com/skyflow/VaultClient.java index 87d64091..d6b2018e 100644 --- a/v2/src/main/java/com/skyflow/VaultClient.java +++ b/v2/src/main/java/com/skyflow/VaultClient.java @@ -5,12 +5,19 @@ import com.skyflow.generated.rest.ApiClient; import com.skyflow.generated.rest.api.RecordsApi; import com.skyflow.generated.rest.api.TokensApi; +import com.skyflow.generated.rest.models.RecordServiceInsertRecordBody; import com.skyflow.generated.rest.models.V1DetokenizePayload; import com.skyflow.generated.rest.models.V1DetokenizeRecordRequest; +import com.skyflow.generated.rest.models.V1FieldRecords; import com.skyflow.utils.Utils; +import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.tokens.DetokenizeRequest; import io.github.cdimascio.dotenv.Dotenv; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + public class VaultClient { private final RecordsApi recordsApi; private final TokensApi tokensApi; @@ -72,6 +79,26 @@ protected V1DetokenizePayload getDetokenizePayload(DetokenizeRequest request) { return payload; } + protected RecordServiceInsertRecordBody getInsertRequestBody(InsertRequest request) { + RecordServiceInsertRecordBody insertRecordBody = new RecordServiceInsertRecordBody(); + insertRecordBody.setTokenization(request.getReturnTokens()); + insertRecordBody.setHomogeneous(request.getHomogeneous()); + insertRecordBody.setUpsert(request.getUpsert()); + insertRecordBody.setByot(request.getTokenStrict().getBYOT()); + + List> values = request.getValues(); + List> tokens = request.getTokens(); + List records = new ArrayList<>(); + for (int index = 0; index < values.size(); index++) { + V1FieldRecords record = new V1FieldRecords(); + record.setFields(values.get(index)); + record.setTokens(tokens.get(index)); + records.add(record); + } + insertRecordBody.setRecords(records); + return insertRecordBody; + } + private void updateVaultURL() { String vaultURL = Utils.getVaultURL(this.vaultConfig.getClusterId(), this.vaultConfig.getEnv()); this.apiClient.setBasePath(vaultURL); diff --git a/v2/src/main/java/com/skyflow/enums/Byot.java b/v2/src/main/java/com/skyflow/enums/Byot.java new file mode 100644 index 00000000..9fe7d989 --- /dev/null +++ b/v2/src/main/java/com/skyflow/enums/Byot.java @@ -0,0 +1,24 @@ +package com.skyflow.enums; + +import com.skyflow.generated.rest.models.V1BYOT; + +public enum Byot { + DISABLE(V1BYOT.DISABLE), + ENABLE(V1BYOT.ENABLE), + ENABLE_STRICT(V1BYOT.ENABLE_STRICT); + + private final V1BYOT byot; + + Byot(V1BYOT byot) { + this.byot = byot; + } + + public V1BYOT getBYOT() { + return byot; + } + + @Override + public String toString() { + return String.valueOf(byot); + } +} diff --git a/v2/src/main/java/com/skyflow/errors/SkyflowException.java b/v2/src/main/java/com/skyflow/errors/SkyflowException.java index 7cf96536..52b4d8ef 100644 --- a/v2/src/main/java/com/skyflow/errors/SkyflowException.java +++ b/v2/src/main/java/com/skyflow/errors/SkyflowException.java @@ -1,11 +1,98 @@ package com.skyflow.errors; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.util.List; +import java.util.Map; + public class SkyflowException extends Exception { - // members + private String requestId; + private int code; + private String message; + private JSONArray details; + private JSONObject responseBody; + + public SkyflowException() { + } public SkyflowException(String message) { super(message); + this.message = message; + } + + public SkyflowException(Throwable cause) { + super(cause); + } + + public SkyflowException(String message, Throwable cause) { + super(message, cause); + } + + public SkyflowException(int code, String message) { + super(message); + this.code = code; + } + + public SkyflowException(int code, Throwable cause, Map> responseHeaders, String responseBody) { + this(cause); + this.code = code; + setRequestId(responseHeaders); + setResponseBody(responseBody); + } + + private void setResponseBody(String responseBody) { + try { + if (responseBody != null) { + JSONParser parser = new JSONParser(); + this.responseBody = (JSONObject) parser.parse(responseBody); + setMessage(); + setDetails(); + } + } catch (ParseException e) { + throw new RuntimeException(e); + } } - // getters and setters + public String getRequestId() { + return requestId; + } + + private void setRequestId(Map> responseHeaders) { + if (responseHeaders != null) { + List ids = responseHeaders.get("x-request-id"); + this.requestId = ids.get(0); + } + } + + private void setMessage() { + this.message = (String) (((JSONObject) responseBody.get("error")).get("message")); + } + + private void setDetails() { + this.details = (JSONArray) (((JSONObject) responseBody.get("error")).get("details")); + } + + public int getCode() { + return code; + } + + @Override + public String getMessage() { + return message; + } + + @Override + public String toString() { + return String.format( + "%n requestId: %s%n code: %s%n message: %s%n details: %s", + this.requestId, this.code, this.message, this.details + ); + } + + public JSONArray getDetails() { + return details; + } } diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index 1d2468a7..7f17798c 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -4,6 +4,7 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.tokens.DetokenizeRequest; // Add config and request validations @@ -31,4 +32,8 @@ public static void validateCredentials(Credentials credentials) throws SkyflowEx public static void validateDetokenizeRequest(DetokenizeRequest detokenizeRequest) throws SkyflowException { } + + public static void validateInsertRequest(InsertRequest insertRequest) throws SkyflowException { + + } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index 538d2863..80f25082 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -6,8 +6,10 @@ import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.ApiException; import com.skyflow.generated.rest.auth.HttpBearerAuth; +import com.skyflow.generated.rest.models.RecordServiceInsertRecordBody; import com.skyflow.generated.rest.models.V1DetokenizePayload; import com.skyflow.generated.rest.models.V1DetokenizeResponse; +import com.skyflow.generated.rest.models.V1InsertRecordResponse; import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; @@ -30,8 +32,18 @@ public VaultController(VaultConfig vaultConfig, Credentials credentials) { this.detectController = null; } - public InsertResponse insert(InsertRequest insertRequest) { - return null; + public InsertResponse insert(InsertRequest insertRequest) throws SkyflowException { + V1InsertRecordResponse result = null; + try { + Validations.validateInsertRequest(insertRequest); + setBearerToken(); + RecordServiceInsertRecordBody insertBody = super.getInsertRequestBody(insertRequest); + result = super.getRecordsApi().recordServiceInsertRecord( + super.getVaultConfig().getVaultId(), insertRequest.getTable(), insertBody); + } catch (ApiException e) { + throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + } + return new InsertResponse(result); } public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws SkyflowException { diff --git a/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java b/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java index 3cc4bbff..fd95d23e 100644 --- a/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java @@ -7,7 +7,8 @@ public class InsertRequest { private final String table; - private final ArrayList> data; + private final ArrayList> values; + private final ArrayList> tokens; private final Boolean returnTokens; private final String upsert; private final Boolean homogeneous; @@ -16,7 +17,8 @@ public class InsertRequest { private InsertRequest(InsertRequestBuilder builder) { this.table = builder.table; - this.data = builder.data; + this.values = builder.values; + this.tokens = builder.tokens; this.returnTokens = builder.returnTokens; this.upsert = builder.upsert; this.homogeneous = builder.homogeneous; @@ -32,8 +34,12 @@ public String getTable() { return table; } - public ArrayList> getData() { - return this.data; + public ArrayList> getValues() { + return this.values; + } + + public ArrayList> getTokens() { + return this.tokens; } public Boolean getReturnTokens() { @@ -58,20 +64,26 @@ public Byot getTokenStrict() { public static final class InsertRequestBuilder { private String table; - private ArrayList> data; - private Boolean returnTokens; + private ArrayList> values; + private ArrayList> tokens; + private Boolean returnTokens = true; private String upsert; private Boolean homogeneous; private Boolean tokenMode; - private Byot tokenStrict; + private Byot tokenStrict = Byot.DISABLE; public InsertRequestBuilder table(String table) { this.table = table; return this; } - public InsertRequestBuilder data(ArrayList> data) { - this.data = data; + public InsertRequestBuilder values(ArrayList> values) { + this.values = values; + return this; + } + + public InsertRequestBuilder tokens(ArrayList> tokens) { + this.tokens = tokens; return this; } diff --git a/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java b/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java index 444418dd..6f9ef81b 100644 --- a/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java +++ b/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java @@ -1,10 +1,93 @@ package com.skyflow.vault.data; +import com.google.gson.internal.LinkedTreeMap; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.models.V1InsertRecordResponse; +import com.skyflow.generated.rest.models.V1RecordMetaProperties; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + public class InsertResponse { - // members + private final V1InsertRecordResponse generatedResponse; + private final ArrayList> insertedFields; + private final ArrayList> errorFields; - public InsertResponse() { + public InsertResponse(V1InsertRecordResponse response) throws SkyflowException { + this.generatedResponse = response; + this.insertedFields = new ArrayList<>(); + this.errorFields = new ArrayList<>(); + this.createResponse(); } - // getters ans setters + public ArrayList> getInsertedFields() { + return insertedFields; + } + + public ArrayList> getErrorFields() { + return errorFields; + } + + private void createResponse() throws SkyflowException { + List records = this.generatedResponse.getRecords(); + if (records != null && !records.isEmpty()) { + createSuccessResponse(records); + } + } + + private void createSuccessResponse(List records) throws SkyflowException { + try { + for (V1RecordMetaProperties record : records) { + HashMap insertRecord = new HashMap<>(); + + String skyflowId = record.getSkyflowId(); + insertRecord.put("skyflowId", skyflowId); + + /* + Getting unchecked cast warning, however, this type is inferred + from an exception trying to cast into another type. Therefore, + this type cast will not fail. + */ + LinkedTreeMap tokensMap = (LinkedTreeMap) record.getTokens(); + if (tokensMap != null) { + for (String key : tokensMap.keySet()) { + insertRecord.put(key, tokensMap.get(key)); + } + } + insertedFields.add(insertRecord); + } + } catch (Exception e) { + throw new SkyflowException(e); + } + } + + @Override + public String toString() { + StringBuilder response = new StringBuilder("{"); + response.append("\n\t\"insertedFields\": ").append(formatRecords(insertedFields)); + response.append("\n\t\"errors\": ").append(formatRecords(errorFields)); + response.append("\n}"); + return response.toString(); + } + + private String formatRecords(ArrayList> records) { + StringBuilder sb = new StringBuilder("["); + for (int index = 0; index < records.size(); index++) { + HashMap map = records.get(index); + sb.append("{"); + for (String key : map.keySet()) { + sb.append("\n\t\"").append(key).append("\": \"").append(map.get(key)).append("\","); + } + sb.append("\n}"); + if (index != records.size() - 1) { + sb.append(", "); + } + } + return toIndentedString(sb.append("]")); + } + + private String toIndentedString(Object o) { + return o.toString().replace("\n", "\n\t"); + } } diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java index 82dd417b..445b7aeb 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java @@ -51,8 +51,8 @@ private void createSuccessResponse(List records) { @Override public String toString() { StringBuilder response = new StringBuilder("{"); - response.append("\n\t").append("\"detokenizedFields\": ").append(toIndentedString(detokenizedFields)).append("\""); - response.append("\n\t").append("\"errors\": \"").append(toIndentedString(errorRecords)).append("\""); + response.append("\n\t").append("\"detokenizedFields\": ").append(toIndentedString(detokenizedFields)); + response.append("\n\t").append("\"errors\": \"").append(toIndentedString(errorRecords)); response.append("\n}"); return response.toString(); } From 96ab82c20b0a5cc21fc48c5b8811bb02fb9f3270 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 9 Oct 2024 17:13:51 +0530 Subject: [PATCH 016/126] SK-1703 Worked on feedback for Detokenize public interfaces --- .../vault/controller/VaultController.java | 29 ++++++++++++--- .../tokens/DetokenizeRecordResponse.java | 33 +++++++---------- .../vault/tokens/DetokenizeResponse.java | 35 ++----------------- 3 files changed, 40 insertions(+), 57 deletions(-) diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index 80f25082..26bb2691 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -6,18 +6,19 @@ import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.ApiException; import com.skyflow.generated.rest.auth.HttpBearerAuth; -import com.skyflow.generated.rest.models.RecordServiceInsertRecordBody; -import com.skyflow.generated.rest.models.V1DetokenizePayload; -import com.skyflow.generated.rest.models.V1DetokenizeResponse; -import com.skyflow.generated.rest.models.V1InsertRecordResponse; +import com.skyflow.generated.rest.models.*; import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.InsertResponse; +import com.skyflow.vault.tokens.DetokenizeRecordResponse; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.DetokenizeResponse; +import java.util.ArrayList; +import java.util.List; + public final class VaultController extends VaultClient { private DetectController detectController; private AuditController auditController; @@ -48,15 +49,33 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws SkyflowException { V1DetokenizeResponse result = null; + ArrayList detokenizedFields = new ArrayList<>(); + ArrayList errorRecords = new ArrayList<>(); try { Validations.validateDetokenizeRequest(detokenizeRequest); setBearerToken(); V1DetokenizePayload payload = super.getDetokenizePayload(detokenizeRequest); result = super.getTokensApi().recordServiceDetokenize(super.getVaultConfig().getVaultId(), payload); + List records = result.getRecords(); + if (records != null) { + for (V1DetokenizeRecordResponse record : records) { + DetokenizeRecordResponse recordResponse = new DetokenizeRecordResponse(record); + if (record.getError() != null) { + errorRecords.add(recordResponse); + } else { + detokenizedFields.add(recordResponse); + } + } + } } catch (ApiException e) { throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } - return new DetokenizeResponse(result); + + if (!errorRecords.isEmpty()){ + // handle partial case, throw error and send data in error + // or simply log as a partial success and return proper response + } + return new DetokenizeResponse(detokenizedFields, errorRecords); } public Object get(Object getRequest) { diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java index a2cbce51..2fb1d42f 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java @@ -1,43 +1,36 @@ package com.skyflow.vault.tokens; +import com.skyflow.generated.rest.models.V1DetokenizeRecordResponse; + public class DetokenizeRecordResponse { - private String token; - private String value; - private String type; - private String error; + private final String token; + private final String value; + private final String type; + private final String error; - public String getError() { - return error; + public DetokenizeRecordResponse(V1DetokenizeRecordResponse record) { + this.token = record.getToken(); + this.value = record.getValue(); + this.type = record.getValueType().getValue(); + this.error = record.getError(); } - void setError(String error) { - this.error = error; + public String getError() { + return error; } public String getToken() { return token; } - void setToken(String token) { - this.token = token; - } - public String getValue() { return value; } - void setValue(String value) { - this.value = value; - } - public String getType() { return type; } - void setType(String type) { - this.type = type; - } - @Override public String toString() { StringBuilder response = new StringBuilder("{"); diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java index 445b7aeb..beb51700 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java @@ -1,21 +1,14 @@ package com.skyflow.vault.tokens; -import com.skyflow.generated.rest.models.V1DetokenizeRecordResponse; -import com.skyflow.generated.rest.models.V1DetokenizeResponse; - import java.util.ArrayList; -import java.util.List; public class DetokenizeResponse { - private final V1DetokenizeResponse generatedResponse; private final ArrayList detokenizedFields; private final ArrayList errorRecords; - public DetokenizeResponse(V1DetokenizeResponse response) { - this.generatedResponse = response; - this.detokenizedFields = new ArrayList<>(); - this.errorRecords = new ArrayList<>(); - this.createResponse(); + public DetokenizeResponse(ArrayList detokenizedFields, ArrayList errorRecords) { + this.detokenizedFields = detokenizedFields; + this.errorRecords = errorRecords; } public ArrayList getDetokenizedFields() { @@ -26,28 +19,6 @@ public ArrayList getErrors() { return errorRecords; } - private void createResponse() { - List records = this.generatedResponse.getRecords(); - if (records != null) { - createSuccessResponse(records); - } - } - - private void createSuccessResponse(List records) { - for (V1DetokenizeRecordResponse record : records) { - DetokenizeRecordResponse recordResponse = new DetokenizeRecordResponse(); - recordResponse.setToken(record.getToken()); - if (record.getError() != null) { - recordResponse.setError(record.getError()); - this.errorRecords.add(recordResponse); - } else { - recordResponse.setValue(record.getValue()); - recordResponse.setType(record.getValueType().getValue()); - this.detokenizedFields.add(recordResponse); - } - } - } - @Override public String toString() { StringBuilder response = new StringBuilder("{"); From 864159ee5cffa8601fa3d265e5fd3f414092c053 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 9 Oct 2024 18:06:02 +0530 Subject: [PATCH 017/126] SK-1701 Worked on feedback for Insert public interfaces --- v2/src/main/java/com/skyflow/VaultClient.java | 13 ++- .../vault/controller/VaultController.java | 32 +++++++- .../skyflow/vault/data/InsertResponse.java | 79 ++++++++++--------- 3 files changed, 84 insertions(+), 40 deletions(-) diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/v2/src/main/java/com/skyflow/VaultClient.java index d6b2018e..76271b2c 100644 --- a/v2/src/main/java/com/skyflow/VaultClient.java +++ b/v2/src/main/java/com/skyflow/VaultClient.java @@ -3,6 +3,7 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.api.QueryApi; import com.skyflow.generated.rest.api.RecordsApi; import com.skyflow.generated.rest.api.TokensApi; import com.skyflow.generated.rest.models.RecordServiceInsertRecordBody; @@ -21,6 +22,7 @@ public class VaultClient { private final RecordsApi recordsApi; private final TokensApi tokensApi; + private final QueryApi queryApi; private final ApiClient apiClient; private final VaultConfig vaultConfig; private Credentials commonCredentials; @@ -31,8 +33,9 @@ protected VaultClient(VaultConfig vaultConfig, Credentials credentials) { this.vaultConfig = vaultConfig; this.commonCredentials = credentials; this.apiClient = new ApiClient(); - this.tokensApi = new TokensApi(this.apiClient); this.recordsApi = new RecordsApi(this.apiClient); + this.tokensApi = new TokensApi(this.apiClient); + this.queryApi = new QueryApi(this.apiClient); updateVaultURL(); prioritiseCredentials(); } @@ -49,6 +52,10 @@ protected TokensApi getTokensApi() { return tokensApi; } + protected QueryApi getQueryApi() { + return queryApi; + } + protected ApiClient getApiClient() { return apiClient; } @@ -92,7 +99,9 @@ protected RecordServiceInsertRecordBody getInsertRequestBody(InsertRequest reque for (int index = 0; index < values.size(); index++) { V1FieldRecords record = new V1FieldRecords(); record.setFields(values.get(index)); - record.setTokens(tokens.get(index)); + if (tokens != null) { + record.setTokens(tokens.get(index)); + } records.add(record); } insertRecordBody.setRecords(records); diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index 26bb2691..b494c6d2 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -1,5 +1,6 @@ package com.skyflow.vault.controller; +import com.google.gson.internal.LinkedTreeMap; import com.skyflow.VaultClient; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; @@ -17,6 +18,7 @@ import com.skyflow.vault.tokens.DetokenizeResponse; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; public final class VaultController extends VaultClient { @@ -32,19 +34,47 @@ public VaultController(VaultConfig vaultConfig, Credentials credentials) { this.binLookupController = null; this.detectController = null; } + + private static synchronized HashMap getFormattedInsertRecord(V1RecordMetaProperties record) { + HashMap insertRecord = new HashMap<>(); + String skyflowId = record.getSkyflowId(); + insertRecord.put("skyflowId", skyflowId); + + /* + Getting unchecked cast warning, however, this type is inferred + from an exception trying to cast into another type. Therefore, + this type cast will not fail. + */ + LinkedTreeMap tokensMap = (LinkedTreeMap) record.getTokens(); + if (tokensMap != null) { + for (String key : tokensMap.keySet()) { + insertRecord.put(key, tokensMap.get(key)); + } + } + return insertRecord; + } public InsertResponse insert(InsertRequest insertRequest) throws SkyflowException { V1InsertRecordResponse result = null; + ArrayList> insertedFields = new ArrayList<>(); + ArrayList> errorFields = new ArrayList<>(); try { Validations.validateInsertRequest(insertRequest); setBearerToken(); RecordServiceInsertRecordBody insertBody = super.getInsertRequestBody(insertRequest); result = super.getRecordsApi().recordServiceInsertRecord( super.getVaultConfig().getVaultId(), insertRequest.getTable(), insertBody); + List records = result.getRecords(); + if (records != null) { + for (V1RecordMetaProperties record : records) { + HashMap insertRecord = getFormattedInsertRecord(record); + insertedFields.add(insertRecord); + } + } } catch (ApiException e) { throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } - return new InsertResponse(result); + return new InsertResponse(insertedFields, errorFields); } public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws SkyflowException { diff --git a/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java b/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java index 6f9ef81b..908ca8a1 100644 --- a/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java +++ b/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java @@ -10,17 +10,22 @@ import java.util.List; public class InsertResponse { - private final V1InsertRecordResponse generatedResponse; +// private final V1InsertRecordResponse generatedResponse; private final ArrayList> insertedFields; private final ArrayList> errorFields; - public InsertResponse(V1InsertRecordResponse response) throws SkyflowException { - this.generatedResponse = response; - this.insertedFields = new ArrayList<>(); - this.errorFields = new ArrayList<>(); - this.createResponse(); + public InsertResponse(ArrayList> insertedFields, ArrayList> errorFields) { + this.insertedFields = insertedFields; + this.errorFields = errorFields; } +// public InsertResponse(V1InsertRecordResponse response) throws SkyflowException { +// this.generatedResponse = response; +// this.insertedFields = new ArrayList<>(); +// this.errorFields = new ArrayList<>(); +// this.createResponse(); +// } + public ArrayList> getInsertedFields() { return insertedFields; } @@ -29,38 +34,38 @@ public ArrayList> getErrorFields() { return errorFields; } - private void createResponse() throws SkyflowException { - List records = this.generatedResponse.getRecords(); - if (records != null && !records.isEmpty()) { - createSuccessResponse(records); - } - } - - private void createSuccessResponse(List records) throws SkyflowException { - try { - for (V1RecordMetaProperties record : records) { - HashMap insertRecord = new HashMap<>(); +// private void createResponse() throws SkyflowException { +// List records = this.generatedResponse.getRecords(); +// if (records != null && !records.isEmpty()) { +// createSuccessResponse(records); +// } +// } - String skyflowId = record.getSkyflowId(); - insertRecord.put("skyflowId", skyflowId); - - /* - Getting unchecked cast warning, however, this type is inferred - from an exception trying to cast into another type. Therefore, - this type cast will not fail. - */ - LinkedTreeMap tokensMap = (LinkedTreeMap) record.getTokens(); - if (tokensMap != null) { - for (String key : tokensMap.keySet()) { - insertRecord.put(key, tokensMap.get(key)); - } - } - insertedFields.add(insertRecord); - } - } catch (Exception e) { - throw new SkyflowException(e); - } - } +// private void createSuccessResponse(List records) throws SkyflowException { +// try { +// for (V1RecordMetaProperties record : records) { +// HashMap insertRecord = new HashMap<>(); +// +// String skyflowId = record.getSkyflowId(); +// insertRecord.put("skyflowId", skyflowId); +// +// /* +// Getting unchecked cast warning, however, this type is inferred +// from an exception trying to cast into another type. Therefore, +// this type cast will not fail. +// */ +// LinkedTreeMap tokensMap = (LinkedTreeMap) record.getTokens(); +// if (tokensMap != null) { +// for (String key : tokensMap.keySet()) { +// insertRecord.put(key, tokensMap.get(key)); +// } +// } +// insertedFields.add(insertRecord); +// } +// } catch (Exception e) { +// throw new SkyflowException(e); +// } +// } @Override public String toString() { From 4aabe84b0e6f56934e87a8d6127c7e34143960da Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 9 Oct 2024 20:45:45 +0530 Subject: [PATCH 018/126] SK-1702 Implement public interfaces for Get vault API --- .../java/com/skyflow/utils/Constants.java | 1 + .../utils/validations/Validations.java | 4 + .../vault/controller/VaultController.java | 63 ++++++- .../com/skyflow/vault/data/GetRequest.java | 156 ++++++++++++++++++ .../com/skyflow/vault/data/GetResponse.java | 51 ++++++ 5 files changed, 271 insertions(+), 4 deletions(-) create mode 100644 v2/src/main/java/com/skyflow/vault/data/GetRequest.java create mode 100644 v2/src/main/java/com/skyflow/vault/data/GetResponse.java diff --git a/v2/src/main/java/com/skyflow/utils/Constants.java b/v2/src/main/java/com/skyflow/utils/Constants.java index 563b5ca5..a88dc63b 100644 --- a/v2/src/main/java/com/skyflow/utils/Constants.java +++ b/v2/src/main/java/com/skyflow/utils/Constants.java @@ -10,4 +10,5 @@ public final class Constants { public static final String PKCS8_PRIVATE_FOOTER = "-----END PRIVATE KEY-----"; public static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; public static final String SIGNED_DATA_TOKEN_PREFIX = "signed_token_"; + public static final String ORDER_ASCENDING = "ASCENDING"; } diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index 7f17798c..02833790 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -4,6 +4,7 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.GetRequest; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.tokens.DetokenizeRequest; @@ -36,4 +37,7 @@ public static void validateDetokenizeRequest(DetokenizeRequest detokenizeRequest public static void validateInsertRequest(InsertRequest insertRequest) throws SkyflowException { } + + public static void validateGetRequest(GetRequest getRequest) throws SkyflowException { + } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index b494c6d2..1b212bf9 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -4,6 +4,7 @@ import com.skyflow.VaultClient; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; +import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.ApiException; import com.skyflow.generated.rest.auth.HttpBearerAuth; @@ -11,6 +12,8 @@ import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; +import com.skyflow.vault.data.GetRequest; +import com.skyflow.vault.data.GetResponse; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.InsertResponse; import com.skyflow.vault.tokens.DetokenizeRecordResponse; @@ -34,7 +37,7 @@ public VaultController(VaultConfig vaultConfig, Credentials credentials) { this.binLookupController = null; this.detectController = null; } - + private static synchronized HashMap getFormattedInsertRecord(V1RecordMetaProperties record) { HashMap insertRecord = new HashMap<>(); String skyflowId = record.getSkyflowId(); @@ -54,6 +57,28 @@ private static synchronized HashMap getFormattedInsertRecord(V1R return insertRecord; } + private static synchronized HashMap getFormattedGetRecord(V1FieldRecords record) { + HashMap getRecord = new HashMap<>(); + + /* + Getting unchecked cast warning, however, this type is inferred + from an exception trying to cast into another type. Therefore, + this type cast will not fail. + */ + LinkedTreeMap map = null; + if (record.getTokens() != null) { + map = (LinkedTreeMap) record.getTokens(); + } else { + map = (LinkedTreeMap) record.getFields(); + } + if (map != null) { + for (String key : map.keySet()) { + getRecord.put(key, map.get(key)); + } + } + return getRecord; + } + public InsertResponse insert(InsertRequest insertRequest) throws SkyflowException { V1InsertRecordResponse result = null; ArrayList> insertedFields = new ArrayList<>(); @@ -101,15 +126,45 @@ public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } - if (!errorRecords.isEmpty()){ + if (!errorRecords.isEmpty()) { // handle partial case, throw error and send data in error // or simply log as a partial success and return proper response } return new DetokenizeResponse(detokenizedFields, errorRecords); } - public Object get(Object getRequest) { - return null; + public GetResponse get(GetRequest getRequest) throws SkyflowException { + V1BulkGetRecordResponse result = null; + ArrayList> data = new ArrayList<>(); + ArrayList> errors = new ArrayList<>(); + try { + Validations.validateGetRequest(getRequest); + setBearerToken(); + RedactionType redactionType = getRequest.getRedactionType(); + result = super.getRecordsApi().recordServiceBulkGetRecord( + super.getVaultConfig().getVaultId(), + getRequest.getTable(), + getRequest.getIds(), + redactionType != null ? redactionType.toString() : null, + getRequest.getTokenization(), + getRequest.getFields(), + getRequest.getOffset(), + getRequest.getLimit(), + getRequest.getDownloadURL(), + getRequest.getColumnName(), + getRequest.getColumnValues(), + getRequest.getOrderBy() + ); + List records = result.getRecords(); + if (records != null) { + for (V1FieldRecords record : records) { + data.add(getFormattedGetRecord(record)); + } + } + } catch (ApiException e) { + throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + } + return new GetResponse(data, errors); } public Object update(Object updateRequest) { diff --git a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java new file mode 100644 index 00000000..c7666d40 --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java @@ -0,0 +1,156 @@ +package com.skyflow.vault.data; + +import com.skyflow.enums.RedactionType; +import com.skyflow.utils.Constants; + +import java.util.ArrayList; +import java.util.List; + +public class GetRequest { + private final String table; + private final ArrayList ids; + private final RedactionType redactionType; + private final Boolean tokenization; + private final List fields; + private final String offset; + private final String limit; + private final Boolean downloadURL; + private final String columnName; + private final ArrayList columnValues; + private final String orderBy; + + private GetRequest(GetRequestBuilder builder) { + this.table = builder.table; + this.ids = builder.ids; + this.redactionType = builder.redactionType; + this.tokenization = builder.tokenization; + this.fields = builder.fields; + this.offset = builder.offset; + this.limit = builder.limit; + this.downloadURL = builder.downloadURL; + this.columnName = builder.columnName; + this.columnValues = builder.columnValues; + this.orderBy = builder.orderBy; + } + + public static GetRequestBuilder builder() { + return new GetRequestBuilder(); + } + + public String getTable() { + return table; + } + + public ArrayList getIds() { + return ids; + } + + public RedactionType getRedactionType() { + return redactionType; + } + + public Boolean getTokenization() { + return tokenization; + } + + public List getFields() { + return fields; + } + + public String getOffset() { + return offset; + } + + public String getLimit() { + return limit; + } + + public Boolean getDownloadURL() { + return downloadURL; + } + + public String getColumnName() { + return columnName; + } + + public ArrayList getColumnValues() { + return columnValues; + } + + public String getOrderBy() { + return orderBy; + } + + public static class GetRequestBuilder { + private String table; + private ArrayList ids; + private RedactionType redactionType = RedactionType.PLAIN_TEXT; + private Boolean tokenization = false; + private List fields; + private String offset = null; + private String limit = null; + private Boolean downloadURL = true; + private String columnName; + private ArrayList columnValues; + private String orderBy = Constants.ORDER_ASCENDING; + + public GetRequestBuilder table(String table) { + this.table = table; + return this; + } + + public GetRequestBuilder ids(ArrayList ids) { + this.ids = ids; + return this; + } + + public GetRequestBuilder redactionType(RedactionType redactionType) { + this.redactionType = redactionType; + return this; + } + + public GetRequestBuilder tokenization(Boolean tokenization) { + this.tokenization = tokenization; + return this; + } + + public GetRequestBuilder fields(List fields) { + this.fields = fields; + return this; + } + + public GetRequestBuilder offset(String offset) { + this.offset = offset; + return this; + } + + public GetRequestBuilder limit(String limit) { + this.limit = limit; + return this; + } + + public GetRequestBuilder downloadURL(Boolean downloadURL) { + this.downloadURL = downloadURL; + return this; + } + + public GetRequestBuilder columnName(String columnName) { + this.columnName = columnName; + return this; + } + + public GetRequestBuilder columnValues(ArrayList columnValues) { + this.columnValues = columnValues; + return this; + } + + public GetRequestBuilder orderBy(String orderBy) { + this.orderBy = orderBy; + return this; + } + + public GetRequest build() { + return new GetRequest(this); + } + } +} diff --git a/v2/src/main/java/com/skyflow/vault/data/GetResponse.java b/v2/src/main/java/com/skyflow/vault/data/GetResponse.java new file mode 100644 index 00000000..14ad518c --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/data/GetResponse.java @@ -0,0 +1,51 @@ +package com.skyflow.vault.data; + +import java.util.ArrayList; +import java.util.HashMap; + +public class GetResponse { + private final ArrayList> data; + private final ArrayList> errors; + + public GetResponse(ArrayList> data, ArrayList> errors) { + this.data = data; + this.errors = errors; + } + + public ArrayList> getData() { + return data; + } + + public ArrayList> getErrors() { + return errors; + } + + @Override + public String toString() { + StringBuilder response = new StringBuilder("{"); + response.append("\n\t\"data\": ").append(formatRecords(data)); + response.append("\n\t\"errors\": ").append(formatRecords(errors)); + response.append("\n}"); + return response.toString(); + } + + private String formatRecords(ArrayList> records) { + StringBuilder sb = new StringBuilder("["); + for (int index = 0; index < records.size(); index++) { + HashMap map = records.get(index); + sb.append("{"); + for (String key : map.keySet()) { + sb.append("\n\t\"").append(key).append("\": \"").append(map.get(key)).append("\","); + } + sb.append("\n}"); + if (index != records.size() - 1) { + sb.append(", "); + } + } + return toIndentedString(sb.append("]")); + } + + private String toIndentedString(Object o) { + return o.toString().replace("\n", "\n\t"); + } +} From 3246b376fdb7d31ce3578693db8c14a12091e5ee Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 10 Oct 2024 19:47:33 +0530 Subject: [PATCH 019/126] SK-1678 Replaced use of JSONObject with Gson JsonObject SK-1703 Abstracted constructor for Detokenize Request Builder --- .../serviceaccount/util/BearerToken.java | 39 +++++++++---------- .../vault/tokens/DetokenizeRequest.java | 3 +- 2 files changed, 19 insertions(+), 23 deletions(-) diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java b/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java index 6d15fef1..39c7733d 100644 --- a/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java +++ b/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java @@ -1,5 +1,8 @@ package com.skyflow.serviceaccount.util; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.ApiClient; import com.skyflow.generated.rest.ApiException; @@ -10,13 +13,10 @@ import com.skyflow.utils.Utils; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; import java.io.File; +import java.io.FileNotFoundException; import java.io.FileReader; -import java.io.IOException; import java.net.MalformedURLException; import java.security.PrivateKey; import java.util.ArrayList; @@ -45,19 +45,18 @@ public static BearerTokenBuilder builder() { } private static V1GetAuthTokenResponse generateBearerTokenFromCredentials( - File credentialsPath, String context, ArrayList roles + File credentialsFile, String context, ArrayList roles ) throws SkyflowException { - JSONParser parser = new JSONParser(); try { - if (credentialsPath == null || !credentialsPath.isFile()) { - throw new SkyflowException("credentials string cannot bt empty"); + if (credentialsFile == null || !credentialsFile.isFile()) { + throw new SkyflowException("credentials file is not a valid file."); } - Object obj = parser.parse(new FileReader(String.valueOf(credentialsPath))); - JSONObject serviceAccountCredentials = (JSONObject) obj; + FileReader reader = new FileReader(String.valueOf(credentialsFile)); + JsonObject serviceAccountCredentials = JsonParser.parseReader(reader).getAsJsonObject(); return getBearerTokenFromCredentials(serviceAccountCredentials, context, roles); - } catch (ParseException e) { + } catch (JsonSyntaxException e) { throw new SkyflowException("credentials string is not in valid json string format"); - } catch (IOException e) { + } catch (FileNotFoundException e) { throw new RuntimeException(e); } } @@ -65,39 +64,37 @@ private static V1GetAuthTokenResponse generateBearerTokenFromCredentials( private static V1GetAuthTokenResponse generateBearerTokenFromCredentialString( String credentials, String context, ArrayList roles ) throws SkyflowException { - JSONParser parser = new JSONParser(); try { if (credentials == null || credentials.isEmpty()) { throw new SkyflowException("credentials string cannot bt empty"); } - Object obj = parser.parse(credentials); - JSONObject serviceAccountCredentials = (JSONObject) obj; + JsonObject serviceAccountCredentials = JsonParser.parseString(credentials).getAsJsonObject(); return getBearerTokenFromCredentials(serviceAccountCredentials, context, roles); - } catch (ParseException e) { + } catch (JsonSyntaxException e) { throw new SkyflowException("credentials string is not in valid json string format"); } } private static V1GetAuthTokenResponse getBearerTokenFromCredentials( - JSONObject credentials, String context, ArrayList roles + JsonObject credentials, String context, ArrayList roles ) throws SkyflowException { try { - String privateKey = (String) credentials.get("privateKey"); + String privateKey = credentials.get("privateKey").getAsString(); if (privateKey == null) { throw new SkyflowException("privateKey not found"); } - String clientID = (String) credentials.get("clientID"); + String clientID = credentials.get("clientID").getAsString(); if (clientID == null) { throw new SkyflowException("clientID not found"); } - String keyID = (String) credentials.get("keyID"); + String keyID = credentials.get("keyID").getAsString(); if (keyID == null) { throw new SkyflowException("keyID not found"); } - String tokenURI = (String) credentials.get("tokenURI"); + String tokenURI = credentials.get("tokenURI").getAsString(); if (tokenURI == null) { throw new SkyflowException("tokenURI not found"); } diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java index 24dd4e2d..5dac7b3a 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java @@ -32,8 +32,7 @@ public static final class DetokenizeRequestBuilder { private RedactionType redactionType; private Boolean continueOnError; - public DetokenizeRequestBuilder() { - this.tokens = new ArrayList<>(); + private DetokenizeRequestBuilder() { this.redactionType = RedactionType.PLAIN_TEXT; this.continueOnError = true; } From 382877b1cc132b784c86f6a26f2592524e085509 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 10 Oct 2024 21:33:16 +0530 Subject: [PATCH 020/126] SK-1664 Implement vault API public interfaces - SK-1701 Modified insert public interfaces - SK-1702 Modified get public interfaces - SK-1704 Implemented update public interfaces --- v2/src/main/java/com/skyflow/Skyflow.java | 4 +- v2/src/main/java/com/skyflow/VaultClient.java | 25 +++-- .../java/com/skyflow/config/VaultConfig.java | 10 +- .../com/skyflow/enums/{ENV.java => Env.java} | 2 +- .../com/skyflow/errors/SkyflowException.java | 23 +++-- v2/src/main/java/com/skyflow/utils/Utils.java | 4 +- .../utils/validations/Validations.java | 4 + .../vault/controller/VaultController.java | 72 ++++++++++---- .../com/skyflow/vault/data/GetRequest.java | 19 ++-- .../com/skyflow/vault/data/GetResponse.java | 14 +-- .../com/skyflow/vault/data/InsertRequest.java | 25 +++-- .../skyflow/vault/data/InsertResponse.java | 16 +-- .../com/skyflow/vault/data/UpdateRequest.java | 99 +++++++++++++++++++ .../skyflow/vault/data/UpdateResponse.java | 44 +++++++++ 14 files changed, 283 insertions(+), 78 deletions(-) rename v2/src/main/java/com/skyflow/enums/{ENV.java => Env.java} (80%) create mode 100644 v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java create mode 100644 v2/src/main/java/com/skyflow/vault/data/UpdateResponse.java diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/v2/src/main/java/com/skyflow/Skyflow.java index 7a0e45aa..6c08644e 100644 --- a/v2/src/main/java/com/skyflow/Skyflow.java +++ b/v2/src/main/java/com/skyflow/Skyflow.java @@ -3,7 +3,7 @@ import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.ENV; +import com.skyflow.enums.Env; import com.skyflow.enums.LogLevel; import com.skyflow.errors.SkyflowException; import com.skyflow.vault.controller.ConnectionController; @@ -199,7 +199,7 @@ private VaultConfig findAndUpdateVaultConfig(VaultConfig vaultConfig) { if (previousConfig == null) { // display error log, throw error, or both } else { - ENV env = vaultConfig.getEnv() != null ? vaultConfig.getEnv() : previousConfig.getEnv(); + Env env = vaultConfig.getEnv() != null ? vaultConfig.getEnv() : previousConfig.getEnv(); String clusterId = vaultConfig.getClusterId() != null ? vaultConfig.getClusterId() : previousConfig.getClusterId(); Credentials credentials = vaultConfig.getCredentials() != null ? vaultConfig.getCredentials() : previousConfig.getCredentials(); previousConfig.setEnv(env); diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/v2/src/main/java/com/skyflow/VaultClient.java index 76271b2c..7114b6c9 100644 --- a/v2/src/main/java/com/skyflow/VaultClient.java +++ b/v2/src/main/java/com/skyflow/VaultClient.java @@ -6,12 +6,10 @@ import com.skyflow.generated.rest.api.QueryApi; import com.skyflow.generated.rest.api.RecordsApi; import com.skyflow.generated.rest.api.TokensApi; -import com.skyflow.generated.rest.models.RecordServiceInsertRecordBody; -import com.skyflow.generated.rest.models.V1DetokenizePayload; -import com.skyflow.generated.rest.models.V1DetokenizeRecordRequest; -import com.skyflow.generated.rest.models.V1FieldRecords; +import com.skyflow.generated.rest.models.*; import com.skyflow.utils.Utils; import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.UpdateRequest; import com.skyflow.vault.tokens.DetokenizeRequest; import io.github.cdimascio.dotenv.Dotenv; @@ -93,8 +91,8 @@ protected RecordServiceInsertRecordBody getInsertRequestBody(InsertRequest reque insertRecordBody.setUpsert(request.getUpsert()); insertRecordBody.setByot(request.getTokenStrict().getBYOT()); - List> values = request.getValues(); - List> tokens = request.getTokens(); + List> values = request.getValues(); + List> tokens = request.getTokens(); List records = new ArrayList<>(); for (int index = 0; index < values.size(); index++) { V1FieldRecords record = new V1FieldRecords(); @@ -108,6 +106,21 @@ protected RecordServiceInsertRecordBody getInsertRequestBody(InsertRequest reque return insertRecordBody; } + protected RecordServiceUpdateRecordBody getUpdateRequestBody(UpdateRequest request) { + RecordServiceUpdateRecordBody updateRequestBody = new RecordServiceUpdateRecordBody(); + updateRequestBody.byot(request.getByot().getBYOT()); + updateRequestBody.setTokenization(request.getReturnTokens()); + HashMap values = request.getValues(); + HashMap tokens = request.getTokens(); + V1FieldRecords record = new V1FieldRecords(); + record.setFields(values); + if (tokens != null) { + record.setTokens(tokens); + } + updateRequestBody.setRecord(record); + return updateRequestBody; + } + private void updateVaultURL() { String vaultURL = Utils.getVaultURL(this.vaultConfig.getClusterId(), this.vaultConfig.getEnv()); this.apiClient.setBasePath(vaultURL); diff --git a/v2/src/main/java/com/skyflow/config/VaultConfig.java b/v2/src/main/java/com/skyflow/config/VaultConfig.java index 49bfa5e2..624d7d9a 100644 --- a/v2/src/main/java/com/skyflow/config/VaultConfig.java +++ b/v2/src/main/java/com/skyflow/config/VaultConfig.java @@ -1,18 +1,18 @@ package com.skyflow.config; -import com.skyflow.enums.ENV; +import com.skyflow.enums.Env; import com.skyflow.utils.Utils; public class VaultConfig { private String vaultId; private String clusterId; - private ENV env; + private Env env; private Credentials credentials; public VaultConfig() { this.vaultId = null; this.clusterId = null; - this.env = ENV.PROD; + this.env = Env.PROD; this.credentials = null; } @@ -32,11 +32,11 @@ public void setClusterId(String clusterId) { this.clusterId = clusterId; } - public ENV getEnv() { + public Env getEnv() { return env; } - public void setEnv(ENV env) { + public void setEnv(Env env) { this.env = env; } diff --git a/v2/src/main/java/com/skyflow/enums/ENV.java b/v2/src/main/java/com/skyflow/enums/Env.java similarity index 80% rename from v2/src/main/java/com/skyflow/enums/ENV.java rename to v2/src/main/java/com/skyflow/enums/Env.java index 17c3e985..3d1466e9 100644 --- a/v2/src/main/java/com/skyflow/enums/ENV.java +++ b/v2/src/main/java/com/skyflow/enums/Env.java @@ -1,6 +1,6 @@ package com.skyflow.enums; -public enum ENV { +public enum Env { DEV, STAGE, SANDBOX, diff --git a/v2/src/main/java/com/skyflow/errors/SkyflowException.java b/v2/src/main/java/com/skyflow/errors/SkyflowException.java index 52b4d8ef..20f70fb8 100644 --- a/v2/src/main/java/com/skyflow/errors/SkyflowException.java +++ b/v2/src/main/java/com/skyflow/errors/SkyflowException.java @@ -1,9 +1,9 @@ package com.skyflow.errors; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; import java.util.List; import java.util.Map; @@ -12,8 +12,8 @@ public class SkyflowException extends Exception { private String requestId; private int code; private String message; - private JSONArray details; - private JSONObject responseBody; + private JsonArray details; + private JsonObject responseBody; public SkyflowException() { } @@ -46,12 +46,11 @@ public SkyflowException(int code, Throwable cause, Map> res private void setResponseBody(String responseBody) { try { if (responseBody != null) { - JSONParser parser = new JSONParser(); - this.responseBody = (JSONObject) parser.parse(responseBody); + this.responseBody = JsonParser.parseString(responseBody).getAsJsonObject(); setMessage(); setDetails(); } - } catch (ParseException e) { + } catch (JsonSyntaxException e) { throw new RuntimeException(e); } } @@ -68,11 +67,11 @@ private void setRequestId(Map> responseHeaders) { } private void setMessage() { - this.message = (String) (((JSONObject) responseBody.get("error")).get("message")); + this.message = ((JsonObject) responseBody.get("error")).get("message").getAsString(); } private void setDetails() { - this.details = (JSONArray) (((JSONObject) responseBody.get("error")).get("details")); + this.details = ((JsonObject) responseBody.get("error")).get("details").getAsJsonArray(); } public int getCode() { @@ -92,7 +91,7 @@ public String toString() { ); } - public JSONArray getDetails() { + public JsonArray getDetails() { return details; } } diff --git a/v2/src/main/java/com/skyflow/utils/Utils.java b/v2/src/main/java/com/skyflow/utils/Utils.java index 740e78e1..51115bb0 100644 --- a/v2/src/main/java/com/skyflow/utils/Utils.java +++ b/v2/src/main/java/com/skyflow/utils/Utils.java @@ -1,7 +1,7 @@ package com.skyflow.utils; import com.skyflow.config.Credentials; -import com.skyflow.enums.ENV; +import com.skyflow.enums.Env; import com.skyflow.errors.SkyflowException; import com.skyflow.serviceaccount.util.BearerToken; import org.apache.commons.codec.binary.Base64; @@ -16,7 +16,7 @@ import java.security.spec.PKCS8EncodedKeySpec; public final class Utils { - public static String getVaultURL(String clusterId, ENV env) { + public static String getVaultURL(String clusterId, Env env) { StringBuilder sb = new StringBuilder(Constants.SECURE_PROTOCOL); sb.append(clusterId); switch (env) { diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index 02833790..665e4ec5 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -6,6 +6,7 @@ import com.skyflow.errors.SkyflowException; import com.skyflow.vault.data.GetRequest; import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.UpdateRequest; import com.skyflow.vault.tokens.DetokenizeRequest; // Add config and request validations @@ -40,4 +41,7 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky public static void validateGetRequest(GetRequest getRequest) throws SkyflowException { } + + public static void validateUpdateRequest(UpdateRequest updateRequest) throws SkyflowException { + } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index 1b212bf9..bb1711ef 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -12,10 +12,7 @@ import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; -import com.skyflow.vault.data.GetRequest; -import com.skyflow.vault.data.GetResponse; -import com.skyflow.vault.data.InsertRequest; -import com.skyflow.vault.data.InsertResponse; +import com.skyflow.vault.data.*; import com.skyflow.vault.tokens.DetokenizeRecordResponse; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.DetokenizeResponse; @@ -38,8 +35,8 @@ public VaultController(VaultConfig vaultConfig, Credentials credentials) { this.detectController = null; } - private static synchronized HashMap getFormattedInsertRecord(V1RecordMetaProperties record) { - HashMap insertRecord = new HashMap<>(); + private static synchronized HashMap getFormattedInsertRecord(V1RecordMetaProperties record) { + HashMap insertRecord = new HashMap<>(); String skyflowId = record.getSkyflowId(); insertRecord.put("skyflowId", skyflowId); @@ -48,7 +45,7 @@ private static synchronized HashMap getFormattedInsertRecord(V1R from an exception trying to cast into another type. Therefore, this type cast will not fail. */ - LinkedTreeMap tokensMap = (LinkedTreeMap) record.getTokens(); + LinkedTreeMap tokensMap = (LinkedTreeMap) record.getTokens(); if (tokensMap != null) { for (String key : tokensMap.keySet()) { insertRecord.put(key, tokensMap.get(key)); @@ -57,19 +54,19 @@ private static synchronized HashMap getFormattedInsertRecord(V1R return insertRecord; } - private static synchronized HashMap getFormattedGetRecord(V1FieldRecords record) { - HashMap getRecord = new HashMap<>(); + private static synchronized HashMap getFormattedGetRecord(V1FieldRecords record) { + HashMap getRecord = new HashMap<>(); /* Getting unchecked cast warning, however, this type is inferred from an exception trying to cast into another type. Therefore, this type cast will not fail. */ - LinkedTreeMap map = null; + LinkedTreeMap map; if (record.getTokens() != null) { - map = (LinkedTreeMap) record.getTokens(); + map = (LinkedTreeMap) record.getTokens(); } else { - map = (LinkedTreeMap) record.getFields(); + map = (LinkedTreeMap) record.getFields(); } if (map != null) { for (String key : map.keySet()) { @@ -79,10 +76,29 @@ private static synchronized HashMap getFormattedGetRecord(V1Fiel return getRecord; } + private static HashMap getFormattedUpdateRecord(V1UpdateRecordResponse record) { + HashMap updateTokens = new HashMap<>(); + /* + Getting unchecked cast warning, however, this type is inferred + from an exception trying to cast into another type. Therefore, + this type cast will not fail. + */ + LinkedTreeMap map = null; + if (record.getTokens() != null) { + map = (LinkedTreeMap) record.getTokens(); + } + if (map != null) { + for (String key : map.keySet()) { + updateTokens.put(key, map.get(key)); + } + } + return updateTokens; + } + public InsertResponse insert(InsertRequest insertRequest) throws SkyflowException { V1InsertRecordResponse result = null; - ArrayList> insertedFields = new ArrayList<>(); - ArrayList> errorFields = new ArrayList<>(); + ArrayList> insertedFields = new ArrayList<>(); + ArrayList> errorFields = new ArrayList<>(); try { Validations.validateInsertRequest(insertRequest); setBearerToken(); @@ -92,7 +108,7 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio List records = result.getRecords(); if (records != null) { for (V1RecordMetaProperties record : records) { - HashMap insertRecord = getFormattedInsertRecord(record); + HashMap insertRecord = getFormattedInsertRecord(record); insertedFields.add(insertRecord); } } @@ -135,8 +151,8 @@ public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws public GetResponse get(GetRequest getRequest) throws SkyflowException { V1BulkGetRecordResponse result = null; - ArrayList> data = new ArrayList<>(); - ArrayList> errors = new ArrayList<>(); + ArrayList> data = new ArrayList<>(); + ArrayList> errors = new ArrayList<>(); try { Validations.validateGetRequest(getRequest); setBearerToken(); @@ -167,8 +183,26 @@ public GetResponse get(GetRequest getRequest) throws SkyflowException { return new GetResponse(data, errors); } - public Object update(Object updateRequest) { - return null; + public UpdateResponse update(UpdateRequest updateRequest) throws SkyflowException { + V1UpdateRecordResponse result; + String skyflowId; + HashMap tokensMap; + try { + Validations.validateUpdateRequest(updateRequest); + setBearerToken(); + RecordServiceUpdateRecordBody updateBody = super.getUpdateRequestBody(updateRequest); + result = super.getRecordsApi().recordServiceUpdateRecord( + super.getVaultConfig().getVaultId(), + updateRequest.getTable(), + updateRequest.getId(), + updateBody + ); + skyflowId = result.getSkyflowId(); + tokensMap = getFormattedUpdateRecord(result); + } catch (ApiException e) { + throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + } + return new UpdateResponse(skyflowId, tokensMap); } public Object delete(Object deleteRequest) { diff --git a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java index c7666d40..862bfa03 100644 --- a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java @@ -84,15 +84,22 @@ public String getOrderBy() { public static class GetRequestBuilder { private String table; private ArrayList ids; - private RedactionType redactionType = RedactionType.PLAIN_TEXT; - private Boolean tokenization = false; + private RedactionType redactionType; + private Boolean tokenization; private List fields; - private String offset = null; - private String limit = null; - private Boolean downloadURL = true; + private String offset; + private String limit; + private Boolean downloadURL; private String columnName; private ArrayList columnValues; - private String orderBy = Constants.ORDER_ASCENDING; + private String orderBy; + + private GetRequestBuilder() { + this.redactionType = RedactionType.PLAIN_TEXT; + this.tokenization = false; + this.downloadURL = true; + this.orderBy = Constants.ORDER_ASCENDING; + } public GetRequestBuilder table(String table) { this.table = table; diff --git a/v2/src/main/java/com/skyflow/vault/data/GetResponse.java b/v2/src/main/java/com/skyflow/vault/data/GetResponse.java index 14ad518c..2d2a4b1d 100644 --- a/v2/src/main/java/com/skyflow/vault/data/GetResponse.java +++ b/v2/src/main/java/com/skyflow/vault/data/GetResponse.java @@ -4,19 +4,19 @@ import java.util.HashMap; public class GetResponse { - private final ArrayList> data; - private final ArrayList> errors; + private final ArrayList> data; + private final ArrayList> errors; - public GetResponse(ArrayList> data, ArrayList> errors) { + public GetResponse(ArrayList> data, ArrayList> errors) { this.data = data; this.errors = errors; } - public ArrayList> getData() { + public ArrayList> getData() { return data; } - public ArrayList> getErrors() { + public ArrayList> getErrors() { return errors; } @@ -29,10 +29,10 @@ public String toString() { return response.toString(); } - private String formatRecords(ArrayList> records) { + private String formatRecords(ArrayList> records) { StringBuilder sb = new StringBuilder("["); for (int index = 0; index < records.size(); index++) { - HashMap map = records.get(index); + HashMap map = records.get(index); sb.append("{"); for (String key : map.keySet()) { sb.append("\n\t\"").append(key).append("\": \"").append(map.get(key)).append("\","); diff --git a/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java b/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java index fd95d23e..d7df9157 100644 --- a/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java @@ -7,8 +7,8 @@ public class InsertRequest { private final String table; - private final ArrayList> values; - private final ArrayList> tokens; + private final ArrayList> values; + private final ArrayList> tokens; private final Boolean returnTokens; private final String upsert; private final Boolean homogeneous; @@ -34,11 +34,11 @@ public String getTable() { return table; } - public ArrayList> getValues() { + public ArrayList> getValues() { return this.values; } - public ArrayList> getTokens() { + public ArrayList> getTokens() { return this.tokens; } @@ -64,25 +64,30 @@ public Byot getTokenStrict() { public static final class InsertRequestBuilder { private String table; - private ArrayList> values; - private ArrayList> tokens; - private Boolean returnTokens = true; + private ArrayList> values; + private ArrayList> tokens; + private Boolean returnTokens; private String upsert; private Boolean homogeneous; private Boolean tokenMode; - private Byot tokenStrict = Byot.DISABLE; + private Byot tokenStrict; + + private InsertRequestBuilder() { + this.returnTokens = true; + this.tokenStrict = Byot.DISABLE; + } public InsertRequestBuilder table(String table) { this.table = table; return this; } - public InsertRequestBuilder values(ArrayList> values) { + public InsertRequestBuilder values(ArrayList> values) { this.values = values; return this; } - public InsertRequestBuilder tokens(ArrayList> tokens) { + public InsertRequestBuilder tokens(ArrayList> tokens) { this.tokens = tokens; return this; } diff --git a/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java b/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java index 908ca8a1..f569e409 100644 --- a/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java +++ b/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java @@ -11,10 +11,10 @@ public class InsertResponse { // private final V1InsertRecordResponse generatedResponse; - private final ArrayList> insertedFields; - private final ArrayList> errorFields; + private final ArrayList> insertedFields; + private final ArrayList> errorFields; - public InsertResponse(ArrayList> insertedFields, ArrayList> errorFields) { + public InsertResponse(ArrayList> insertedFields, ArrayList> errorFields) { this.insertedFields = insertedFields; this.errorFields = errorFields; } @@ -26,11 +26,11 @@ public InsertResponse(ArrayList> insertedFields, ArrayLi // this.createResponse(); // } - public ArrayList> getInsertedFields() { + public ArrayList> getInsertedFields() { return insertedFields; } - public ArrayList> getErrorFields() { + public ArrayList> getErrorFields() { return errorFields; } @@ -44,7 +44,7 @@ public ArrayList> getErrorFields() { // private void createSuccessResponse(List records) throws SkyflowException { // try { // for (V1RecordMetaProperties record : records) { -// HashMap insertRecord = new HashMap<>(); +// HashMap insertRecord = new HashMap<>(); // // String skyflowId = record.getSkyflowId(); // insertRecord.put("skyflowId", skyflowId); @@ -76,10 +76,10 @@ public String toString() { return response.toString(); } - private String formatRecords(ArrayList> records) { + private String formatRecords(ArrayList> records) { StringBuilder sb = new StringBuilder("["); for (int index = 0; index < records.size(); index++) { - HashMap map = records.get(index); + HashMap map = records.get(index); sb.append("{"); for (String key : map.keySet()) { sb.append("\n\t\"").append(key).append("\": \"").append(map.get(key)).append("\","); diff --git a/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java b/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java new file mode 100644 index 00000000..55d64209 --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java @@ -0,0 +1,99 @@ +package com.skyflow.vault.data; + +import com.skyflow.enums.Byot; + +import java.util.HashMap; + +public class UpdateRequest { + private final String table; + private final String id; + private final Boolean returnTokens; + private final HashMap values; + private final HashMap tokens; + private final Byot tokenStrict; + + private UpdateRequest(UpdateRequestBuilder builder) { + this.table = builder.table; + this.id = builder.id; + this.returnTokens = builder.returnTokens; + this.values = builder.values; + this.tokens = builder.tokens; + this.tokenStrict = builder.tokenStrict; + } + + public static UpdateRequestBuilder builder() { + return new UpdateRequestBuilder(); + } + + public String getTable() { + return table; + } + + public String getId() { + return id; + } + + public Boolean getReturnTokens() { + return returnTokens; + } + + public HashMap getValues() { + return values; + } + + public HashMap getTokens() { + return tokens; + } + + public Byot getByot() { + return tokenStrict; + } + + public static class UpdateRequestBuilder { + private String table; + private String id; + private Boolean returnTokens; + private HashMap values; + private HashMap tokens; + private Byot tokenStrict; + + private UpdateRequestBuilder() { + this.returnTokens = true; + this.tokenStrict = Byot.DISABLE; + } + + public UpdateRequestBuilder table(String table) { + this.table = table; + return this; + } + + public UpdateRequestBuilder id(String id) { + this.id = id; + return this; + } + + public UpdateRequestBuilder returnTokens(Boolean returnTokens) { + this.returnTokens = returnTokens; + return this; + } + + public UpdateRequestBuilder values(HashMap values) { + this.values = values; + return this; + } + + public UpdateRequestBuilder tokens(HashMap tokens) { + this.tokens = tokens; + return this; + } + + public UpdateRequestBuilder tokenStrict(Byot tokenStrict) { + this.tokenStrict = tokenStrict; + return this; + } + + public UpdateRequest build() { + return new UpdateRequest(this); + } + } +} diff --git a/v2/src/main/java/com/skyflow/vault/data/UpdateResponse.java b/v2/src/main/java/com/skyflow/vault/data/UpdateResponse.java new file mode 100644 index 00000000..05ae30bd --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/data/UpdateResponse.java @@ -0,0 +1,44 @@ +package com.skyflow.vault.data; + +import java.util.HashMap; + +public class UpdateResponse { + private String skyflowId; + private HashMap tokens; + + public UpdateResponse(String skyflowId, HashMap tokens) { + this.skyflowId = skyflowId; + this.tokens = tokens; + } + + public String getSkyflowId() { + return skyflowId; + } + + public HashMap getTokens() { + return tokens; + } + + @Override + public String toString() { + StringBuilder response = new StringBuilder("{"); + response.append("\n\t\"skyflowId\": ").append(skyflowId); + response.append("\n\t\"tokens\": ").append(formatRecords(tokens)); + response.append("\n}"); + return response.toString(); + } + + private String formatRecords(HashMap tokens) { + StringBuilder sb = new StringBuilder(); + sb.append("{"); + for (String key : tokens.keySet()) { + sb.append("\n\t\"").append(key).append("\": \"").append(tokens.get(key)).append("\","); + } + sb.append("\n}"); + return toIndentedString(sb); + } + + private String toIndentedString(Object o) { + return o.toString().replace("\n", "\n\t"); + } +} From 0ad69e425b1980b72d93a31d643287cf0ad56244 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 11 Oct 2024 16:44:43 +0530 Subject: [PATCH 021/126] SK-1707 Implement Delete API public interfaces --- .../utils/validations/Validations.java | 4 ++ .../vault/controller/VaultController.java | 20 ++++++-- .../com/skyflow/vault/data/DeleteRequest.java | 47 +++++++++++++++++++ .../skyflow/vault/data/DeleteResponse.java | 34 ++++++++++++++ 4 files changed, 102 insertions(+), 3 deletions(-) create mode 100644 v2/src/main/java/com/skyflow/vault/data/DeleteRequest.java create mode 100644 v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index 665e4ec5..5eb88b69 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -4,6 +4,7 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.DeleteRequest; import com.skyflow.vault.data.GetRequest; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.UpdateRequest; @@ -44,4 +45,7 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep public static void validateUpdateRequest(UpdateRequest updateRequest) throws SkyflowException { } + + public static void validateDeleteRequest(DeleteRequest deleteRequest) throws SkyflowException { + } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index bb1711ef..7d4168a3 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -76,7 +76,7 @@ private static synchronized HashMap getFormattedGetRecord(V1Fiel return getRecord; } - private static HashMap getFormattedUpdateRecord(V1UpdateRecordResponse record) { + private static synchronized HashMap getFormattedUpdateRecord(V1UpdateRecordResponse record) { HashMap updateTokens = new HashMap<>(); /* Getting unchecked cast warning, however, this type is inferred @@ -205,8 +205,22 @@ public UpdateResponse update(UpdateRequest updateRequest) throws SkyflowExceptio return new UpdateResponse(skyflowId, tokensMap); } - public Object delete(Object deleteRequest) { - return null; + public DeleteResponse delete(DeleteRequest deleteRequest) throws SkyflowException { + V1BulkDeleteRecordResponse result; + try { + Validations.validateDeleteRequest(deleteRequest); + setBearerToken(); + RecordServiceBulkDeleteRecordBody deleteBody = new RecordServiceBulkDeleteRecordBody(); + for (String id : deleteRequest.getIds()) { + deleteBody.addSkyflowIdsItem(id); + } + result = super.getRecordsApi().recordServiceBulkDeleteRecord( + super.getVaultConfig().getVaultId(), deleteRequest.getTable(), deleteBody); + System.out.println(result); + } catch (ApiException e) { + throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + } + return new DeleteResponse((ArrayList) result.getRecordIDResponse()); } public Object uploadFile(Object uploadFileRequest) { diff --git a/v2/src/main/java/com/skyflow/vault/data/DeleteRequest.java b/v2/src/main/java/com/skyflow/vault/data/DeleteRequest.java new file mode 100644 index 00000000..0bd11df8 --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/data/DeleteRequest.java @@ -0,0 +1,47 @@ +package com.skyflow.vault.data; + +import java.util.ArrayList; + +public class DeleteRequest { + private final String table; + private final ArrayList ids; + + private DeleteRequest(DeleteRequestBuilder builder) { + this.table = builder.table; + this.ids = builder.ids; + } + + public static DeleteRequestBuilder builder() { + return new DeleteRequestBuilder(); + } + + public String getTable() { + return table; + } + + public ArrayList getIds() { + return ids; + } + + public static class DeleteRequestBuilder { + private String table; + private ArrayList ids; + + private DeleteRequestBuilder() { + } + + public DeleteRequestBuilder table(String table) { + this.table = table; + return this; + } + + public DeleteRequestBuilder ids(ArrayList ids) { + this.ids = ids; + return this; + } + + public DeleteRequest build() { + return new DeleteRequest(this); + } + } +} diff --git a/v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java b/v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java new file mode 100644 index 00000000..975b6510 --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java @@ -0,0 +1,34 @@ +package com.skyflow.vault.data; + +import java.util.ArrayList; + +public class DeleteResponse { + private ArrayList deletedIds; + + public DeleteResponse(ArrayList deletedIds) { + this.deletedIds = deletedIds; + } + + public ArrayList getDeletedIds() { + return deletedIds; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("{"); + sb.append("\n\t\"deletedIds\": ").append(formatIds()); + return sb.append("\n}").toString(); + } + + private String formatIds() { + StringBuilder sb = new StringBuilder("["); + for (String id : deletedIds) { + sb.append("\n\t\"").append(id).append("\""); + } + return toIndentedString(sb.append("]")); + } + + private String toIndentedString(Object o) { + return o.toString().replace("\n", "\n\t"); + } +} From df0a13f262cd1b758390e060c47e6150940b1bed Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 11 Oct 2024 20:25:50 +0530 Subject: [PATCH 022/126] SK-1705 Implement Query API public interfaces --- .../utils/validations/Validations.java | 8 ++-- .../vault/controller/VaultController.java | 39 ++++++++++++++-- .../skyflow/vault/data/DeleteResponse.java | 6 +-- .../com/skyflow/vault/data/QueryRequest.java | 33 +++++++++++++ .../com/skyflow/vault/data/QueryResponse.java | 46 +++++++++++++++++++ 5 files changed, 122 insertions(+), 10 deletions(-) create mode 100644 v2/src/main/java/com/skyflow/vault/data/QueryRequest.java create mode 100644 v2/src/main/java/com/skyflow/vault/data/QueryResponse.java diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index 5eb88b69..b8d36fd8 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -4,10 +4,7 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.data.DeleteRequest; -import com.skyflow.vault.data.GetRequest; -import com.skyflow.vault.data.InsertRequest; -import com.skyflow.vault.data.UpdateRequest; +import com.skyflow.vault.data.*; import com.skyflow.vault.tokens.DetokenizeRequest; // Add config and request validations @@ -48,4 +45,7 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky public static void validateDeleteRequest(DeleteRequest deleteRequest) throws SkyflowException { } + + public static void validateQueryRequest(QueryRequest queryRequest) throws SkyflowException { + } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index 7d4168a3..aafc04fa 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -95,6 +95,25 @@ private static synchronized HashMap getFormattedUpdateRecord(V1U return updateTokens; } + private static synchronized HashMap getFormattedQueryRecord(V1FieldRecords record) { + HashMap queryRecord = new HashMap<>(); + /* + Getting unchecked cast warning, however, this type is inferred + from an exception trying to cast into another type. Therefore, + this type cast will not fail. + */ + LinkedTreeMap map = null; + if (record.getFields() != null) { + map = (LinkedTreeMap) record.getFields(); + } + if (map != null) { + for (String key : map.keySet()) { + queryRecord.put(key, map.get(key)); + } + } + return queryRecord; + } + public InsertResponse insert(InsertRequest insertRequest) throws SkyflowException { V1InsertRecordResponse result = null; ArrayList> insertedFields = new ArrayList<>(); @@ -216,7 +235,6 @@ public DeleteResponse delete(DeleteRequest deleteRequest) throws SkyflowExceptio } result = super.getRecordsApi().recordServiceBulkDeleteRecord( super.getVaultConfig().getVaultId(), deleteRequest.getTable(), deleteBody); - System.out.println(result); } catch (ApiException e) { throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } @@ -227,8 +245,23 @@ public Object uploadFile(Object uploadFileRequest) { return null; } - public Object query(Object queryRequest) { - return null; + public QueryResponse query(QueryRequest queryRequest) throws SkyflowException { + V1GetQueryResponse result; + ArrayList> fields = new ArrayList<>(); + try { + Validations.validateQueryRequest(queryRequest); + setBearerToken(); + result = super.getQueryApi().queryServiceExecuteQuery( + super.getVaultConfig().getVaultId(), new QueryServiceExecuteQueryBody().query(queryRequest.getQuery())); + if (result.getRecords() != null) { + for (V1FieldRecords record : result.getRecords()) { + fields.add(getFormattedQueryRecord(record)); + } + } + } catch (ApiException e) { + throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + } + return new QueryResponse(fields); } public Object tokenize(Object tokenizeRequest) { diff --git a/v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java b/v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java index 975b6510..0024c68a 100644 --- a/v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java +++ b/v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java @@ -15,9 +15,9 @@ public ArrayList getDeletedIds() { @Override public String toString() { - StringBuilder sb = new StringBuilder("{"); - sb.append("\n\t\"deletedIds\": ").append(formatIds()); - return sb.append("\n}").toString(); + StringBuilder response = new StringBuilder("{"); + response.append("\n\t\"deletedIds\": ").append(formatIds()); + return response.append("\n}").toString(); } private String formatIds() { diff --git a/v2/src/main/java/com/skyflow/vault/data/QueryRequest.java b/v2/src/main/java/com/skyflow/vault/data/QueryRequest.java new file mode 100644 index 00000000..58c0c54d --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/data/QueryRequest.java @@ -0,0 +1,33 @@ +package com.skyflow.vault.data; + +public class QueryRequest { + private final String query; + + private QueryRequest(QueryRequestBuilder builder) { + this.query = builder.query; + } + + public static QueryRequestBuilder builder() { + return new QueryRequestBuilder(); + } + + public String getQuery() { + return query; + } + + public static class QueryRequestBuilder { + private String query; + + private QueryRequestBuilder() { + } + + public QueryRequestBuilder query(String query) { + this.query = query; + return this; + } + + public QueryRequest build() { + return new QueryRequest(this); + } + } +} diff --git a/v2/src/main/java/com/skyflow/vault/data/QueryResponse.java b/v2/src/main/java/com/skyflow/vault/data/QueryResponse.java new file mode 100644 index 00000000..72d1e316 --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/data/QueryResponse.java @@ -0,0 +1,46 @@ +package com.skyflow.vault.data; + +import java.util.ArrayList; +import java.util.HashMap; + +public class QueryResponse { + private ArrayList> fields; + private ArrayList> tokenizedData; + + public QueryResponse(ArrayList> fields) { + this.fields = fields; + } + + public ArrayList> getFields() { + return fields; + } + + @Override + public String toString() { + StringBuilder response = new StringBuilder("{"); + response.append("\n\t\"fields\": ").append(formatFields()); + return response.append("\n}").toString(); + } + + private String formatFields() { + StringBuilder sb = new StringBuilder("["); + for (int index = 0; index < fields.size(); index++) { + HashMap map = fields.get(index); + sb.append("{"); + for (String key : map.keySet()) { + sb.append("\n\t\"").append(key).append("\": \"").append(map.get(key)).append("\","); + } + sb.append("\n\t\"tokenizedData\": ").append(tokenizedData); + sb.append("\n}"); + if (index != fields.size() - 1) { + sb.append(", "); + } + } + return toIndentedString(sb.append("]")); + } + + private String toIndentedString(Object o) { + return o.toString().replace("\n", "\n\t"); + } + +} From de7eddc93792d5cc18ec93398ac1d96d411b8c13 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 15 Oct 2024 14:06:10 +0530 Subject: [PATCH 023/126] SK-1664 implement tokenize api public interface --- v2/src/main/java/com/skyflow/VaultClient.java | 13 +++++ .../java/com/skyflow/utils/ColumnValue.java | 52 +++++++++++++++++++ .../utils/validations/Validations.java | 5 ++ .../vault/controller/VaultController.java | 27 +++++++++- .../skyflow/vault/tokens/TokenizeRequest.java | 39 ++++++++++++++ .../vault/tokens/TokenizeResponse.java | 13 +++++ 6 files changed, 147 insertions(+), 2 deletions(-) create mode 100644 v2/src/main/java/com/skyflow/utils/ColumnValue.java create mode 100644 v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java create mode 100644 v2/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/v2/src/main/java/com/skyflow/VaultClient.java index 7114b6c9..bff4a879 100644 --- a/v2/src/main/java/com/skyflow/VaultClient.java +++ b/v2/src/main/java/com/skyflow/VaultClient.java @@ -7,10 +7,12 @@ import com.skyflow.generated.rest.api.RecordsApi; import com.skyflow.generated.rest.api.TokensApi; import com.skyflow.generated.rest.models.*; +import com.skyflow.utils.ColumnValue; import com.skyflow.utils.Utils; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.UpdateRequest; import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.TokenizeRequest; import io.github.cdimascio.dotenv.Dotenv; import java.util.ArrayList; @@ -121,6 +123,17 @@ protected RecordServiceUpdateRecordBody getUpdateRequestBody(UpdateRequest reque return updateRequestBody; } + protected V1TokenizePayload getTokenizePayload(TokenizeRequest request) { + V1TokenizePayload payload = new V1TokenizePayload(); + for(ColumnValue columnValue: request.getColumnValues()) { + V1TokenizeRecordRequest recordRequest = new V1TokenizeRecordRequest(); + recordRequest.setValue(columnValue.getValue()); + recordRequest.setColumnGroup(columnValue.getColumnGroup()); + payload.addTokenizationParametersItem(recordRequest); + } + return payload; + } + private void updateVaultURL() { String vaultURL = Utils.getVaultURL(this.vaultConfig.getClusterId(), this.vaultConfig.getEnv()); this.apiClient.setBasePath(vaultURL); diff --git a/v2/src/main/java/com/skyflow/utils/ColumnValue.java b/v2/src/main/java/com/skyflow/utils/ColumnValue.java new file mode 100644 index 00000000..a7f416c9 --- /dev/null +++ b/v2/src/main/java/com/skyflow/utils/ColumnValue.java @@ -0,0 +1,52 @@ +package com.skyflow.utils; + +import com.skyflow.enums.RedactionType; +import com.skyflow.vault.tokens.DetokenizeRequest; + +import java.util.ArrayList; + +public class ColumnValue { + + private final ColumnValueBuilder builder; + + private ColumnValue(ColumnValueBuilder builder) { + this.builder = builder; + } + + public static ColumnValueBuilder builder() { + return new ColumnValueBuilder(); + } + + public String getValue() { + return this.builder.value; + } + + public String getColumnGroup() { + return this.builder.columnGroup; + } + + public static final class ColumnValueBuilder { + private String value; + private String columnGroup; + + public ColumnValueBuilder() { + this.value = ""; + this.columnGroup = ""; + } + + public ColumnValueBuilder value(String value) { + this.value = value; + return this; + } + + public ColumnValueBuilder columnGroup(String columnGroup) { + this.columnGroup = columnGroup; + return this; + } + + public ColumnValue build() { + return new ColumnValue(this); + } + } + +} diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index b8d36fd8..556e36f2 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -6,6 +6,7 @@ import com.skyflow.errors.SkyflowException; import com.skyflow.vault.data.*; import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.TokenizeRequest; // Add config and request validations public class Validations { @@ -48,4 +49,8 @@ public static void validateDeleteRequest(DeleteRequest deleteRequest) throws Sky public static void validateQueryRequest(QueryRequest queryRequest) throws SkyflowException { } + + public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) throws SkyflowException { + + } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index aafc04fa..f99939be 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -16,6 +16,11 @@ import com.skyflow.vault.tokens.DetokenizeRecordResponse; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.DetokenizeResponse; +import com.skyflow.vault.tokens.TokenizeRequest; +import com.skyflow.vault.tokens.TokenizeResponse; + +import java.util.ArrayList; +import java.util.List; import java.util.ArrayList; import java.util.HashMap; @@ -264,8 +269,26 @@ public QueryResponse query(QueryRequest queryRequest) throws SkyflowException { return new QueryResponse(fields); } - public Object tokenize(Object tokenizeRequest) { - return null; + public TokenizeResponse tokenize(TokenizeRequest tokenizeRequest) throws SkyflowException { + V1TokenizeResponse result = null; + List list = new ArrayList<>(); + try { + Validations.validateTokenizeRequest(tokenizeRequest); + setBearerToken(); + V1TokenizePayload payload = super.getTokenizePayload(tokenizeRequest); + result = super.getTokensApi().recordServiceTokenize(super.getVaultConfig().getVaultId(), payload); + if(result!=null && result.getRecords().size()>0) { + + for(V1TokenizeRecordResponse response : result.getRecords()) { + if(response.getToken()!=null) { + list.add(response.getToken()); + } + } + } + } catch (ApiException e) { + throw new SkyflowException(e.getResponseBody()); + } + return new TokenizeResponse(list); } public BinLookupController lookUpBin() { diff --git a/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java b/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java new file mode 100644 index 00000000..7bfd8de0 --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java @@ -0,0 +1,39 @@ +package com.skyflow.vault.tokens; + +import com.skyflow.utils.ColumnValue; + +import java.util.ArrayList; +import java.util.List; + +public class TokenizeRequest { + private final TokenizeRequestBuilder builder; + + private TokenizeRequest(TokenizeRequest.TokenizeRequestBuilder builder) { + this.builder = builder; + } + + public static TokenizeRequestBuilder builder() { + return new TokenizeRequestBuilder(); + } + + public List getColumnValues() { + return this.builder.columnValues; + } + + public static final class TokenizeRequestBuilder { + private List columnValues; + + public TokenizeRequestBuilder() { + this.columnValues = new ArrayList<>(); + } + + public TokenizeRequestBuilder columnValues(List columnValues) { + this.columnValues = columnValues; + return this; + } + + public TokenizeRequest build() { + return new TokenizeRequest(this); + } + } +} diff --git a/v2/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java b/v2/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java new file mode 100644 index 00000000..8f62631b --- /dev/null +++ b/v2/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java @@ -0,0 +1,13 @@ +package com.skyflow.vault.tokens; + +import java.util.List; + +public class TokenizeResponse { + + private List tokens; + + public TokenizeResponse(List tokens) { + this.tokens = tokens; + } + +} From d441a2872ade357b096e67bd866a909e04d97192 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 15 Oct 2024 14:15:53 +0530 Subject: [PATCH 024/126] SK-1666 implement invoke connection public interface --- .../java/com/skyflow/ConnectionClient.java | 65 +++++++ v2/src/main/java/com/skyflow/Skyflow.java | 4 + .../com/skyflow/config/ConnectionConfig.java | 9 + .../java/com/skyflow/utils/HttpUtility.java | 180 ++++++++++++++++++ v2/src/main/java/com/skyflow/utils/Utils.java | 39 ++++ .../connection/InvokeConnectionRequest.java | 91 ++++++++- .../connection/InvokeConnectionResponse.java | 14 +- .../controller/ConnectionController.java | 79 +++++++- 8 files changed, 470 insertions(+), 11 deletions(-) create mode 100644 v2/src/main/java/com/skyflow/ConnectionClient.java create mode 100644 v2/src/main/java/com/skyflow/utils/HttpUtility.java diff --git a/v2/src/main/java/com/skyflow/ConnectionClient.java b/v2/src/main/java/com/skyflow/ConnectionClient.java new file mode 100644 index 00000000..a42d3aa6 --- /dev/null +++ b/v2/src/main/java/com/skyflow/ConnectionClient.java @@ -0,0 +1,65 @@ +package com.skyflow; + +import com.skyflow.config.ConnectionConfig; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.api.RecordsApi; +import com.skyflow.generated.rest.api.TokensApi; +import io.github.cdimascio.dotenv.Dotenv; + +public class ConnectionClient { + + private final ConnectionConfig connectionConfig; + private Credentials commonCredentials; + private Credentials finalCredentials; + private final ApiClient apiClient; + + + protected ConnectionClient(ConnectionConfig connectionConfig, Credentials credentials) { + super(); + this.connectionConfig = connectionConfig; + this.commonCredentials = credentials; + this.apiClient = new ApiClient(); + prioritiseCredentials(); + } + + protected Credentials getFinalCredentials() { + return finalCredentials; + } + + protected ConnectionConfig getConnectionConfig() { + return connectionConfig; + } + + protected void setCommonCredentials(Credentials commonCredentials) { + this.commonCredentials = commonCredentials; + prioritiseCredentials(); + } + + protected ApiClient getApiClient() { + return apiClient; + } + + private void prioritiseCredentials() { + try { + if (this.connectionConfig.getCredentials() != null) { + this.finalCredentials = this.connectionConfig.getCredentials(); + } else if (this.commonCredentials != null) { + this.finalCredentials = this.commonCredentials; + } else { + Dotenv dotenv = Dotenv.load(); + String sysCredentials = dotenv.get("SKYFLOW_CREDENTIALS"); + if (sysCredentials == null) { + // throw error for not passing any credentials + } else { + this.finalCredentials = new Credentials(); + this.finalCredentials.setCredentialsString(sysCredentials); + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/v2/src/main/java/com/skyflow/Skyflow.java index 6c08644e..c8bae6cc 100644 --- a/v2/src/main/java/com/skyflow/Skyflow.java +++ b/v2/src/main/java/com/skyflow/Skyflow.java @@ -100,6 +100,7 @@ public static final class SkyflowClientBuilder { private final LinkedHashMap connectionsMap; private final LinkedHashMap vaultClientsMap; private final LinkedHashMap vaultConfigMap; + private final LinkedHashMap connectionConfigMap; private Credentials skyflowCredentials; private LogLevel logLevel; @@ -107,6 +108,7 @@ public SkyflowClientBuilder() { this.vaultClientsMap = new LinkedHashMap<>(); this.vaultConfigMap = new LinkedHashMap<>(); this.connectionsMap = new LinkedHashMap<>(); + this.connectionConfigMap = new LinkedHashMap<>(); this.skyflowCredentials = null; this.logLevel = LogLevel.ERROR; } @@ -147,6 +149,7 @@ public SkyflowClientBuilder addConnectionConfig(ConnectionConfig connectionConfi if (this.connectionsMap.containsKey(connectionConfig.getConnectionId())) { // display error log, throw error, or both } else { + this.connectionConfigMap.put(connectionConfig.getConnectionId(), connectionConfig); ConnectionController controller = new ConnectionController(connectionConfig, this.skyflowCredentials); this.connectionsMap.put(connectionConfig.getConnectionId(), controller); } @@ -166,6 +169,7 @@ public SkyflowClientBuilder updateConnectionConfig(ConnectionConfig connectionCo public SkyflowClientBuilder removeConnectionConfig(String connectionId) { if (this.connectionsMap.containsKey(connectionId)) { this.connectionsMap.remove(connectionId); + this.connectionConfigMap.remove(connectionId); } else { // display error log, throw error, or both } diff --git a/v2/src/main/java/com/skyflow/config/ConnectionConfig.java b/v2/src/main/java/com/skyflow/config/ConnectionConfig.java index 0c2c4320..3d431565 100644 --- a/v2/src/main/java/com/skyflow/config/ConnectionConfig.java +++ b/v2/src/main/java/com/skyflow/config/ConnectionConfig.java @@ -26,4 +26,13 @@ public void setConnectionUrl(String connectionUrl) { public void setCredentials(Credentials credentials) { this.credentials = credentials; } + + public String getConnectionUrl() { + return connectionUrl; + } + + public Credentials getCredentials() { + return credentials; + } + } diff --git a/v2/src/main/java/com/skyflow/utils/HttpUtility.java b/v2/src/main/java/com/skyflow/utils/HttpUtility.java new file mode 100644 index 00000000..93cbdd31 --- /dev/null +++ b/v2/src/main/java/com/skyflow/utils/HttpUtility.java @@ -0,0 +1,180 @@ +package com.skyflow.utils; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.skyflow.errors.SkyflowException; + +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +public final class HttpUtility { + + private static String requestID; + + public static String getRequestID() { + return requestID; + } + + private static final String LINE_FEED = "\r\n"; + + public static String sendRequest(String method, URL url, JsonObject params, Map headers) throws IOException, SkyflowException { + + HttpURLConnection connection = null; + BufferedReader in = null; + StringBuffer response = null; + String boundary = String.valueOf(System.currentTimeMillis()); + + try { + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod(method); + connection.setRequestProperty("content-type", "application/json"); + connection.setRequestProperty("Accept", "*/*"); + + if (headers != null && headers.size() > 0) { + for (Map.Entry entry : headers.entrySet()) + connection.setRequestProperty(entry.getKey(), entry.getValue()); + + // append dynamic boundary if content-type is multipart/form-data + if (headers.containsKey("content-type")) { + if (headers.get("content-type") == "multipart/form-data") { + connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary); + } + } + } + if (params != null && params.size() > 0) { + connection.setDoOutput(true); + try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { + byte[] input = null; + String requestContentType = connection.getRequestProperty("content-type"); + + if (requestContentType.contains("application/x-www-form-urlencoded")) { + input = formatJsonToFormEncodedString(params).getBytes(StandardCharsets.UTF_8); + } else if (requestContentType.contains("multipart/form-data")) { + input = formatJsonToMultiPartFormDataString(params, boundary).getBytes(StandardCharsets.UTF_8); + }else { + input = params.toString().getBytes(StandardCharsets.UTF_8); + } + + wr.write(input, 0, input.length); + wr.flush(); + } + } + + int status = connection.getResponseCode(); + String requestID = connection.getHeaderField("x-request-id"); + HttpUtility.requestID = requestID; + + Reader streamReader; + if (status > 299) { + if (connection.getErrorStream() != null) + streamReader = new InputStreamReader(connection.getErrorStream()); + else { + String description = appendRequestId("replace with description", requestID); + throw new SkyflowException(description); + } + } else { + streamReader = new InputStreamReader(connection.getInputStream()); + } + + response = new StringBuffer(); + in = new BufferedReader(streamReader); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + + if (status > 299) { + String errorMsg = appendRequestIdToErrorObj(status, response.toString(), requestID); + throw new SkyflowException(errorMsg); + } + } finally { + if (in != null) { + in.close(); + } + if (connection != null) { + connection.disconnect(); + } + } + return response.toString(); + + } + + public static String formatJsonToFormEncodedString(JsonObject requestBody) { + StringBuilder formEncodeString = new StringBuilder(); + HashMap jsonMap = convertJsonToMap(requestBody, ""); + + for (Map.Entry currentEntry : jsonMap.entrySet()) + formEncodeString.append(makeFormEncodeKeyValuePair(currentEntry.getKey(), currentEntry.getValue())); + + return formEncodeString.substring(0, formEncodeString.length() - 1); + } + + public static String formatJsonToMultiPartFormDataString(JsonObject requestBody, String boundary) { + StringBuilder formEncodeString = new StringBuilder(); + HashMap jsonMap = convertJsonToMap(requestBody, ""); + + for (Map.Entry currentEntry : jsonMap.entrySet()) + formEncodeString.append(makeFormDataKeyValuePair(currentEntry.getKey(), currentEntry.getValue(), boundary)); + + formEncodeString.append(LINE_FEED); + formEncodeString.append("--").append(boundary).append("--").append(LINE_FEED); + + return formEncodeString.toString(); + } + + private static HashMap convertJsonToMap(JsonObject json, String rootKey) { + HashMap currentMap = new HashMap<>(); + for (Object key : json.keySet()) { + Object currentValue = json.get((String) key); + String currentKey = rootKey.length() != 0 ? rootKey + '[' + key.toString() + ']' : rootKey + key.toString(); + if (currentValue instanceof JsonObject) { + currentMap.putAll(convertJsonToMap((JsonObject) currentValue, currentKey)); + } else { + currentMap.put(currentKey, currentValue.toString()); + } + } + return currentMap; + } + + private static String makeFormDataKeyValuePair(String key, String value, String boundary) { + StringBuilder formDataTextField = new StringBuilder(); + formDataTextField.append("--").append(boundary).append(LINE_FEED); + formDataTextField.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_FEED); + formDataTextField.append(LINE_FEED); + formDataTextField.append(value).append(LINE_FEED); + + return formDataTextField.toString(); + } + + public static String appendRequestId(String message, String requestId) { + if (requestId != null && !requestId.isEmpty()) { + message = message + " - requestId: " + requestId; + } + return message; + } + + public static String appendRequestIdToErrorObj(int status, String error, String requestId) throws SkyflowException { + if (requestId != null && !requestId.isEmpty()) { + JsonObject errorObject = (JsonObject) new JsonParser().parse(error); + JsonObject tempError = (JsonObject) errorObject.get("error"); + if (tempError != null) { + String message = String.valueOf(tempError.get("message")); + message = message + " - requestId: " + requestId; + + tempError.addProperty("message", message); + errorObject.add("error", tempError); + } + error = errorObject.toString(); + } + return error; + } + + private static String makeFormEncodeKeyValuePair(String key, String value) { + return key + "=" + value + "&"; + } + +} diff --git a/v2/src/main/java/com/skyflow/utils/Utils.java b/v2/src/main/java/com/skyflow/utils/Utils.java index 51115bb0..0937083f 100644 --- a/v2/src/main/java/com/skyflow/utils/Utils.java +++ b/v2/src/main/java/com/skyflow/utils/Utils.java @@ -1,9 +1,11 @@ package com.skyflow.utils; +import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; import com.skyflow.enums.Env; import com.skyflow.errors.SkyflowException; import com.skyflow.serviceaccount.util.BearerToken; +import com.skyflow.vault.connection.InvokeConnectionRequest; import org.apache.commons.codec.binary.Base64; import java.io.File; @@ -14,6 +16,8 @@ import java.security.PrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; +import java.util.HashMap; +import java.util.Map; public final class Utils { public static String getVaultURL(String clusterId, Env env) { @@ -97,4 +101,39 @@ private static PrivateKey parsePkcs8PrivateKey(byte[] pkcs8Bytes) throws Skyflow } return privateKey; } + + public static String constructConnectionURL(ConnectionConfig config, InvokeConnectionRequest invokeConnectionRequest) { + StringBuilder filledURL = new StringBuilder((String) config.getConnectionUrl()); + + if (invokeConnectionRequest.getPathParams() != null && !invokeConnectionRequest.getPathParams().isEmpty()) { + for (Map.Entry entry : invokeConnectionRequest.getPathParams().entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + filledURL = new StringBuilder(filledURL.toString().replace(String.format("{%s}", key), value)); + } + } + + if(invokeConnectionRequest.getQueryParams() != null && !invokeConnectionRequest.getQueryParams().isEmpty()) { + filledURL.append("?"); + for (Map.Entry entry : invokeConnectionRequest.getQueryParams().entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + filledURL.append(key).append("=").append(value).append("&"); + } + filledURL = new StringBuilder(filledURL.substring(0, filledURL.length() - 1)); + } + + return filledURL.toString(); + } + + public static Map constructConnectionHeadersMap(Map requestHeaders) { + Map headersMap = new HashMap<>(); + for (Map.Entry entry : requestHeaders.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + headersMap.put(key.toLowerCase(), value); + } + return headersMap; + } + } diff --git a/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java b/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java index 886e2166..a74b9adb 100644 --- a/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java +++ b/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java @@ -1,10 +1,95 @@ package com.skyflow.vault.connection; +import com.google.gson.JsonObject; +import com.skyflow.enums.RedactionType; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.TokenizeRequest; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + public class InvokeConnectionRequest { - // members - public InvokeConnectionRequest() { + private final InvokeConnectionRequestBuilder builder; + + private InvokeConnectionRequest(InvokeConnectionRequestBuilder builder) { + this.builder = builder; + } + + public static InvokeConnectionRequestBuilder builder() { + return new InvokeConnectionRequestBuilder(); + } + + public InvokeConnectionRequest getConnectionRequest() { + return new InvokeConnectionRequest(builder); + } + + public String getMethodName() { + return builder.methodName; + } + + public Map getPathParams() { + return builder.pathParams; + } + + public Map getQueryParams() { + return builder.queryParams; + } + + public Map getRequestHeaders() { + return builder.requestHeaders; + } + + public Object getRequestBody() { + return builder.requestBody; + } + + public static final class InvokeConnectionRequestBuilder{ + + private String methodName; + private Map pathParams; + private Map queryParams; + private Map requestHeaders; + private Object requestBody; + + public InvokeConnectionRequestBuilder() { + this.methodName = ""; + this.pathParams = new HashMap<>(); + this.queryParams = new HashMap<>(); + this.requestHeaders = new HashMap<>(); + this.requestBody = new Object(); + } + + public InvokeConnectionRequestBuilder methodName(String methodName) { + this.methodName = methodName; + return this; + } + + public InvokeConnectionRequestBuilder pathParams(Map pathParams) { + this.pathParams = pathParams; + return this; + } + + public InvokeConnectionRequestBuilder queryParams(Map queryParams) { + this.queryParams = queryParams; + return this; + } + + public InvokeConnectionRequestBuilder requestHeaders(Map requestHeaders) { + this.requestHeaders = requestHeaders; + return this; + } + + public InvokeConnectionRequestBuilder requestBody(Object requestBody) { + this.requestBody = requestBody; + return this; + } + + public InvokeConnectionRequest build() { + return new InvokeConnectionRequest(this); + } + } - // getters ans setters } diff --git a/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java b/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java index 4876cffd..d6c8fa17 100644 --- a/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java +++ b/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java @@ -1,10 +1,18 @@ package com.skyflow.vault.connection; +import com.google.gson.JsonObject; + public class InvokeConnectionResponse { - // members + private JsonObject response; - public InvokeConnectionResponse() { + public InvokeConnectionResponse(JsonObject response) { + this.response = response; } - // getters ans setters + @Override + public String toString() { + return "InvokeConnectionResponse{" + + "response=" + response + + '}'; + } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java b/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java index 3061ca3c..74e91d29 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -1,15 +1,35 @@ package com.skyflow.vault.controller; +import com.google.gson.Gson; +import com.google.gson.JsonParser; +import com.skyflow.ConnectionClient; import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.auth.HttpBearerAuth; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.utils.HttpUtility; +import com.skyflow.utils.Utils; +import com.skyflow.utils.validations.Validations; import com.skyflow.vault.connection.InvokeConnectionRequest; import com.skyflow.vault.connection.InvokeConnectionResponse; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; -public class ConnectionController { +import java.net.URL; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class ConnectionController extends ConnectionClient { private ConnectionConfig connectionConfig; private Credentials commonCredentials; + private String token; + public ConnectionController(ConnectionConfig connectionConfig, Credentials credentials) { + super(connectionConfig, credentials); this.connectionConfig = connectionConfig; this.commonCredentials = credentials; } @@ -26,9 +46,58 @@ public void setConnectionConfig(ConnectionConfig connectionConfig) { this.connectionConfig = connectionConfig; } - // check in python interfaces - public InvokeConnectionResponse invoke(InvokeConnectionRequest invokeConnectionRequest) { - // invoke the connection - return null; + public InvokeConnectionResponse invoke(InvokeConnectionRequest invokeConnectionRequest) throws SkyflowException, IOException { + + InvokeConnectionResponse connectionResponse; + setBearerToken(); + String filledURL = Utils.constructConnectionURL(connectionConfig, invokeConnectionRequest); + Map headers = new HashMap<>(); + + if (invokeConnectionRequest.getRequestHeaders().containsKey("requestHeader")) { + headers = Utils.constructConnectionHeadersMap(invokeConnectionRequest.getRequestHeaders()); + } + if (!headers.containsKey("x-skyflow-authorization")) { + headers.put("x-skyflow-authorization", token); + } + + String requestMethod = invokeConnectionRequest.getMethodName(); + JsonObject requestBody = null; + Object requestBodyObject = invokeConnectionRequest.getRequestBody(); + + if(requestBodyObject!=null) { + try { + requestBody = (JsonObject) convertObjectToJson(requestBodyObject); + System.out.println("Converted requestBody to JsonObject: " + requestBody.toString()); + } catch (Exception e) { + System.out.println("Error while converting requestBody to JsonObject: " + e.getMessage()); + } + } + + String response = HttpUtility.sendRequest(requestMethod, new URL(filledURL), requestBody, headers); +// connectionResponse = (JsonObject) new JsonParser().parse(response); + connectionResponse = new InvokeConnectionResponse((JsonObject) new JsonParser().parse(response)); + return connectionResponse; + } + + private void setBearerToken() throws SkyflowException { + Validations.validateCredentials(super.getFinalCredentials()); + if (token == null || Token.isExpired(token)) { + token = Utils.generateBearerToken(super.getFinalCredentials()); + } + HttpBearerAuth Bearer = (HttpBearerAuth) super.getApiClient().getAuthentication("Bearer"); + Bearer.setBearerToken(token); + } + + private JsonObject convertObjectToJson(Object object) { + Gson gson = new Gson(); + JsonElement jsonElement = gson.toJsonTree(object); + + if (jsonElement.isJsonObject()) { + return jsonElement.getAsJsonObject(); + } else { + JsonObject wrapper = new JsonObject(); + wrapper.add("value", jsonElement); + return wrapper; + } } } From 5496e94d02fe36172dcf94455450dd046d7e3cb3 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 16 Oct 2024 18:15:58 +0530 Subject: [PATCH 025/126] SK-1701 Add continueOnError in insert vault API public interface --- v2/src/main/java/com/skyflow/VaultClient.java | 32 ++++++- .../vault/controller/VaultController.java | 83 ++++++++++++++----- .../com/skyflow/vault/data/InsertRequest.java | 23 ++++- .../com/skyflow/vault/data/UpdateRequest.java | 2 +- 4 files changed, 110 insertions(+), 30 deletions(-) diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/v2/src/main/java/com/skyflow/VaultClient.java index bff4a879..f465c2a4 100644 --- a/v2/src/main/java/com/skyflow/VaultClient.java +++ b/v2/src/main/java/com/skyflow/VaultClient.java @@ -86,7 +86,7 @@ protected V1DetokenizePayload getDetokenizePayload(DetokenizeRequest request) { return payload; } - protected RecordServiceInsertRecordBody getInsertRequestBody(InsertRequest request) { + protected RecordServiceInsertRecordBody getBulkInsertRequestBody(InsertRequest request) { RecordServiceInsertRecordBody insertRecordBody = new RecordServiceInsertRecordBody(); insertRecordBody.setTokenization(request.getReturnTokens()); insertRecordBody.setHomogeneous(request.getHomogeneous()); @@ -108,9 +108,35 @@ protected RecordServiceInsertRecordBody getInsertRequestBody(InsertRequest reque return insertRecordBody; } + protected RecordServiceBatchOperationBody getBatchInsertRequestBody(InsertRequest request) { + RecordServiceBatchOperationBody insertRequestBody = new RecordServiceBatchOperationBody(); + insertRequestBody.setContinueOnError(true); + insertRequestBody.setByot(request.getTokenStrict().getBYOT()); + + ArrayList> values = request.getValues(); + ArrayList> tokens = request.getTokens(); + List records = new ArrayList<>(); + + for (int index = 0; index < values.size(); index++) { + V1BatchRecord record = new V1BatchRecord(); + record.setMethod(BatchRecordMethod.POST); + record.setTableName(request.getTable()); + record.setUpsert(request.getUpsert()); + record.setTokenization(request.getReturnTokens()); + record.setFields(values.get(index)); + if (tokens != null) { + record.setTokens(tokens.get(index)); + } + records.add(record); + } + + insertRequestBody.setRecords(records); + return insertRequestBody; + } + protected RecordServiceUpdateRecordBody getUpdateRequestBody(UpdateRequest request) { RecordServiceUpdateRecordBody updateRequestBody = new RecordServiceUpdateRecordBody(); - updateRequestBody.byot(request.getByot().getBYOT()); + updateRequestBody.byot(request.getTokenStrict().getBYOT()); updateRequestBody.setTokenization(request.getReturnTokens()); HashMap values = request.getValues(); HashMap tokens = request.getTokens(); @@ -125,7 +151,7 @@ protected RecordServiceUpdateRecordBody getUpdateRequestBody(UpdateRequest reque protected V1TokenizePayload getTokenizePayload(TokenizeRequest request) { V1TokenizePayload payload = new V1TokenizePayload(); - for(ColumnValue columnValue: request.getColumnValues()) { + for (ColumnValue columnValue : request.getColumnValues()) { V1TokenizeRecordRequest recordRequest = new V1TokenizeRecordRequest(); recordRequest.setValue(columnValue.getValue()); recordRequest.setColumnGroup(columnValue.getColumnGroup()); diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index f99939be..69428bad 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -1,5 +1,6 @@ package com.skyflow.vault.controller; +import com.google.gson.*; import com.google.gson.internal.LinkedTreeMap; import com.skyflow.VaultClient; import com.skyflow.config.Credentials; @@ -13,18 +14,12 @@ import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; import com.skyflow.vault.data.*; -import com.skyflow.vault.tokens.DetokenizeRecordResponse; -import com.skyflow.vault.tokens.DetokenizeRequest; -import com.skyflow.vault.tokens.DetokenizeResponse; -import com.skyflow.vault.tokens.TokenizeRequest; -import com.skyflow.vault.tokens.TokenizeResponse; - -import java.util.ArrayList; -import java.util.List; +import com.skyflow.vault.tokens.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; public final class VaultController extends VaultClient { private DetectController detectController; @@ -40,7 +35,34 @@ public VaultController(VaultConfig vaultConfig, Credentials credentials) { this.detectController = null; } - private static synchronized HashMap getFormattedInsertRecord(V1RecordMetaProperties record) { + private static synchronized HashMap getFormattedBatchInsertRecord(Object record, int requestIndex) { + HashMap insertRecord = new HashMap<>(); + Gson gson = new Gson(); + String jsonString = gson.toJson(record); + JsonObject bodyObject = JsonParser.parseString(jsonString).getAsJsonObject().get("Body").getAsJsonObject(); + JsonArray records = bodyObject.getAsJsonArray("records"); + JsonPrimitive error = bodyObject.getAsJsonPrimitive("error"); + + if (records != null) { + for (JsonElement recordElement : records) { + JsonObject recordObject = recordElement.getAsJsonObject(); + insertRecord.put("skyflow_id", recordObject.get("skyflow_id").getAsString()); + + Map tokensMap = recordObject.get("tokens").getAsJsonObject().asMap(); + for (String key : tokensMap.keySet()) { + insertRecord.put(key, tokensMap.get(key)); + } + } + } + + if (error != null) { + insertRecord.put("error", error.getAsString()); + } + insertRecord.put("request_index", requestIndex); + return insertRecord; + } + + private static synchronized HashMap getFormattedBulkInsertRecord(V1RecordMetaProperties record) { HashMap insertRecord = new HashMap<>(); String skyflowId = record.getSkyflowId(); insertRecord.put("skyflowId", skyflowId); @@ -120,20 +142,37 @@ private static synchronized HashMap getFormattedQueryRecord(V1Fi } public InsertResponse insert(InsertRequest insertRequest) throws SkyflowException { - V1InsertRecordResponse result = null; + V1InsertRecordResponse bulkInsertResult = null; + V1BatchOperationResponse batchInsertResult = null; ArrayList> insertedFields = new ArrayList<>(); ArrayList> errorFields = new ArrayList<>(); + Boolean continueOnError = insertRequest.getContinueOnError(); try { Validations.validateInsertRequest(insertRequest); setBearerToken(); - RecordServiceInsertRecordBody insertBody = super.getInsertRequestBody(insertRequest); - result = super.getRecordsApi().recordServiceInsertRecord( - super.getVaultConfig().getVaultId(), insertRequest.getTable(), insertBody); - List records = result.getRecords(); - if (records != null) { - for (V1RecordMetaProperties record : records) { - HashMap insertRecord = getFormattedInsertRecord(record); - insertedFields.add(insertRecord); + if (continueOnError) { + RecordServiceBatchOperationBody insertBody = super.getBatchInsertRequestBody(insertRequest); + batchInsertResult = super.getRecordsApi().recordServiceBatchOperation(super.getVaultConfig().getVaultId(), insertBody); + List records = batchInsertResult.getResponses(); + for (int index = 0; index < records.size(); index++) { + Object record = records.get(index); + HashMap insertRecord = getFormattedBatchInsertRecord(record, index); + if (insertRecord.containsKey("skyflow_id")) { + insertedFields.add(insertRecord); + } else { + errorFields.add(insertRecord); + } + } + } else { + RecordServiceInsertRecordBody insertBody = super.getBulkInsertRequestBody(insertRequest); + bulkInsertResult = super.getRecordsApi().recordServiceInsertRecord( + super.getVaultConfig().getVaultId(), insertRequest.getTable(), insertBody); + List records = bulkInsertResult.getRecords(); + if (records != null) { + for (V1RecordMetaProperties record : records) { + HashMap insertRecord = getFormattedBulkInsertRecord(record); + insertedFields.add(insertRecord); + } } } } catch (ApiException e) { @@ -277,15 +316,15 @@ public TokenizeResponse tokenize(TokenizeRequest tokenizeRequest) throws Skyflow setBearerToken(); V1TokenizePayload payload = super.getTokenizePayload(tokenizeRequest); result = super.getTokensApi().recordServiceTokenize(super.getVaultConfig().getVaultId(), payload); - if(result!=null && result.getRecords().size()>0) { + if (result != null && result.getRecords().size() > 0) { - for(V1TokenizeRecordResponse response : result.getRecords()) { - if(response.getToken()!=null) { + for (V1TokenizeRecordResponse response : result.getRecords()) { + if (response.getToken() != null) { list.add(response.getToken()); } } } - } catch (ApiException e) { + } catch (ApiException e) { throw new SkyflowException(e.getResponseBody()); } return new TokenizeResponse(list); diff --git a/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java b/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java index d7df9157..8cdc22bc 100644 --- a/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java @@ -13,6 +13,7 @@ public class InsertRequest { private final String upsert; private final Boolean homogeneous; private final Boolean tokenMode; + private final Boolean continueOnError; private final Byot tokenStrict; private InsertRequest(InsertRequestBuilder builder) { @@ -23,6 +24,7 @@ private InsertRequest(InsertRequestBuilder builder) { this.upsert = builder.upsert; this.homogeneous = builder.homogeneous; this.tokenMode = builder.tokenMode; + this.continueOnError = builder.continueOnError; this.tokenStrict = builder.tokenStrict; } @@ -58,6 +60,10 @@ public Boolean getTokenMode() { return tokenMode; } + public Boolean getContinueOnError() { + return continueOnError; + } + public Byot getTokenStrict() { return tokenStrict; } @@ -70,10 +76,14 @@ public static final class InsertRequestBuilder { private String upsert; private Boolean homogeneous; private Boolean tokenMode; + private Boolean continueOnError; private Byot tokenStrict; private InsertRequestBuilder() { this.returnTokens = true; + this.homogeneous = true; + this.tokenMode = true; + this.continueOnError = false; this.tokenStrict = Byot.DISABLE; } @@ -93,7 +103,7 @@ public InsertRequestBuilder tokens(ArrayList> tokens) { } public InsertRequestBuilder returnTokens(Boolean returnTokens) { - this.returnTokens = returnTokens; + this.returnTokens = returnTokens == null || returnTokens; return this; } @@ -103,17 +113,22 @@ public InsertRequestBuilder upsert(String upsert) { } public InsertRequestBuilder homogeneous(Boolean homogeneous) { - this.homogeneous = homogeneous; + this.homogeneous = homogeneous == null || homogeneous; return this; } public InsertRequestBuilder tokenMode(Boolean tokenMode) { - this.tokenMode = tokenMode; + this.tokenMode = tokenMode == null || tokenMode; + return this; + } + + public InsertRequestBuilder continueOnError(Boolean continueOnError) { + this.continueOnError = continueOnError != null && continueOnError; return this; } public InsertRequestBuilder tokenStrict(Byot tokenStrict) { - this.tokenStrict = tokenStrict; + this.tokenStrict = tokenStrict == null ? Byot.DISABLE : tokenStrict; return this; } diff --git a/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java b/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java index 55d64209..7bda90dd 100644 --- a/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java @@ -45,7 +45,7 @@ public HashMap getTokens() { return tokens; } - public Byot getByot() { + public Byot getTokenStrict() { return tokenStrict; } From 19aa8ce494a1a73b5c128ca0b98c778d5bb1ed14 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 16 Oct 2024 19:28:44 +0530 Subject: [PATCH 026/126] SK-1681 Add validations --- .../com/skyflow/config/ConnectionConfig.java | 4 + .../utils/validations/Validations.java | 173 +++++++++++++++++- .../com/skyflow/vault/data/GetRequest.java | 8 +- 3 files changed, 175 insertions(+), 10 deletions(-) diff --git a/v2/src/main/java/com/skyflow/config/ConnectionConfig.java b/v2/src/main/java/com/skyflow/config/ConnectionConfig.java index 0c2c4320..f0821de7 100644 --- a/v2/src/main/java/com/skyflow/config/ConnectionConfig.java +++ b/v2/src/main/java/com/skyflow/config/ConnectionConfig.java @@ -19,6 +19,10 @@ public void setConnectionId(String connectionId) { this.connectionId = connectionId; } + public String getConnectionUrl() { + return connectionUrl; + } + public void setConnectionUrl(String connectionUrl) { this.connectionUrl = connectionUrl; } diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index 556e36f2..f24a8e82 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -3,20 +3,36 @@ import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Byot; +import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; import com.skyflow.vault.data.*; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; -// Add config and request validations +import java.util.ArrayList; +import java.util.HashMap; + public class Validations { public static void validateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { - + String vaultId = vaultConfig.getVaultId(); + String clusterId = vaultConfig.getClusterId(); + if (vaultId == null || vaultId.trim().isEmpty()) { + throw new SkyflowException(); + } else if (clusterId == null || clusterId.trim().isEmpty()) { + throw new SkyflowException(); + } } public static void validateConnectionConfig(ConnectionConfig connectionConfig) throws SkyflowException { - + String connectionId = connectionConfig.getConnectionId(); + String connectionUrl = connectionConfig.getConnectionUrl(); + if (connectionId == null || connectionId.trim().isEmpty()) { + throw new SkyflowException(); + } else if (connectionUrl == null || connectionUrl.trim().isEmpty()) { + throw new SkyflowException(); + } } public static void validateCredentials(Credentials credentials) throws SkyflowException { @@ -26,15 +42,77 @@ public static void validateCredentials(Credentials credentials) throws SkyflowEx if (credentials.getToken() != null) nonNullMembers++; if (nonNullMembers != 1) { - throw new SkyflowException("only one of tokens, path, and credentialsString is allowed"); + throw new SkyflowException(); } } public static void validateDetokenizeRequest(DetokenizeRequest detokenizeRequest) throws SkyflowException { - + ArrayList tokens = detokenizeRequest.getTokens(); + RedactionType redactionType = detokenizeRequest.getRedactionType(); + Boolean continueOnError = detokenizeRequest.getContinueOnError(); + if (tokens == null || tokens.isEmpty()) { + throw new SkyflowException(); + } else if (continueOnError == null) { + throw new SkyflowException(); + } else if (redactionType == null) { + throw new SkyflowException(); + } else { + for (String token : tokens) { + if (token == null || token.trim().isEmpty()) { + throw new SkyflowException(); + } + } + } } public static void validateInsertRequest(InsertRequest insertRequest) throws SkyflowException { + String table = insertRequest.getTable(); + ArrayList> values = insertRequest.getValues(); + ArrayList> tokens = insertRequest.getTokens(); + Boolean returnTokens = insertRequest.getReturnTokens(); + String upsert = insertRequest.getUpsert(); + Boolean homogeneous = insertRequest.getHomogeneous(); + Boolean tokenMode = insertRequest.getTokenMode(); + Byot tokenStrict = insertRequest.getTokenStrict(); + + if (table == null || table.trim().isEmpty()) { + throw new SkyflowException(); + } else if (values == null || values.isEmpty()) { + throw new SkyflowException(); + } else if (upsert != null && upsert.trim().isEmpty()) { + throw new SkyflowException(); + } else if (homogeneous != null && homogeneous) { + throw new SkyflowException(); + } + + for (HashMap valuesMap : values) { + for (String key : valuesMap.keySet()) { + if (key == null || key.trim().isEmpty()) { + throw new SkyflowException(); + } else { + Object value = valuesMap.get(key); + if (value == null || value.toString().trim().isEmpty()) { + throw new SkyflowException(); + } + } + } + } + + switch (tokenStrict) { + case DISABLE: + if (tokens != null) { + throw new SkyflowException(); + } + case ENABLE: + if (tokens == null) { + throw new SkyflowException(); + } + case ENABLE_STRICT: + if (tokens.size() != values.size()) { + throw new SkyflowException(); + } + } + validateTokensForInsertRequest(tokens, values); } @@ -42,15 +120,98 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep } public static void validateUpdateRequest(UpdateRequest updateRequest) throws SkyflowException { + String table = updateRequest.getTable(); + String skyflowId = updateRequest.getId(); + Boolean returnTokens = updateRequest.getReturnTokens(); + HashMap values = updateRequest.getValues(); + HashMap tokens = updateRequest.getTokens(); + + if (table == null || table.trim().isEmpty()) { + throw new SkyflowException(); + } else if (skyflowId == null || skyflowId.trim().isEmpty()) { + throw new SkyflowException(); + } else if (returnTokens == null) { + throw new SkyflowException(); + } else if (values == null || values.isEmpty()) { + throw new SkyflowException(); + } else if (tokens == null || tokens.isEmpty()) { + throw new SkyflowException(); + } + + for (String key : values.keySet()) { + if (key == null || key.trim().isEmpty()) { + throw new SkyflowException(); + } else { + Object value = values.get(key); + if (value == null || value.toString().trim().isEmpty()) { + throw new SkyflowException(); + } + } + } + + for (String key : tokens.keySet()) { + if (key == null || key.trim().isEmpty()) { + throw new SkyflowException(); + } else { + Object value = tokens.get(key); + if (value == null || value.toString().trim().isEmpty()) { + throw new SkyflowException(); + } + } + } } public static void validateDeleteRequest(DeleteRequest deleteRequest) throws SkyflowException { + String table = deleteRequest.getTable(); + ArrayList ids = deleteRequest.getIds(); + if (table == null || table.trim().isEmpty()) { + throw new SkyflowException(); + } else if (ids == null || ids.isEmpty()) { + throw new SkyflowException(); + } else { + for (String id : ids) { + if (id.trim().isEmpty()) { + throw new SkyflowException(); + } + } + } } public static void validateQueryRequest(QueryRequest queryRequest) throws SkyflowException { + String query = queryRequest.getQuery(); + if (query == null || query.trim().isEmpty()) { + throw new SkyflowException(); + } } - + public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) throws SkyflowException { } + + private static void validateTokensForInsertRequest( + ArrayList> tokens, + ArrayList> values + ) throws SkyflowException { + if (tokens.isEmpty()) { + throw new SkyflowException(); + } + + for (int index = 0; index < tokens.size(); index++) { + HashMap tokensMap = tokens.get(index); + HashMap valuesMap = values.get(index); + + for (String key : tokensMap.keySet()) { + if (key == null || key.trim().isEmpty()) { + throw new SkyflowException(); + } else if (!valuesMap.containsKey(key)) { + throw new SkyflowException(); + } else { + Object value = tokensMap.get(key); + if (value == null || value.toString().trim().isEmpty()) { + throw new SkyflowException(); + } + } + } + } + } } diff --git a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java index 862bfa03..38a62f50 100644 --- a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java @@ -112,12 +112,12 @@ public GetRequestBuilder ids(ArrayList ids) { } public GetRequestBuilder redactionType(RedactionType redactionType) { - this.redactionType = redactionType; + this.redactionType = redactionType == null ? RedactionType.PLAIN_TEXT : redactionType; return this; } public GetRequestBuilder tokenization(Boolean tokenization) { - this.tokenization = tokenization; + this.tokenization = tokenization != null && tokenization; return this; } @@ -137,7 +137,7 @@ public GetRequestBuilder limit(String limit) { } public GetRequestBuilder downloadURL(Boolean downloadURL) { - this.downloadURL = downloadURL; + this.downloadURL = downloadURL == null || downloadURL; return this; } @@ -152,7 +152,7 @@ public GetRequestBuilder columnValues(ArrayList columnValues) { } public GetRequestBuilder orderBy(String orderBy) { - this.orderBy = orderBy; + this.orderBy = orderBy == null ? Constants.ORDER_ASCENDING : orderBy; return this; } From 9e0442070552843079c3c4009cfb61c27d46a2be Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Thu, 17 Oct 2024 16:16:03 +0530 Subject: [PATCH 027/126] SK-1681 add validations for tokenize request --- .../skyflow/utils/validations/Validations.java | 17 ++++++++++++++++- .../skyflow/vault/tokens/TokenizeRequest.java | 2 +- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index f24a8e82..24d2e701 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -6,12 +6,14 @@ import com.skyflow.enums.Byot; import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.ColumnValue; import com.skyflow.vault.data.*; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; import java.util.ArrayList; import java.util.HashMap; +import java.util.List; public class Validations { @@ -184,8 +186,21 @@ public static void validateQueryRequest(QueryRequest queryRequest) throws Skyflo } } - public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) throws SkyflowException { + public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) throws SkyflowException { + List columnValues = tokenizeRequest.getColumnValues(); + if(columnValues == null || columnValues.isEmpty()) { + throw new SkyflowException(); + } else { + for(ColumnValue value : columnValues) { + if (value.getValue() == null || value.getValue().isEmpty() ) { + throw new SkyflowException(); + } + else if(value.getColumnGroup() == null || value.getColumnGroup().isEmpty()) { + throw new SkyflowException(); + } + } + } } private static void validateTokensForInsertRequest( diff --git a/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java b/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java index 7bfd8de0..92918814 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java @@ -27,7 +27,7 @@ public TokenizeRequestBuilder() { this.columnValues = new ArrayList<>(); } - public TokenizeRequestBuilder columnValues(List columnValues) { + public TokenizeRequestBuilder values(List columnValues) { this.columnValues = columnValues; return this; } From c4ad6c5ca8571ddfab5b07b6b37f56628a2f76b4 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Fri, 18 Oct 2024 15:04:56 +0530 Subject: [PATCH 028/126] SK-1666 validations for invoke connection request --- .../java/com/skyflow/enums/RequestMethod.java | 22 ++++++++ v2/src/main/java/com/skyflow/utils/Utils.java | 2 +- .../utils/validations/Validations.java | 36 +++++++++++++ .../controller/ConnectionController.java | 50 ++++++++++--------- .../skyflow/vault/tokens/TokenizeRequest.java | 2 +- 5 files changed, 87 insertions(+), 25 deletions(-) create mode 100644 v2/src/main/java/com/skyflow/enums/RequestMethod.java diff --git a/v2/src/main/java/com/skyflow/enums/RequestMethod.java b/v2/src/main/java/com/skyflow/enums/RequestMethod.java new file mode 100644 index 00000000..ffa3d949 --- /dev/null +++ b/v2/src/main/java/com/skyflow/enums/RequestMethod.java @@ -0,0 +1,22 @@ +package com.skyflow.enums; + +public enum RequestMethod { + GET("GET"), + POST("POST"), + PUT("PUT"), + PATCH("PATCH"), + DELETE("DELETE"), + ; + + private final String requestMethod; + + + RequestMethod(String requestMethod) { + this.requestMethod = requestMethod; + } + + @Override + public String toString() { + return requestMethod; + } +} diff --git a/v2/src/main/java/com/skyflow/utils/Utils.java b/v2/src/main/java/com/skyflow/utils/Utils.java index 0937083f..048f3c38 100644 --- a/v2/src/main/java/com/skyflow/utils/Utils.java +++ b/v2/src/main/java/com/skyflow/utils/Utils.java @@ -103,7 +103,7 @@ private static PrivateKey parsePkcs8PrivateKey(byte[] pkcs8Bytes) throws Skyflow } public static String constructConnectionURL(ConnectionConfig config, InvokeConnectionRequest invokeConnectionRequest) { - StringBuilder filledURL = new StringBuilder((String) config.getConnectionUrl()); + StringBuilder filledURL = new StringBuilder(config.getConnectionUrl()); if (invokeConnectionRequest.getPathParams() != null && !invokeConnectionRequest.getPathParams().isEmpty()) { for (Map.Entry entry : invokeConnectionRequest.getPathParams().entrySet()) { diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index 556e36f2..696deb27 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -3,11 +3,16 @@ import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; +import com.skyflow.enums.RequestMethod; +import com.skyflow.errors.ErrorCode; import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.connection.InvokeConnectionRequest; import com.skyflow.vault.data.*; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; +import java.net.URL; + // Add config and request validations public class Validations { @@ -19,6 +24,37 @@ public static void validateConnectionConfig(ConnectionConfig connectionConfig) t } + public static void validateInvokeConnectionRequest(InvokeConnectionRequest invokeConnectionRequest) throws SkyflowException { + if (invokeConnectionRequest.getRequestHeaders().containsKey("connectionURL")) { + String connectionURL = invokeConnectionRequest.getRequestHeaders().get("connectionURL"); + if (isInvalidURL(connectionURL)) { + throw new SkyflowException(); + } + } else { + throw new SkyflowException(); + } + + if (invokeConnectionRequest.getMethodName()!=null) { + try { + RequestMethod requestMethod = RequestMethod.valueOf(invokeConnectionRequest.getMethodName()); + } catch (Exception e) { + throw new SkyflowException(); + } + } else { + throw new SkyflowException(); + } + } + + private static boolean isInvalidURL(String configURL) { + try { + URL url = new URL(configURL); + if (!url.getProtocol().equals("https")) throw new Exception(); + } catch (Exception e) { + return true; + } + return false; + } + public static void validateCredentials(Credentials credentials) throws SkyflowException { int nonNullMembers = 0; if (credentials.getPath() != null) nonNullMembers++; diff --git a/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java b/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java index 74e91d29..d2e08977 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -19,6 +19,7 @@ import java.net.URL; import java.io.IOException; +import java.text.ParseException; import java.util.HashMap; import java.util.Map; @@ -49,33 +50,36 @@ public void setConnectionConfig(ConnectionConfig connectionConfig) { public InvokeConnectionResponse invoke(InvokeConnectionRequest invokeConnectionRequest) throws SkyflowException, IOException { InvokeConnectionResponse connectionResponse; - setBearerToken(); - String filledURL = Utils.constructConnectionURL(connectionConfig, invokeConnectionRequest); - Map headers = new HashMap<>(); - - if (invokeConnectionRequest.getRequestHeaders().containsKey("requestHeader")) { - headers = Utils.constructConnectionHeadersMap(invokeConnectionRequest.getRequestHeaders()); - } - if (!headers.containsKey("x-skyflow-authorization")) { - headers.put("x-skyflow-authorization", token); - } + try { + Validations.validateInvokeConnectionRequest(invokeConnectionRequest); + setBearerToken(); + String filledURL = Utils.constructConnectionURL(connectionConfig, invokeConnectionRequest); + Map headers = new HashMap<>(); + + if (invokeConnectionRequest.getRequestHeaders().containsKey("requestHeader")) { + headers = Utils.constructConnectionHeadersMap(invokeConnectionRequest.getRequestHeaders()); + } + if (!headers.containsKey("x-skyflow-authorization")) { + headers.put("x-skyflow-authorization", token); + } - String requestMethod = invokeConnectionRequest.getMethodName(); - JsonObject requestBody = null; - Object requestBodyObject = invokeConnectionRequest.getRequestBody(); + String requestMethod = invokeConnectionRequest.getMethodName(); + JsonObject requestBody = null; + Object requestBodyObject = invokeConnectionRequest.getRequestBody(); - if(requestBodyObject!=null) { - try { - requestBody = (JsonObject) convertObjectToJson(requestBodyObject); - System.out.println("Converted requestBody to JsonObject: " + requestBody.toString()); - } catch (Exception e) { - System.out.println("Error while converting requestBody to JsonObject: " + e.getMessage()); + if(requestBodyObject!=null) { + try { + requestBody = convertObjectToJson(requestBodyObject); + } catch (Exception e) { + throw new SkyflowException(); + } } - } - String response = HttpUtility.sendRequest(requestMethod, new URL(filledURL), requestBody, headers); -// connectionResponse = (JsonObject) new JsonParser().parse(response); - connectionResponse = new InvokeConnectionResponse((JsonObject) new JsonParser().parse(response)); + String response = HttpUtility.sendRequest(requestMethod, new URL(filledURL), requestBody, headers); + connectionResponse = new InvokeConnectionResponse((JsonObject) new JsonParser().parse(response)); + } catch (IOException e) { + throw new SkyflowException(); + } return connectionResponse; } diff --git a/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java b/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java index 7bfd8de0..f0540933 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java @@ -23,7 +23,7 @@ public List getColumnValues() { public static final class TokenizeRequestBuilder { private List columnValues; - public TokenizeRequestBuilder() { + private TokenizeRequestBuilder() { this.columnValues = new ArrayList<>(); } From b56f6efa1bd393390a4ebc7938ead791ab0f0843 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Fri, 18 Oct 2024 15:14:29 +0530 Subject: [PATCH 029/126] SK-1664 move ColumnValue class to tokens package --- v2/src/main/java/com/skyflow/VaultClient.java | 2 +- .../skyflow/{utils => vault/tokens}/ColumnValue.java | 11 ++--------- .../com/skyflow/vault/tokens/TokenizeRequest.java | 6 ++---- 3 files changed, 5 insertions(+), 14 deletions(-) rename v2/src/main/java/com/skyflow/{utils => vault/tokens}/ColumnValue.java (78%) diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/v2/src/main/java/com/skyflow/VaultClient.java index f465c2a4..52be5807 100644 --- a/v2/src/main/java/com/skyflow/VaultClient.java +++ b/v2/src/main/java/com/skyflow/VaultClient.java @@ -7,7 +7,7 @@ import com.skyflow.generated.rest.api.RecordsApi; import com.skyflow.generated.rest.api.TokensApi; import com.skyflow.generated.rest.models.*; -import com.skyflow.utils.ColumnValue; +import com.skyflow.vault.tokens.ColumnValue; import com.skyflow.utils.Utils; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.UpdateRequest; diff --git a/v2/src/main/java/com/skyflow/utils/ColumnValue.java b/v2/src/main/java/com/skyflow/vault/tokens/ColumnValue.java similarity index 78% rename from v2/src/main/java/com/skyflow/utils/ColumnValue.java rename to v2/src/main/java/com/skyflow/vault/tokens/ColumnValue.java index a7f416c9..3fa08b2e 100644 --- a/v2/src/main/java/com/skyflow/utils/ColumnValue.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/ColumnValue.java @@ -1,9 +1,4 @@ -package com.skyflow.utils; - -import com.skyflow.enums.RedactionType; -import com.skyflow.vault.tokens.DetokenizeRequest; - -import java.util.ArrayList; +package com.skyflow.vault.tokens; public class ColumnValue { @@ -29,9 +24,7 @@ public static final class ColumnValueBuilder { private String value; private String columnGroup; - public ColumnValueBuilder() { - this.value = ""; - this.columnGroup = ""; + private ColumnValueBuilder() { } public ColumnValueBuilder value(String value) { diff --git a/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java b/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java index 7bfd8de0..f7570714 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java @@ -1,7 +1,5 @@ package com.skyflow.vault.tokens; -import com.skyflow.utils.ColumnValue; - import java.util.ArrayList; import java.util.List; @@ -23,11 +21,11 @@ public List getColumnValues() { public static final class TokenizeRequestBuilder { private List columnValues; - public TokenizeRequestBuilder() { + private TokenizeRequestBuilder() { this.columnValues = new ArrayList<>(); } - public TokenizeRequestBuilder columnValues(List columnValues) { + public TokenizeRequestBuilder values(List columnValues) { this.columnValues = columnValues; return this; } From b08a5353dd456e9532b1d78c8ddeb355d62b8bf0 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 18 Oct 2024 21:08:29 +0530 Subject: [PATCH 030/126] SK-1664 Implement vault API interfaces - Change builder pattern implementation for vault API interfaces --- .../com/skyflow/vault/data/DeleteRequest.java | 12 ++--- .../com/skyflow/vault/data/GetRequest.java | 48 ++++++------------- .../com/skyflow/vault/data/InsertRequest.java | 45 ++++++----------- .../com/skyflow/vault/data/QueryRequest.java | 8 ++-- .../com/skyflow/vault/data/UpdateRequest.java | 28 ++++------- 5 files changed, 46 insertions(+), 95 deletions(-) diff --git a/v2/src/main/java/com/skyflow/vault/data/DeleteRequest.java b/v2/src/main/java/com/skyflow/vault/data/DeleteRequest.java index 0bd11df8..d61c996f 100644 --- a/v2/src/main/java/com/skyflow/vault/data/DeleteRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/DeleteRequest.java @@ -3,12 +3,10 @@ import java.util.ArrayList; public class DeleteRequest { - private final String table; - private final ArrayList ids; + private final DeleteRequestBuilder builder; private DeleteRequest(DeleteRequestBuilder builder) { - this.table = builder.table; - this.ids = builder.ids; + this.builder = builder; } public static DeleteRequestBuilder builder() { @@ -16,14 +14,14 @@ public static DeleteRequestBuilder builder() { } public String getTable() { - return table; + return this.builder.table; } public ArrayList getIds() { - return ids; + return this.builder.ids; } - public static class DeleteRequestBuilder { + public static final class DeleteRequestBuilder { private String table; private ArrayList ids; diff --git a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java index 862bfa03..28c0e567 100644 --- a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java @@ -7,30 +7,10 @@ import java.util.List; public class GetRequest { - private final String table; - private final ArrayList ids; - private final RedactionType redactionType; - private final Boolean tokenization; - private final List fields; - private final String offset; - private final String limit; - private final Boolean downloadURL; - private final String columnName; - private final ArrayList columnValues; - private final String orderBy; + private final GetRequestBuilder builder; private GetRequest(GetRequestBuilder builder) { - this.table = builder.table; - this.ids = builder.ids; - this.redactionType = builder.redactionType; - this.tokenization = builder.tokenization; - this.fields = builder.fields; - this.offset = builder.offset; - this.limit = builder.limit; - this.downloadURL = builder.downloadURL; - this.columnName = builder.columnName; - this.columnValues = builder.columnValues; - this.orderBy = builder.orderBy; + this.builder = builder; } public static GetRequestBuilder builder() { @@ -38,50 +18,50 @@ public static GetRequestBuilder builder() { } public String getTable() { - return table; + return this.builder.table; } public ArrayList getIds() { - return ids; + return this.builder.ids; } public RedactionType getRedactionType() { - return redactionType; + return this.builder.redactionType; } public Boolean getTokenization() { - return tokenization; + return this.builder.tokenization; } public List getFields() { - return fields; + return this.builder.fields; } public String getOffset() { - return offset; + return this.builder.offset; } public String getLimit() { - return limit; + return this.builder.limit; } public Boolean getDownloadURL() { - return downloadURL; + return this.builder.downloadURL; } public String getColumnName() { - return columnName; + return this.builder.columnName; } public ArrayList getColumnValues() { - return columnValues; + return this.builder.columnValues; } public String getOrderBy() { - return orderBy; + return this.builder.orderBy; } - public static class GetRequestBuilder { + public static final class GetRequestBuilder { private String table; private ArrayList ids; private RedactionType redactionType; diff --git a/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java b/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java index 8cdc22bc..b2a49f1b 100644 --- a/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java @@ -6,26 +6,10 @@ import java.util.HashMap; public class InsertRequest { - private final String table; - private final ArrayList> values; - private final ArrayList> tokens; - private final Boolean returnTokens; - private final String upsert; - private final Boolean homogeneous; - private final Boolean tokenMode; - private final Boolean continueOnError; - private final Byot tokenStrict; + private final InsertRequestBuilder builder; private InsertRequest(InsertRequestBuilder builder) { - this.table = builder.table; - this.values = builder.values; - this.tokens = builder.tokens; - this.returnTokens = builder.returnTokens; - this.upsert = builder.upsert; - this.homogeneous = builder.homogeneous; - this.tokenMode = builder.tokenMode; - this.continueOnError = builder.continueOnError; - this.tokenStrict = builder.tokenStrict; + this.builder = builder; } public static InsertRequestBuilder builder() { @@ -33,39 +17,39 @@ public static InsertRequestBuilder builder() { } public String getTable() { - return table; + return this.builder.table; } public ArrayList> getValues() { - return this.values; + return this.builder.values; } public ArrayList> getTokens() { - return this.tokens; + return this.builder.tokens; } public Boolean getReturnTokens() { - return returnTokens; + return this.builder.returnTokens; } public String getUpsert() { - return upsert; + return this.builder.upsert; } public Boolean getHomogeneous() { - return homogeneous; + return this.builder.homogeneous; } public Boolean getTokenMode() { - return tokenMode; + return this.builder.tokenMode; } public Boolean getContinueOnError() { - return continueOnError; + return this.builder.continueOnError; } public Byot getTokenStrict() { - return tokenStrict; + return this.builder.tokenStrict; } public static final class InsertRequestBuilder { @@ -81,8 +65,7 @@ public static final class InsertRequestBuilder { private InsertRequestBuilder() { this.returnTokens = true; - this.homogeneous = true; - this.tokenMode = true; + this.tokenMode = false; this.continueOnError = false; this.tokenStrict = Byot.DISABLE; } @@ -113,12 +96,12 @@ public InsertRequestBuilder upsert(String upsert) { } public InsertRequestBuilder homogeneous(Boolean homogeneous) { - this.homogeneous = homogeneous == null || homogeneous; + this.homogeneous = homogeneous; return this; } public InsertRequestBuilder tokenMode(Boolean tokenMode) { - this.tokenMode = tokenMode == null || tokenMode; + this.tokenMode = tokenMode != null && tokenMode; return this; } diff --git a/v2/src/main/java/com/skyflow/vault/data/QueryRequest.java b/v2/src/main/java/com/skyflow/vault/data/QueryRequest.java index 58c0c54d..2aaa200d 100644 --- a/v2/src/main/java/com/skyflow/vault/data/QueryRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/QueryRequest.java @@ -1,10 +1,10 @@ package com.skyflow.vault.data; public class QueryRequest { - private final String query; + private final QueryRequestBuilder builder; private QueryRequest(QueryRequestBuilder builder) { - this.query = builder.query; + this.builder = builder; } public static QueryRequestBuilder builder() { @@ -12,10 +12,10 @@ public static QueryRequestBuilder builder() { } public String getQuery() { - return query; + return this.builder.query; } - public static class QueryRequestBuilder { + public static final class QueryRequestBuilder { private String query; private QueryRequestBuilder() { diff --git a/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java b/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java index 7bda90dd..76c1c4b5 100644 --- a/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java @@ -5,20 +5,10 @@ import java.util.HashMap; public class UpdateRequest { - private final String table; - private final String id; - private final Boolean returnTokens; - private final HashMap values; - private final HashMap tokens; - private final Byot tokenStrict; + private final UpdateRequestBuilder builder; private UpdateRequest(UpdateRequestBuilder builder) { - this.table = builder.table; - this.id = builder.id; - this.returnTokens = builder.returnTokens; - this.values = builder.values; - this.tokens = builder.tokens; - this.tokenStrict = builder.tokenStrict; + this.builder = builder; } public static UpdateRequestBuilder builder() { @@ -26,30 +16,30 @@ public static UpdateRequestBuilder builder() { } public String getTable() { - return table; + return this.builder.table; } public String getId() { - return id; + return this.builder.id; } public Boolean getReturnTokens() { - return returnTokens; + return this.builder.returnTokens; } public HashMap getValues() { - return values; + return this.builder.values; } public HashMap getTokens() { - return tokens; + return this.builder.tokens; } public Byot getTokenStrict() { - return tokenStrict; + return this.builder.tokenStrict; } - public static class UpdateRequestBuilder { + public static final class UpdateRequestBuilder { private String table; private String id; private Boolean returnTokens; From c6c282c0a942d61316f21d0bd7d7122a1572a2b1 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 22 Oct 2024 12:14:30 +0530 Subject: [PATCH 031/126] SK-1682 add error codes, messages and logs --- .../java/com/skyflow/errors/ErrorCode.java | 115 ++++++++++++++++++ .../main/java/com/skyflow/logs/ErrorLogs.java | 49 ++++++++ 2 files changed, 164 insertions(+) create mode 100644 v2/src/main/java/com/skyflow/errors/ErrorCode.java create mode 100644 v2/src/main/java/com/skyflow/logs/ErrorLogs.java diff --git a/v2/src/main/java/com/skyflow/errors/ErrorCode.java b/v2/src/main/java/com/skyflow/errors/ErrorCode.java new file mode 100644 index 00000000..73a3bec2 --- /dev/null +++ b/v2/src/main/java/com/skyflow/errors/ErrorCode.java @@ -0,0 +1,115 @@ +/* + Copyright (c) 2022 Skyflow, Inc. +*/ +package com.skyflow.errors; + +public enum ErrorCode { + + InvalidCredentialFilePath(400, "{Language} SDK v{semver} Initialization failed. Invalid credentials. Specify the file path as a string."), + EmptyCredentialFilePath(400, "{Language} SDK v{semver} Initialization failed. Invalid credentials. Specify a valid file path."), + InvalidRolesKeyType(4000, "{Language} SDK v{semver} Initialization failed. Invalid roles. Specify roles as an array."), + InvalidRoleType(400, "{Language} SDK v{semver} Initialization failed. Invalid role. Specify the role as a string."), + EmptyRoles(400, "{Language} SDK v{semver} Initialization failed. Invalid roles. Specify at least one role."), + EmptyRoleInRoles(400, "{Language} SDK v{semver} Initialization failed. Invalid role. Specify a valid role."), + InvalidContext(400, "{Language} SDK v{semver} Initialization failed. Invalid context provided. Specify context as type Context."), + EmptyContext(400, "{Language} SDK v{semver} Initialization failed. Invalid context. Specify a valid context."), + InvalidCredentialsString(400, "{Language} SDK v{semver} Initialization failed. Invalid credentials. Specify credentials as a string."), + EmptyCredentialsString(400, "{Language} SDK v{semver} Initialization failed. Invalid credentials. Specify valid credentials."), + EmptyVaultId(400, "{Language} SDK v{semver} Initialization failed. Invalid vault ID. Specify a valid vault ID."), + InvalidVaultId(400, "{Language} SDK v{semver} Initialization failed. Invalid vault ID. Specify a valid vault ID as a string."), + InvalidClusterId(400, "{Language} SDK v{semver} Initialization failed. Invalid cluster ID. Specify cluster ID as a string."), + EmptyClusterId(400, "{Language} SDK v{semver} Initialization failed. Invalid cluster ID. Specify a valid cluster ID."), + InvalidConnectionId(400, "{Language} SDK v{semver} Initialization failed. Invalid connection ID. Specify connection ID as a string."), + EmptyConnectionId(400, "{Language} SDK v{semver} Initialization failed. Invalid connection ID. Specify a valid connection ID."), + InvalidConnectionUrl(400, "{Language} SDK v{semver} Initialization failed. Invalid connection URL. Specify connection URL as a string."), + EmptyConnectionUrl(400, "{Language} SDK v{semver} Initialization failed. Invalid connection URL. Specify a valid connection URL."), + TokenProviderError(400, "{Language} SDK v{semver} Initialization failed. Invalid token provider. Specify the token provider as a function."), + TokenProviderInvalidToken(400, "{Language} SDK v{semver} Initialization failed. Invalid token. Verify the output of the token provider."), + FileNotFound(400, "{Language} SDK v{semver} Initialization failed. Credential file not found at %s1. Verify the file path."), + FileInvalidJson(400, "{Language} SDK v{semver} Initialization failed. File at %s1 is not in valid JSON format. Verify the file contents."), + InvalidCredentials(400, "{Language} SDK v{semver} Initialization failed. Invalid credentials provided. Specify valid credentials."), + InvalidUrl(400, "{Language} SDK v{semver} Initialization failed. Vault URL %s1 is invalid. Specify a valid vault URL."), + MissingPrivateKey(400, "{Language} SDK v{semver} Initialization failed. Unable to read private key in credentials. Verify your private key."), + MissingClientId(400, "{Language} SDK v{semver} Initialization failed. Unable to read client ID in credentials. Verify your client ID."), + MissingKeyId(400, "{Language} SDK v{semver} Initialization failed. Unable to read key ID in credentials. Verify your key ID."), + MissingTokenUri(400, "{Language} SDK v{semver} Initialization failed. Unable to read token URI in credentials. Verify your token URI."), + JwtInvalidFormat(400, "{Language} SDK v{semver} Initialization failed. Invalid private key format. Verify your credentials."), + MissingAccessToken(400, "{Language} SDK v{semver} Validation error. Access token not present in the response from bearer token generation. Verify your credentials."), + MissingTokenType(400, "{Language} SDK v{semver} Validation error. Token type not present in the response from bearer token generation. Verify your credentials."), + JwtDecodeError(400, "{Language} SDK v{semver} Validation error. Invalid access token. Verify your credentials."), + VaultIdNotInConfigList(400, "{Language} SDK v{semver} Validation error. VaultId is missing from the config. Specify the vaultIds from configs."), + ConnectionIdNotInConfigList(400, "{Language} SDK v{semver} Validation error. ConnectionId is missing from the config. Specify the connectionIds from configs."), + EmptyCredentials(400, "{Language} SDK v{semver} Validation error. Invalid credentials. Specify a valid credentials."), + EmptyDataTokens(400, "{Language} SDK v{semver} Validation error. Invalid data tokens. Specify valid data tokens."), + DataTokenKeyType(400, "{Language} SDK v{semver} Validation error. Invalid data tokens. Specify data token as an string array."), + TimeToLeaveKeyType(400, "{Language} SDK v{semver} Validation error. Invalid time to live. Specify time to live parameter as an string."), + + //delete interface + InvalidIdTypeDelete(400, "{Language} SDK v{semver} Validation error. Invalid 'id' in 'records' array at index %s1 in records array. Specify 'id' as a string."), + EmptyRecordsInDelete(400, "{Language} SDK v{semver} Validation error. 'records' array can't be empty. Specify one or more records."), + EmptyIDInDelete(400, "{Language} SDK v{semver} Validation error. 'id' can't be empty in the 'records' array. Specify an ID."), + EmptyTableInDelete(400, "{Language} SDK v{semver} Validation error. 'table' can't be empty in the 'records' array. Specify a table."), + + //get interface + InvalidIdsType(400, "{Language} SDK v{semver} Validation error. 'ids' has a value of type %s1. Specify 'ids' as list."), + InvalidIdType(400, "{Language} SDK v{semver} Validation error. 'id' has a value of type %s1. Specify 'id' as string."), + InvalidRedactionType(400, "{Language} SDK v{semver} Validation error. Redaction key has value of type %s1, expected Skyflow.Redaction."), + InvalidColumnName(400, "{Language} SDK v{semver} Validation error. Column name has value of type %s1, expected a string."), + InvalidColumnValue(400, "{Language} SDK v{semver} Validation error. Column values has value of type %s1, expected a list."), + + //connection + InvalidPathParams(400, "{Language} SDK v{semver} Validation error. Path parameters aren't valid. Specify valid path parameters."), + EmptyPathParams(400, "{Language} SDK v{semver} Validation error. Path parameters are empty. Specify valid path parameters."), + InvalidRequestBody(400, "{Language} SDK v{semver} Validation error. Invalid request body. Specify the request body as an object."), + EmptyRequestBody(400, "{Language} SDK v{semver} Validation error. Request body can't be empty. Specify a valid request body."), + + //insert + RecordsKeyError(400, "{Language} SDK v{semver} Validation error. 'records' key is missing from the payload. Specify a 'records' key."), + FieldsKeyError(400, "{Language} SDK v{semver} Validation error. 'fields' key is missing from the payload. Specify a 'fields' key."), + TableKeyError(400, "{Language} SDK v{semver} Validation error. 'table' key is missing from the payload. Specify a 'table' key."), + TokenKeyError(400, "{Language} SDK v{semver} Validation error. 'token' key is missing from the payload. Specify a 'token' key."), + IdsKeyError(400, "{Language} SDK v{semver} Validation error. 'ids' key is missing from the payload. Specify an 'ids' key."), + RedactionKeyError(400, "{Language} SDK v{semver} Validation error. 'redaction' key is missing from the payload. Specify a 'redaction' key."), + UniqueColumnOrIdsKeyError(400, "{Language} SDK v{semver} Validation error. ids or columnName key is missing from the payload. Specify the ids or unique 'columnName' in payload."), + UpdateFieldKeyError(400, "{Language} SDK v{semver} Validation error. Fields are empty in an update payload. Specify at least one field."), + InvalidRecordsType(400, "{Language} SDK v{semver} Validation error. The 'records' key has a value of type %s1. Specify 'records' as a list."), + InvalidFieldsType(400, "{Language} SDK v{semver} Validation error. The 'fields' key has a value of type %s1. Specify 'fields' as a dictionary."), + InvalidTokensType(400, "{Language} SDK v{semver} Validation error. The 'tokens' key has a value of type %s1. Specify 'tokens' as a dictionary."), + EmptyTokensInInsert(400, "{Language} SDK v{semver} Validation error. The 'tokens' field is empty. Specify tokens for one or more fields."), + MismatchOfFieldsAndTokens(400, "{Language} SDK v{semver} Validation error. 'fields' and 'tokens' have different columns names. Verify that 'fields' and 'tokens' columns match."), + InvalidTableType(400, "{Language} SDK v{semver} Validation error. The 'table' key has a value of type %s1. Specify 'table' as a string."), + RedactionWithTokensNotSupported(400, "{Language} SDK v{semver} Validation error. 'redaction' can't be used when tokens are specified. Remove 'redaction' from payload if tokens are specified."), + TokensGetColumnNotSupported(400, "{Language} SDK v{semver} Validation error. Column name and/or column values can't be used when tokens are specified. Remove unique column values or tokens from the payload."), + BothIdsAndColumnDetailsSpecified(400, "{Language} SDK v{semver} Validation error. Both Skyflow IDs and column details can't be specified. Either specify Skyflow IDs or unique column details."), + PartialSuccess(400, "{Language} SDK v{semver} Validation error. Check 'SkyflowError.data' for details."), + InvalidUpsertOptionsType(400, "{Language} SDK v{semver} Validation error. 'upsert' key cannot be empty in options. At least one object of table and column is required."), + InvalidUpsertTableType(400, "{Language} SDK v{semver} Validation error. The 'table' key in the 'upsert' object has avalue of type %s1. Specify 'table' as a string."), + InvalidUpsertColumnType(400, "{Language} SDK v{semver} Validation error. The 'column' key in the 'upsert' object has a value of type %s1. Specify 'column' as a string."), + EmptyUpsertOptionTable(400, "{Language} SDK v{semver} Validation error. The 'table' key in the 'upsert' object can't be an empty string. Specify a 'table' value."), + EmptyUpsertOptionColumn(400, "{Language} SDK v{semver} Validation error. The 'column' key in the 'upsert' object can't be an empty string. Specify a 'column' value."), + BatchInsertPartialSuccess(400, "{Language} SDK v{semver} Insert operation completed with partial success."), + BatchInsertFailure(400, "{Language} SDK v{semver} Insert operation failed."), + InvalidByotType(400, "{Language} SDK v{semver} Validation error. The 'byot' key has a value of type %s1. Specify 'byot' as Skyflow.BYOT."), + NoTokensInInsert(400, "{Language} SDK v{semver} Validation error. Tokens weren't specified for records while 'byot' was %s1. Specify tokens."), + TokensPassedForByotDisable(400, "{Language} SDK v{semver} Validation error. 'byot' wasn't specified. Set 'byot' to 'ENABLE' to insert tokens."), + InsufficientTokensPassedForByotEnableStrict(400, "{Language} SDK v{semver} Validation error. 'byot' is set to 'ENABLE_STRICT', but some fields are missing tokens. Specify tokens for all fields."); + + + + private final int code; + private final String message; + + ErrorCode(int code, String message) { + this.code = code; + this.message = message; + } + + public int getCode() { + return code; + } + + public String getMessage() { + return message; + } + +} diff --git a/v2/src/main/java/com/skyflow/logs/ErrorLogs.java b/v2/src/main/java/com/skyflow/logs/ErrorLogs.java new file mode 100644 index 00000000..b776f314 --- /dev/null +++ b/v2/src/main/java/com/skyflow/logs/ErrorLogs.java @@ -0,0 +1,49 @@ +package com.skyflow.logs; + +public enum ErrorLogs { + ClientConnetion(""), + VaultIdIsRequired("Interface: init - Invalid client credentials. vaultID is required."), + EmptyVaultIdInInit("Interface: init - Invalid client credentials. vaultID cannot be empty."), + VaultUrlIsRequired("Interface: init - Invalid client credentials. vaultURL is required."), + EmptyVaultUrlInInit("Interface: init - Invalid client credentials. vaultURL cannot be empty."), + InvalidVaultUrlInInit("Interface: init - Invalid client credentials. Expecting https://XYZ for vaultURL"), + GetBearerTokenIsRequired("Interface: init - Invalid client credentials. getBearerToken is required."), + BearerTokenRejected(""), + InvalidEncodeUriInGet("Interface: get method - Invalid encodeURI type in get."), + InvalidBearerToken("Bearer token is invalid or expired."), + InvalidVaultId("Vault Id is invalid or cannot be found."), + EmptyVaultId("VaultID is empty"), + InvalidCredentials("Invalid client credentials."), + InvalidContainerType("Invalid container type."), + InvalidCollectValue("Invalid value"), + InvalidCollectValueWithLabel("Invalid %s1"), + RecordsKeyNotFound("records object key value not found."), + EmptyRecords("records object is empty."), + RecordsKeyError("Key “records” is missing or payload is incorrectly formatted."), + MissingRecords(""), + InvalidRecords("Invalid Records"), + EmptyRecordIds(""), + EmptyRecordColumnvalues("Record column values cannot be empty."), + InvalidRecordIdType("Invalid Type of Records Id."), + InvalidRecordColumnValueType(""), + InvalidRecordLabel("Invalid Record Label Type."), + InvalidRecordAltText("Invalid Record altText Type."), + FetchRecordsRejected(""), + InsertRecordsRejected(""), + GetBySkyflowIdRejected(""), + SendInvokeConnectionRejected("Invoke connection request rejected."), + UpdateRequestRejected("Update request is rejected."), + InvalidTableName("Table Name passed doesn’t exist in the vault with id."), + EmptyTableName("Table Name is empty."), + EmptyTableAndFields("table or fields parameter cannot be passed as empty at index %s1 in records array."); + + private final String log; + + ErrorLogs(String log) { + this.log = log; + } + + public final String getLog() { + return log; + } +} From 27f7443d9e4f6bf427adc7e57b60e99cb2ec92f6 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 23 Oct 2024 18:42:10 +0530 Subject: [PATCH 032/126] SK-1681 Add validations --- v2/src/main/java/com/skyflow/Skyflow.java | 27 +-- .../main/java/com/skyflow/enums/LogLevel.java | 6 +- .../utils/validations/Validations.java | 165 +++++++++++++++--- .../vault/controller/VaultController.java | 2 +- .../com/skyflow/vault/data/GetRequest.java | 18 +- .../vault/tokens/DetokenizeRequest.java | 2 +- 6 files changed, 166 insertions(+), 54 deletions(-) diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/v2/src/main/java/com/skyflow/Skyflow.java index 6c08644e..6fe84ad9 100644 --- a/v2/src/main/java/com/skyflow/Skyflow.java +++ b/v2/src/main/java/com/skyflow/Skyflow.java @@ -6,6 +6,8 @@ import com.skyflow.enums.Env; import com.skyflow.enums.LogLevel; import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.LogUtil; +import com.skyflow.utils.validations.Validations; import com.skyflow.vault.controller.ConnectionController; import com.skyflow.vault.controller.VaultController; @@ -28,7 +30,6 @@ public Skyflow addVaultConfig(VaultConfig vaultConfig) throws SkyflowException { } public VaultConfig getVaultConfig(String vaultId) { - // get vault config with vault id return this.builder.vaultConfigMap.get(vaultId); } @@ -48,7 +49,6 @@ public Skyflow addConnectionConfig(ConnectionConfig connectionConfig) { } public ConnectionConfig getConnectionConfig(String connectionId) { - // get connection config with connection id return this.builder.connectionsMap.get(connectionId).getConnectionConfig(); } @@ -62,7 +62,7 @@ public Skyflow removeConnectionConfig(String connectionId) { return this; } - public Skyflow updateSkyflowCredentials(Credentials credentials) { + public Skyflow updateSkyflowCredentials(Credentials credentials) throws SkyflowException { this.builder.addSkyflowCredentials(credentials); return this; } @@ -76,7 +76,6 @@ public LogLevel getLogLevel() { return this.builder.logLevel; } - // in case no id is passed, return first vault controller public VaultController vault() { String vaultId = (String) this.builder.vaultClientsMap.keySet().toArray()[0]; return this.vault(vaultId); @@ -86,7 +85,7 @@ public VaultController vault(String vaultId) { return this.builder.vaultClientsMap.get(vaultId); } - // in case no id is passed, return first connection controller + // In case no id is passed, return first connection controller public ConnectionController connection() { String connectionId = (String) this.builder.connectionsMap.keySet().toArray()[0]; return this.connection(connectionId); @@ -112,9 +111,10 @@ public SkyflowClientBuilder() { } public SkyflowClientBuilder addVaultConfig(VaultConfig vaultConfig) throws SkyflowException { - // check if vaultConfig already exists + Validations.validateVaultConfig(vaultConfig); if (this.vaultClientsMap.containsKey(vaultConfig.getVaultId())) { // display error log, throw error, or both + throw new SkyflowException(); } else { this.vaultConfigMap.put(vaultConfig.getVaultId(), vaultConfig); this.vaultClientsMap.put(vaultConfig.getVaultId(), new VaultController(vaultConfig, this.skyflowCredentials)); @@ -128,6 +128,7 @@ public SkyflowClientBuilder updateVaultConfig(VaultConfig vaultConfig) throws Sk this.vaultClientsMap.get(updatedConfig.getVaultId()).updateVaultConfig(); } else { // display error log, throw error, or both + throw new SkyflowException(); } return this; } @@ -138,6 +139,7 @@ public SkyflowClientBuilder removeVaultConfig(String vaultId) throws SkyflowExce this.vaultConfigMap.remove(vaultId); } else { // display error log, throw error, or both + throw new SkyflowException(); } return this; } @@ -172,32 +174,33 @@ public SkyflowClientBuilder removeConnectionConfig(String connectionId) { return this; } - public SkyflowClientBuilder addSkyflowCredentials(Credentials credentials) { - // set credentials and update in vault controllers + public SkyflowClientBuilder addSkyflowCredentials(Credentials credentials) throws SkyflowException { + Validations.validateCredentials(credentials); this.skyflowCredentials = credentials; for (VaultController vault : this.vaultClientsMap.values()) { vault.setCommonCredentials(this.skyflowCredentials); } - for (ConnectionController controller : this.connectionsMap.values()) { - controller.setCommonCredentials(this.skyflowCredentials); + for (ConnectionController connection : this.connectionsMap.values()) { + connection.setCommonCredentials(this.skyflowCredentials); } return this; } public SkyflowClientBuilder setLogLevel(LogLevel logLevel) { this.logLevel = logLevel; + LogUtil.setupLogger(logLevel); return this; } public Skyflow build() { - // return built skyflow client instance return new Skyflow(this); } - private VaultConfig findAndUpdateVaultConfig(VaultConfig vaultConfig) { + private VaultConfig findAndUpdateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { VaultConfig previousConfig = this.vaultConfigMap.get(vaultConfig.getVaultId()); if (previousConfig == null) { // display error log, throw error, or both + throw new SkyflowException(); } else { Env env = vaultConfig.getEnv() != null ? vaultConfig.getEnv() : previousConfig.getEnv(); String clusterId = vaultConfig.getClusterId() != null ? vaultConfig.getClusterId() : previousConfig.getClusterId(); diff --git a/v2/src/main/java/com/skyflow/enums/LogLevel.java b/v2/src/main/java/com/skyflow/enums/LogLevel.java index 7b86db3a..a605b520 100644 --- a/v2/src/main/java/com/skyflow/enums/LogLevel.java +++ b/v2/src/main/java/com/skyflow/enums/LogLevel.java @@ -1,9 +1,9 @@ package com.skyflow.enums; public enum LogLevel { + OFF, ERROR, - WARNING, + WARN, INFO, - DEBUG, - OFF + DEBUG } diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index 24d2e701..586631f9 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -4,6 +4,7 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; import com.skyflow.enums.Byot; +import com.skyflow.enums.Env; import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; import com.skyflow.utils.ColumnValue; @@ -11,6 +12,8 @@ import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; +import java.net.MalformedURLException; +import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -20,10 +23,23 @@ public class Validations { public static void validateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { String vaultId = vaultConfig.getVaultId(); String clusterId = vaultConfig.getClusterId(); + Env env = vaultConfig.getEnv(); + Credentials credentials = vaultConfig.getCredentials(); if (vaultId == null || vaultId.trim().isEmpty()) { + if (vaultId == null) { + // error log for required + } else { + // error log for empty + } throw new SkyflowException(); } else if (clusterId == null || clusterId.trim().isEmpty()) { + // error log throw new SkyflowException(); + } else if (env == null) { + // error log + throw new SkyflowException(); + } else if (credentials != null) { + validateCredentials(credentials); } } @@ -35,6 +51,12 @@ public static void validateConnectionConfig(ConnectionConfig connectionConfig) t } else if (connectionUrl == null || connectionUrl.trim().isEmpty()) { throw new SkyflowException(); } + + try { + URL url = new URL(connectionUrl); + } catch (MalformedURLException e) { + throw new SkyflowException(); + } } public static void validateCredentials(Credentials credentials) throws SkyflowException { @@ -59,7 +81,8 @@ public static void validateDetokenizeRequest(DetokenizeRequest detokenizeRequest } else if (redactionType == null) { throw new SkyflowException(); } else { - for (String token : tokens) { + for (int index = 0; index < tokens.size(); index++) { + String token = tokens.get(index); if (token == null || token.trim().isEmpty()) { throw new SkyflowException(); } @@ -71,20 +94,25 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky String table = insertRequest.getTable(); ArrayList> values = insertRequest.getValues(); ArrayList> tokens = insertRequest.getTokens(); - Boolean returnTokens = insertRequest.getReturnTokens(); String upsert = insertRequest.getUpsert(); Boolean homogeneous = insertRequest.getHomogeneous(); - Boolean tokenMode = insertRequest.getTokenMode(); Byot tokenStrict = insertRequest.getTokenStrict(); if (table == null || table.trim().isEmpty()) { + if (table == null) { + // error log for required + } else { + // error log for empty + } throw new SkyflowException(); } else if (values == null || values.isEmpty()) { throw new SkyflowException(); - } else if (upsert != null && upsert.trim().isEmpty()) { - throw new SkyflowException(); - } else if (homogeneous != null && homogeneous) { - throw new SkyflowException(); + } else if (upsert != null) { + if (upsert.trim().isEmpty()) { + throw new SkyflowException(); + } else if (homogeneous != null && homogeneous) { + throw new SkyflowException(); + } } for (HashMap valuesMap : values) { @@ -105,20 +133,102 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky if (tokens != null) { throw new SkyflowException(); } + break; case ENABLE: if (tokens == null) { throw new SkyflowException(); } + validateTokensForInsertRequest(tokens, values); + break; case ENABLE_STRICT: - if (tokens.size() != values.size()) { + if (tokens == null) { + throw new SkyflowException(); + } else if (tokens.size() != values.size()) { throw new SkyflowException(); } + validateTokensForInsertRequest(tokens, values); + break; } - validateTokensForInsertRequest(tokens, values); - } public static void validateGetRequest(GetRequest getRequest) throws SkyflowException { + String table = getRequest.getTable(); + ArrayList ids = getRequest.getIds(); + RedactionType redactionType = getRequest.getRedactionType(); + Boolean tokenization = getRequest.getReturnTokens(); + List fields = getRequest.getFields(); + String offset = getRequest.getOffset(); + String limit = getRequest.getLimit(); + Boolean downloadURL = getRequest.getDownloadURL(); + String columnName = getRequest.getColumnName(); + ArrayList columnValues = getRequest.getColumnValues(); + String orderBy = getRequest.getOrderBy(); + + if (table == null || table.trim().isEmpty()) { + throw new SkyflowException(); + } else if (ids != null) { + if (ids.isEmpty()) { + throw new SkyflowException(); + } else { + for (int index = 0; index < ids.size(); index++) { + String id = ids.get(index); + if (id == null || id.trim().isEmpty()) { + throw new SkyflowException(); + } + } + } + } else if (fields != null) { + if (fields.isEmpty()) { + throw new SkyflowException(); + } else { + for (int index = 0; index < fields.size(); index++) { + String field = fields.get(index); + if (field == null || field.trim().isEmpty()) { + throw new SkyflowException(); + } + } + } + } else if (redactionType == null && (tokenization == null || !tokenization)) { + // missing redaction + throw new SkyflowException(); + } else if (tokenization != null && tokenization) { + if (redactionType != null) { + // redaction and tokenization does not work together + throw new SkyflowException(); + } else if (columnName != null || columnValues != null) { + // tokenization does not work with column name/values + throw new SkyflowException(); + } + } else if (offset != null && offset.isEmpty()) { + throw new SkyflowException(); + } else if (limit != null && limit.isEmpty()) { + throw new SkyflowException(); + } + + if (ids == null && columnName == null && columnValues == null) { + // either skyflow ids or column name/values must be passed + throw new SkyflowException(); + } else if (ids != null && (columnName != null || columnValues != null)) { + // skyflow ids and column name/values can not be passed together + throw new SkyflowException(); + } else if (columnName == null && columnValues != null) { + // column name and values must both be passed + throw new SkyflowException(); + } else if (columnName != null && columnValues == null) { + // column name and values must both be passed + throw new SkyflowException(); + } else if (columnName != null) { + if (columnValues.isEmpty()) { + throw new SkyflowException(); + } else { + for (int index = 0; index < columnValues.size(); index++) { + String columnValue = columnValues.get(index); + if (columnValue == null || columnValue.trim().isEmpty()) { + throw new SkyflowException(); + } + } + } + } } public static void validateUpdateRequest(UpdateRequest updateRequest) throws SkyflowException { @@ -136,26 +246,28 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky throw new SkyflowException(); } else if (values == null || values.isEmpty()) { throw new SkyflowException(); - } else if (tokens == null || tokens.isEmpty()) { - throw new SkyflowException(); - } - - for (String key : values.keySet()) { - if (key == null || key.trim().isEmpty()) { + } else if (tokens != null) { + if (tokens.isEmpty()) { throw new SkyflowException(); } else { - Object value = values.get(key); - if (value == null || value.toString().trim().isEmpty()) { - throw new SkyflowException(); + for (String key : tokens.keySet()) { + if (key == null || key.trim().isEmpty()) { + throw new SkyflowException(); + } else { + Object value = tokens.get(key); + if (value == null || value.toString().trim().isEmpty()) { + throw new SkyflowException(); + } + } } } } - for (String key : tokens.keySet()) { + for (String key : values.keySet()) { if (key == null || key.trim().isEmpty()) { throw new SkyflowException(); } else { - Object value = tokens.get(key); + Object value = values.get(key); if (value == null || value.toString().trim().isEmpty()) { throw new SkyflowException(); } @@ -186,17 +298,16 @@ public static void validateQueryRequest(QueryRequest queryRequest) throws Skyflo } } - public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) throws SkyflowException { + public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) throws SkyflowException { List columnValues = tokenizeRequest.getColumnValues(); - if(columnValues == null || columnValues.isEmpty()) { + if (columnValues == null || columnValues.isEmpty()) { throw new SkyflowException(); } else { - for(ColumnValue value : columnValues) { - if (value.getValue() == null || value.getValue().isEmpty() ) { + for (ColumnValue value : columnValues) { + if (value.getValue() == null || value.getValue().isEmpty()) { throw new SkyflowException(); - } - else if(value.getColumnGroup() == null || value.getColumnGroup().isEmpty()) { + } else if (value.getColumnGroup() == null || value.getColumnGroup().isEmpty()) { throw new SkyflowException(); } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index 69428bad..69abdcee 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -225,7 +225,7 @@ public GetResponse get(GetRequest getRequest) throws SkyflowException { getRequest.getTable(), getRequest.getIds(), redactionType != null ? redactionType.toString() : null, - getRequest.getTokenization(), + getRequest.getReturnTokens(), getRequest.getFields(), getRequest.getOffset(), getRequest.getLimit(), diff --git a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java index 38a62f50..96a976ce 100644 --- a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java @@ -10,7 +10,7 @@ public class GetRequest { private final String table; private final ArrayList ids; private final RedactionType redactionType; - private final Boolean tokenization; + private final Boolean returnTokens; private final List fields; private final String offset; private final String limit; @@ -23,7 +23,7 @@ private GetRequest(GetRequestBuilder builder) { this.table = builder.table; this.ids = builder.ids; this.redactionType = builder.redactionType; - this.tokenization = builder.tokenization; + this.returnTokens = builder.returnTokens; this.fields = builder.fields; this.offset = builder.offset; this.limit = builder.limit; @@ -49,8 +49,8 @@ public RedactionType getRedactionType() { return redactionType; } - public Boolean getTokenization() { - return tokenization; + public Boolean getReturnTokens() { + return returnTokens; } public List getFields() { @@ -85,7 +85,7 @@ public static class GetRequestBuilder { private String table; private ArrayList ids; private RedactionType redactionType; - private Boolean tokenization; + private Boolean returnTokens; private List fields; private String offset; private String limit; @@ -95,8 +95,6 @@ public static class GetRequestBuilder { private String orderBy; private GetRequestBuilder() { - this.redactionType = RedactionType.PLAIN_TEXT; - this.tokenization = false; this.downloadURL = true; this.orderBy = Constants.ORDER_ASCENDING; } @@ -112,12 +110,12 @@ public GetRequestBuilder ids(ArrayList ids) { } public GetRequestBuilder redactionType(RedactionType redactionType) { - this.redactionType = redactionType == null ? RedactionType.PLAIN_TEXT : redactionType; + this.redactionType = redactionType; return this; } - public GetRequestBuilder tokenization(Boolean tokenization) { - this.tokenization = tokenization != null && tokenization; + public GetRequestBuilder returnTokens(Boolean returnTokens) { + this.returnTokens = returnTokens; return this; } diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java index 5dac7b3a..8c80c932 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java @@ -43,7 +43,7 @@ public DetokenizeRequestBuilder tokens(ArrayList tokens) { } public DetokenizeRequestBuilder redactionType(RedactionType redactionType) { - this.redactionType = redactionType; + this.redactionType = redactionType == null ? RedactionType.PLAIN_TEXT : redactionType; return this; } From e8352ac8d5332d05bc71872a54c84eb2f11fcc3f Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 23 Oct 2024 21:14:14 +0530 Subject: [PATCH 033/126] SK-1678 Add support for using Api Key SK-1681 Add validations for Api Key --- .../java/com/skyflow/config/Credentials.java | 9 ++++ .../serviceaccount/util/BearerToken.java | 35 ++++++------ .../serviceaccount/util/SignedDataTokens.java | 54 +++++++++---------- .../java/com/skyflow/utils/Constants.java | 1 + v2/src/main/java/com/skyflow/utils/Utils.java | 4 +- .../utils/validations/Validations.java | 32 +++++++++-- 6 files changed, 87 insertions(+), 48 deletions(-) diff --git a/v2/src/main/java/com/skyflow/config/Credentials.java b/v2/src/main/java/com/skyflow/config/Credentials.java index 75130b90..8618ebb9 100644 --- a/v2/src/main/java/com/skyflow/config/Credentials.java +++ b/v2/src/main/java/com/skyflow/config/Credentials.java @@ -8,6 +8,7 @@ public class Credentials { private String context; private String credentialsString; private String token; + private String apiKey; public Credentials() { this.path = null; @@ -55,4 +56,12 @@ public String getToken() { public void setToken(String token) { this.token = token; } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } } diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java b/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java index 39c7733d..0b396dc5 100644 --- a/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java +++ b/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java @@ -1,5 +1,6 @@ package com.skyflow.serviceaccount.util; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; @@ -49,13 +50,13 @@ private static V1GetAuthTokenResponse generateBearerTokenFromCredentials( ) throws SkyflowException { try { if (credentialsFile == null || !credentialsFile.isFile()) { - throw new SkyflowException("credentials file is not a valid file."); + throw new SkyflowException(); } FileReader reader = new FileReader(String.valueOf(credentialsFile)); JsonObject serviceAccountCredentials = JsonParser.parseReader(reader).getAsJsonObject(); return getBearerTokenFromCredentials(serviceAccountCredentials, context, roles); } catch (JsonSyntaxException e) { - throw new SkyflowException("credentials string is not in valid json string format"); + throw new SkyflowException(); } catch (FileNotFoundException e) { throw new RuntimeException(e); } @@ -66,12 +67,12 @@ private static V1GetAuthTokenResponse generateBearerTokenFromCredentialString( ) throws SkyflowException { try { if (credentials == null || credentials.isEmpty()) { - throw new SkyflowException("credentials string cannot bt empty"); + throw new SkyflowException(); } JsonObject serviceAccountCredentials = JsonParser.parseString(credentials).getAsJsonObject(); return getBearerTokenFromCredentials(serviceAccountCredentials, context, roles); } catch (JsonSyntaxException e) { - throw new SkyflowException("credentials string is not in valid json string format"); + throw new SkyflowException(); } } @@ -79,30 +80,32 @@ private static V1GetAuthTokenResponse getBearerTokenFromCredentials( JsonObject credentials, String context, ArrayList roles ) throws SkyflowException { try { - String privateKey = credentials.get("privateKey").getAsString(); + JsonElement privateKey = credentials.get("privateKey"); if (privateKey == null) { - throw new SkyflowException("privateKey not found"); + throw new SkyflowException(); } - String clientID = credentials.get("clientID").getAsString(); + JsonElement clientID = credentials.get("clientID"); if (clientID == null) { - throw new SkyflowException("clientID not found"); + throw new SkyflowException(); } - String keyID = credentials.get("keyID").getAsString(); + JsonElement keyID = credentials.get("keyID"); if (keyID == null) { - throw new SkyflowException("keyID not found"); + throw new SkyflowException(); } - String tokenURI = credentials.get("tokenURI").getAsString(); + JsonElement tokenURI = credentials.get("tokenURI"); if (tokenURI == null) { - throw new SkyflowException("tokenURI not found"); + throw new SkyflowException(); } - PrivateKey pvtKey = Utils.getPrivateKeyFromPem(privateKey); - String signedUserJWT = getSignedToken(clientID, keyID, tokenURI, pvtKey, context); + PrivateKey pvtKey = Utils.getPrivateKeyFromPem(privateKey.getAsString()); + String signedUserJWT = getSignedToken( + clientID.getAsString(), keyID.getAsString(), tokenURI.getAsString(), pvtKey, context + ); - String basePath = Utils.getBaseURL(tokenURI); + String basePath = Utils.getBaseURL(tokenURI.getAsString()); apiClient.setBasePath(basePath); V1GetAuthTokenRequest body = new V1GetAuthTokenRequest(); @@ -115,7 +118,7 @@ private static V1GetAuthTokenResponse getBearerTokenFromCredentials( } return authenticationApi.authenticationServiceGetAuthToken(body); } catch (MalformedURLException e) { - throw new SkyflowException("Invalid value for tokenURI in credentials"); + throw new SkyflowException(); } catch (ApiException e) { throw new RuntimeException(e); } diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java b/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java index 482398b7..d5fe52bf 100644 --- a/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java +++ b/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java @@ -1,12 +1,13 @@ package com.skyflow.serviceaccount.util; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; import com.skyflow.errors.SkyflowException; import com.skyflow.utils.Utils; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; import java.io.File; import java.io.FileReader; @@ -39,22 +40,21 @@ public static SignedDataTokensBuilder builder() { } private static List generateSignedTokens( - File credentialsPath, ArrayList dataTokens, Integer timeToLive, String context + File credentialsFile, ArrayList dataTokens, Integer timeToLive, String context ) throws SkyflowException { // print info log - JSONParser parser = new JSONParser(); List responseToken; try { - if (credentialsPath == null || !credentialsPath.isFile()) { + if (credentialsFile == null || !credentialsFile.isFile()) { // print error log - throw new SkyflowException("credentials string cannot be empty"); + throw new SkyflowException(); } - Object obj = parser.parse(new FileReader(String.valueOf(credentialsPath))); - JSONObject serviceAccountCredentials = (JSONObject) obj; + FileReader reader = new FileReader(String.valueOf(credentialsFile)); + JsonObject serviceAccountCredentials = JsonParser.parseReader(reader).getAsJsonObject(); responseToken = getSignedTokenFromCredentialsFile(serviceAccountCredentials, dataTokens, timeToLive, context); - } catch (ParseException e) { + } catch (JsonSyntaxException e) { // print error log - throw new SkyflowException("credentials string is not in valid json string format"); + throw new SkyflowException(); } catch (IOException e) { throw new RuntimeException(e); } @@ -66,48 +66,46 @@ private static List generateSignedTokensFromCredentials String credentials, ArrayList dataTokens, Integer timeToLive, String context ) throws SkyflowException { // print info log - JSONParser parser = new JSONParser(); List responseToken; // print info log try { if (credentials == null || credentials.isEmpty()) { // print error log - throw new SkyflowException("credentials string cannot by empty"); + throw new SkyflowException(); } - Object obj = parser.parse(credentials); - JSONObject serviceAccountCredentials = (JSONObject) obj; + JsonObject serviceAccountCredentials = JsonParser.parseString(credentials).getAsJsonObject(); responseToken = getSignedTokenFromCredentialsFile(serviceAccountCredentials, dataTokens, timeToLive, context); - } catch (ParseException e) { + } catch (JsonSyntaxException e) { // print error log - throw new SkyflowException("credentials string is not in valid json string format"); + throw new SkyflowException(); } return responseToken; } private static List getSignedTokenFromCredentialsFile( - JSONObject credentials, ArrayList dataTokens, Integer timeToLive, String context + JsonObject credentials, ArrayList dataTokens, Integer timeToLive, String context ) throws SkyflowException { List signedDataTokens = null; try { - String privateKey = (String) credentials.get("privateKey"); + JsonElement privateKey = credentials.get("privateKey"); if (privateKey == null) { - throw new SkyflowException("privateKey not found"); + throw new SkyflowException(); } - String clientID = (String) credentials.get("clientID"); + JsonElement clientID = credentials.get("clientID"); if (clientID == null) { - // print error log - throw new SkyflowException("invalid clientID"); + throw new SkyflowException(); } - String keyID = (String) credentials.get("keyID"); + + JsonElement keyID = credentials.get("keyID"); if (keyID == null) { - // print error log - throw new SkyflowException("invalid KeyID"); + throw new SkyflowException(); } - PrivateKey pvtKey = Utils.getPrivateKeyFromPem(privateKey); - signedDataTokens = getSignedToken(clientID, keyID, pvtKey, dataTokens, timeToLive, context); + PrivateKey pvtKey = Utils.getPrivateKeyFromPem(privateKey.getAsString()); + signedDataTokens = getSignedToken( + clientID.getAsString(), keyID.getAsString(), pvtKey, dataTokens, timeToLive, context); } catch (RuntimeException e) { // throw error } diff --git a/v2/src/main/java/com/skyflow/utils/Constants.java b/v2/src/main/java/com/skyflow/utils/Constants.java index a88dc63b..e80e9b29 100644 --- a/v2/src/main/java/com/skyflow/utils/Constants.java +++ b/v2/src/main/java/com/skyflow/utils/Constants.java @@ -11,4 +11,5 @@ public final class Constants { public static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; public static final String SIGNED_DATA_TOKEN_PREFIX = "signed_token_"; public static final String ORDER_ASCENDING = "ASCENDING"; + public static final String API_KEY_REGEX = "^sky-[a-zA-Z0-9]{5}-[a-fA-F0-9]{32}$"; } diff --git a/v2/src/main/java/com/skyflow/utils/Utils.java b/v2/src/main/java/com/skyflow/utils/Utils.java index 51115bb0..7fbf0272 100644 --- a/v2/src/main/java/com/skyflow/utils/Utils.java +++ b/v2/src/main/java/com/skyflow/utils/Utils.java @@ -52,8 +52,10 @@ public static String generateBearerToken(Credentials credentials) throws Skyflow .setCtx(credentials.getContext()) .build() .getBearerToken(); - } else { + } else if (credentials.getToken() != null) { return credentials.getToken(); + } else { + return credentials.getApiKey(); } } diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index 586631f9..e7b4dc1a 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -8,6 +8,7 @@ import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; import com.skyflow.utils.ColumnValue; +import com.skyflow.utils.Constants; import com.skyflow.vault.data.*; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; @@ -17,6 +18,8 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class Validations { @@ -61,12 +64,35 @@ public static void validateConnectionConfig(ConnectionConfig connectionConfig) t public static void validateCredentials(Credentials credentials) throws SkyflowException { int nonNullMembers = 0; - if (credentials.getPath() != null) nonNullMembers++; - if (credentials.getCredentialsString() != null) nonNullMembers++; - if (credentials.getToken() != null) nonNullMembers++; + String path = credentials.getPath(); + String credentialsString = credentials.getCredentialsString(); + String token = credentials.getToken(); + String apiKey = credentials.getApiKey(); + + if (path != null) nonNullMembers++; + if (credentialsString != null) nonNullMembers++; + if (token != null) nonNullMembers++; + if (apiKey != null) nonNullMembers++; if (nonNullMembers != 1) { throw new SkyflowException(); + } else if (path != null && path.trim().isEmpty()) { + throw new SkyflowException(); + } else if (credentialsString != null && credentialsString.trim().isEmpty()) { + throw new SkyflowException(); + } else if (token != null && token.trim().isEmpty()) { + throw new SkyflowException(); + } else if (apiKey != null) { + if (apiKey.trim().isEmpty()) { + throw new SkyflowException(); + } else { + Pattern pattern = Pattern.compile(Constants.API_KEY_REGEX); + Matcher matcher = pattern.matcher(apiKey); + if (!matcher.matches()) { + // invalid api key + throw new SkyflowException(); + } + } } } From 78a202d6b2088b323b4d3d46e17c88824ebe86a7 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 28 Oct 2024 17:22:43 +0530 Subject: [PATCH 034/126] SK-1680 Implement logging SK-1723 Add error messages and codes --- v2/src/main/java/com/skyflow/Skyflow.java | 36 +- v2/src/main/java/com/skyflow/VaultClient.java | 49 +- .../java/com/skyflow/config/Credentials.java | 1 - .../java/com/skyflow/config/VaultConfig.java | 2 +- .../java/com/skyflow/enums/InterfaceName.java | 23 + .../java/com/skyflow/errors/ErrorCode.java | 107 +--- .../java/com/skyflow/errors/ErrorMessage.java | 131 +++++ .../com/skyflow/errors/SkyflowException.java | 13 +- .../main/java/com/skyflow/logs/ErrorLogs.java | 126 ++-- .../main/java/com/skyflow/logs/InfoLogs.java | 85 +++ .../serviceaccount/util/BearerToken.java | 61 +- .../serviceaccount/util/SignedDataTokens.java | 63 +- .../skyflow/serviceaccount/util/Token.java | 32 +- .../java/com/skyflow/utils/Constants.java | 4 + .../main/java/com/skyflow/utils/Messages.java | 17 - v2/src/main/java/com/skyflow/utils/Utils.java | 24 +- .../com/skyflow/utils/logger/LogUtil.java | 100 ++++ .../utils/validations/Validations.java | 540 +++++++++++++----- .../vault/controller/VaultController.java | 58 +- .../com/skyflow/vault/data/GetRequest.java | 2 +- .../skyflow/vault/data/InsertResponse.java | 47 -- .../com/skyflow/vault/data/UpdateRequest.java | 4 +- .../vault/tokens/DetokenizeRequest.java | 2 +- 23 files changed, 1091 insertions(+), 436 deletions(-) create mode 100644 v2/src/main/java/com/skyflow/enums/InterfaceName.java create mode 100644 v2/src/main/java/com/skyflow/errors/ErrorMessage.java create mode 100644 v2/src/main/java/com/skyflow/logs/InfoLogs.java delete mode 100644 v2/src/main/java/com/skyflow/utils/Messages.java create mode 100644 v2/src/main/java/com/skyflow/utils/logger/LogUtil.java diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/v2/src/main/java/com/skyflow/Skyflow.java index 6fe84ad9..abc1eea2 100644 --- a/v2/src/main/java/com/skyflow/Skyflow.java +++ b/v2/src/main/java/com/skyflow/Skyflow.java @@ -5,8 +5,13 @@ import com.skyflow.config.VaultConfig; import com.skyflow.enums.Env; import com.skyflow.enums.LogLevel; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.utils.LogUtil; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.Utils; +import com.skyflow.utils.logger.LogUtil; import com.skyflow.utils.validations.Validations; import com.skyflow.vault.controller.ConnectionController; import com.skyflow.vault.controller.VaultController; @@ -18,6 +23,7 @@ public final class Skyflow { private Skyflow(SkyflowClientBuilder builder) { this.builder = builder; + LogUtil.printInfoLog(InfoLogs.CLIENT_INITIALIZED.getLog()); } public static SkyflowClientBuilder builder() { @@ -111,13 +117,18 @@ public SkyflowClientBuilder() { } public SkyflowClientBuilder addVaultConfig(VaultConfig vaultConfig) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.VALIDATING_VAULT_CONFIG.getLog()); Validations.validateVaultConfig(vaultConfig); if (this.vaultClientsMap.containsKey(vaultConfig.getVaultId())) { - // display error log, throw error, or both - throw new SkyflowException(); + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.VAULT_CONFIG_EXISTS.getLog(), vaultConfig.getVaultId() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.VaultIdAlreadyInConfigList.getMessage()); } else { this.vaultConfigMap.put(vaultConfig.getVaultId(), vaultConfig); this.vaultClientsMap.put(vaultConfig.getVaultId(), new VaultController(vaultConfig, this.skyflowCredentials)); + LogUtil.printInfoLog(InfoLogs.VAULT_CONTROLLER_INITIALIZED.getLog()); } return this; } @@ -127,8 +138,10 @@ public SkyflowClientBuilder updateVaultConfig(VaultConfig vaultConfig) throws Sk VaultConfig updatedConfig = findAndUpdateVaultConfig(vaultConfig); this.vaultClientsMap.get(updatedConfig.getVaultId()).updateVaultConfig(); } else { - // display error log, throw error, or both - throw new SkyflowException(); + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog(), vaultConfig.getVaultId() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultIdNotInConfigList.getMessage()); } return this; } @@ -138,8 +151,8 @@ public SkyflowClientBuilder removeVaultConfig(String vaultId) throws SkyflowExce this.vaultClientsMap.remove(vaultId); this.vaultConfigMap.remove(vaultId); } else { - // display error log, throw error, or both - throw new SkyflowException(); + LogUtil.printErrorLog(Utils.parameterizedString(ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog(), vaultId)); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultIdNotInConfigList.getMessage()); } return this; } @@ -187,8 +200,11 @@ public SkyflowClientBuilder addSkyflowCredentials(Credentials credentials) throw } public SkyflowClientBuilder setLogLevel(LogLevel logLevel) { - this.logLevel = logLevel; + this.logLevel = logLevel == null ? LogLevel.ERROR : logLevel; LogUtil.setupLogger(logLevel); + LogUtil.printInfoLog(Utils.parameterizedString( + InfoLogs.CURRENT_LOG_LEVEL.getLog(), String.valueOf(logLevel) + )); return this; } @@ -199,7 +215,9 @@ public Skyflow build() { private VaultConfig findAndUpdateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { VaultConfig previousConfig = this.vaultConfigMap.get(vaultConfig.getVaultId()); if (previousConfig == null) { - // display error log, throw error, or both + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog(), vaultConfig.getVaultId() + )); throw new SkyflowException(); } else { Env env = vaultConfig.getEnv() != null ? vaultConfig.getEnv() : previousConfig.getEnv(); diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/v2/src/main/java/com/skyflow/VaultClient.java index 52be5807..1c2e81ea 100644 --- a/v2/src/main/java/com/skyflow/VaultClient.java +++ b/v2/src/main/java/com/skyflow/VaultClient.java @@ -2,15 +2,24 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.ApiClient; import com.skyflow.generated.rest.api.QueryApi; import com.skyflow.generated.rest.api.RecordsApi; import com.skyflow.generated.rest.api.TokensApi; +import com.skyflow.generated.rest.auth.HttpBearerAuth; import com.skyflow.generated.rest.models.*; -import com.skyflow.vault.tokens.ColumnValue; +import com.skyflow.logs.InfoLogs; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; +import com.skyflow.utils.logger.LogUtil; +import com.skyflow.utils.validations.Validations; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.UpdateRequest; +import com.skyflow.vault.tokens.ColumnValue; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; import io.github.cdimascio.dotenv.Dotenv; @@ -27,6 +36,8 @@ public class VaultClient { private final VaultConfig vaultConfig; private Credentials commonCredentials; private Credentials finalCredentials; + private String token; + private String apiKey; protected VaultClient(VaultConfig vaultConfig, Credentials credentials) { super(); @@ -64,6 +75,10 @@ protected VaultConfig getVaultConfig() { return vaultConfig; } + protected String getToken() { + return token; + } + protected void setCommonCredentials(Credentials commonCredentials) { this.commonCredentials = commonCredentials; prioritiseCredentials(); @@ -160,6 +175,31 @@ protected V1TokenizePayload getTokenizePayload(TokenizeRequest request) { return payload; } + protected void setBearerToken() throws SkyflowException { + Validations.validateCredentials(this.finalCredentials); + if (this.finalCredentials.getApiKey() != null) { + setApiKey(); + return; + } else if (token == null || Token.isExpired(token)) { + LogUtil.printInfoLog(InfoLogs.BEARER_TOKEN_EXPIRED.getLog()); + token = Utils.generateBearerToken(this.finalCredentials); + } else { + LogUtil.printInfoLog(InfoLogs.REUSE_BEARER_TOKEN.getLog()); + } + HttpBearerAuth Bearer = (HttpBearerAuth) this.apiClient.getAuthentication("Bearer"); + Bearer.setBearerToken(token); + } + + private void setApiKey() { + if (apiKey == null) { + apiKey = this.finalCredentials.getApiKey(); + } else { + LogUtil.printInfoLog(InfoLogs.REUSE_API_KEY.getLog()); + } + HttpBearerAuth Bearer = (HttpBearerAuth) this.apiClient.getAuthentication("Bearer"); + Bearer.setBearerToken(apiKey); + } + private void updateVaultURL() { String vaultURL = Utils.getVaultURL(this.vaultConfig.getClusterId(), this.vaultConfig.getEnv()); this.apiClient.setBasePath(vaultURL); @@ -173,14 +213,17 @@ private void prioritiseCredentials() { this.finalCredentials = this.commonCredentials; } else { Dotenv dotenv = Dotenv.load(); - String sysCredentials = dotenv.get("SKYFLOW_CREDENTIALS"); + String sysCredentials = dotenv.get(Constants.ENV_CREDENTIALS_KEY_NAME); if (sysCredentials == null) { - // throw error for not passing any credentials + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.EmptyCredentials.getMessage()); } else { this.finalCredentials = new Credentials(); this.finalCredentials.setCredentialsString(sysCredentials); } } + token = null; + apiKey = null; } catch (Exception e) { throw new RuntimeException(e); } diff --git a/v2/src/main/java/com/skyflow/config/Credentials.java b/v2/src/main/java/com/skyflow/config/Credentials.java index 8618ebb9..f1865dc7 100644 --- a/v2/src/main/java/com/skyflow/config/Credentials.java +++ b/v2/src/main/java/com/skyflow/config/Credentials.java @@ -12,7 +12,6 @@ public class Credentials { public Credentials() { this.path = null; - this.roles = new ArrayList<>(); this.context = null; this.credentialsString = null; } diff --git a/v2/src/main/java/com/skyflow/config/VaultConfig.java b/v2/src/main/java/com/skyflow/config/VaultConfig.java index 624d7d9a..2e757c7b 100644 --- a/v2/src/main/java/com/skyflow/config/VaultConfig.java +++ b/v2/src/main/java/com/skyflow/config/VaultConfig.java @@ -37,7 +37,7 @@ public Env getEnv() { } public void setEnv(Env env) { - this.env = env; + this.env = env == null ? Env.PROD : env; } public Credentials getCredentials() { diff --git a/v2/src/main/java/com/skyflow/enums/InterfaceName.java b/v2/src/main/java/com/skyflow/enums/InterfaceName.java new file mode 100644 index 00000000..643bf9da --- /dev/null +++ b/v2/src/main/java/com/skyflow/enums/InterfaceName.java @@ -0,0 +1,23 @@ +package com.skyflow.enums; + +public enum InterfaceName { + INSERT("insert"), + DETOKENIZE("detokenize"), + GET("get"), + UPDATE("update"), + DELETE("delete"), + QUERY("query"), + TOKENIZE("tokenize"), + FILE_UPLOAD("file upload"), + INVOKE_CONNECTION("invoke connection"); + + private final String interfaceName; + + InterfaceName(String interfaceName) { + this.interfaceName = interfaceName; + } + + public String getName() { + return interfaceName; + } +} diff --git a/v2/src/main/java/com/skyflow/errors/ErrorCode.java b/v2/src/main/java/com/skyflow/errors/ErrorCode.java index 73a3bec2..943913c6 100644 --- a/v2/src/main/java/com/skyflow/errors/ErrorCode.java +++ b/v2/src/main/java/com/skyflow/errors/ErrorCode.java @@ -1,115 +1,18 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ package com.skyflow.errors; public enum ErrorCode { - - InvalidCredentialFilePath(400, "{Language} SDK v{semver} Initialization failed. Invalid credentials. Specify the file path as a string."), - EmptyCredentialFilePath(400, "{Language} SDK v{semver} Initialization failed. Invalid credentials. Specify a valid file path."), - InvalidRolesKeyType(4000, "{Language} SDK v{semver} Initialization failed. Invalid roles. Specify roles as an array."), - InvalidRoleType(400, "{Language} SDK v{semver} Initialization failed. Invalid role. Specify the role as a string."), - EmptyRoles(400, "{Language} SDK v{semver} Initialization failed. Invalid roles. Specify at least one role."), - EmptyRoleInRoles(400, "{Language} SDK v{semver} Initialization failed. Invalid role. Specify a valid role."), - InvalidContext(400, "{Language} SDK v{semver} Initialization failed. Invalid context provided. Specify context as type Context."), - EmptyContext(400, "{Language} SDK v{semver} Initialization failed. Invalid context. Specify a valid context."), - InvalidCredentialsString(400, "{Language} SDK v{semver} Initialization failed. Invalid credentials. Specify credentials as a string."), - EmptyCredentialsString(400, "{Language} SDK v{semver} Initialization failed. Invalid credentials. Specify valid credentials."), - EmptyVaultId(400, "{Language} SDK v{semver} Initialization failed. Invalid vault ID. Specify a valid vault ID."), - InvalidVaultId(400, "{Language} SDK v{semver} Initialization failed. Invalid vault ID. Specify a valid vault ID as a string."), - InvalidClusterId(400, "{Language} SDK v{semver} Initialization failed. Invalid cluster ID. Specify cluster ID as a string."), - EmptyClusterId(400, "{Language} SDK v{semver} Initialization failed. Invalid cluster ID. Specify a valid cluster ID."), - InvalidConnectionId(400, "{Language} SDK v{semver} Initialization failed. Invalid connection ID. Specify connection ID as a string."), - EmptyConnectionId(400, "{Language} SDK v{semver} Initialization failed. Invalid connection ID. Specify a valid connection ID."), - InvalidConnectionUrl(400, "{Language} SDK v{semver} Initialization failed. Invalid connection URL. Specify connection URL as a string."), - EmptyConnectionUrl(400, "{Language} SDK v{semver} Initialization failed. Invalid connection URL. Specify a valid connection URL."), - TokenProviderError(400, "{Language} SDK v{semver} Initialization failed. Invalid token provider. Specify the token provider as a function."), - TokenProviderInvalidToken(400, "{Language} SDK v{semver} Initialization failed. Invalid token. Verify the output of the token provider."), - FileNotFound(400, "{Language} SDK v{semver} Initialization failed. Credential file not found at %s1. Verify the file path."), - FileInvalidJson(400, "{Language} SDK v{semver} Initialization failed. File at %s1 is not in valid JSON format. Verify the file contents."), - InvalidCredentials(400, "{Language} SDK v{semver} Initialization failed. Invalid credentials provided. Specify valid credentials."), - InvalidUrl(400, "{Language} SDK v{semver} Initialization failed. Vault URL %s1 is invalid. Specify a valid vault URL."), - MissingPrivateKey(400, "{Language} SDK v{semver} Initialization failed. Unable to read private key in credentials. Verify your private key."), - MissingClientId(400, "{Language} SDK v{semver} Initialization failed. Unable to read client ID in credentials. Verify your client ID."), - MissingKeyId(400, "{Language} SDK v{semver} Initialization failed. Unable to read key ID in credentials. Verify your key ID."), - MissingTokenUri(400, "{Language} SDK v{semver} Initialization failed. Unable to read token URI in credentials. Verify your token URI."), - JwtInvalidFormat(400, "{Language} SDK v{semver} Initialization failed. Invalid private key format. Verify your credentials."), - MissingAccessToken(400, "{Language} SDK v{semver} Validation error. Access token not present in the response from bearer token generation. Verify your credentials."), - MissingTokenType(400, "{Language} SDK v{semver} Validation error. Token type not present in the response from bearer token generation. Verify your credentials."), - JwtDecodeError(400, "{Language} SDK v{semver} Validation error. Invalid access token. Verify your credentials."), - VaultIdNotInConfigList(400, "{Language} SDK v{semver} Validation error. VaultId is missing from the config. Specify the vaultIds from configs."), - ConnectionIdNotInConfigList(400, "{Language} SDK v{semver} Validation error. ConnectionId is missing from the config. Specify the connectionIds from configs."), - EmptyCredentials(400, "{Language} SDK v{semver} Validation error. Invalid credentials. Specify a valid credentials."), - EmptyDataTokens(400, "{Language} SDK v{semver} Validation error. Invalid data tokens. Specify valid data tokens."), - DataTokenKeyType(400, "{Language} SDK v{semver} Validation error. Invalid data tokens. Specify data token as an string array."), - TimeToLeaveKeyType(400, "{Language} SDK v{semver} Validation error. Invalid time to live. Specify time to live parameter as an string."), - - //delete interface - InvalidIdTypeDelete(400, "{Language} SDK v{semver} Validation error. Invalid 'id' in 'records' array at index %s1 in records array. Specify 'id' as a string."), - EmptyRecordsInDelete(400, "{Language} SDK v{semver} Validation error. 'records' array can't be empty. Specify one or more records."), - EmptyIDInDelete(400, "{Language} SDK v{semver} Validation error. 'id' can't be empty in the 'records' array. Specify an ID."), - EmptyTableInDelete(400, "{Language} SDK v{semver} Validation error. 'table' can't be empty in the 'records' array. Specify a table."), - - //get interface - InvalidIdsType(400, "{Language} SDK v{semver} Validation error. 'ids' has a value of type %s1. Specify 'ids' as list."), - InvalidIdType(400, "{Language} SDK v{semver} Validation error. 'id' has a value of type %s1. Specify 'id' as string."), - InvalidRedactionType(400, "{Language} SDK v{semver} Validation error. Redaction key has value of type %s1, expected Skyflow.Redaction."), - InvalidColumnName(400, "{Language} SDK v{semver} Validation error. Column name has value of type %s1, expected a string."), - InvalidColumnValue(400, "{Language} SDK v{semver} Validation error. Column values has value of type %s1, expected a list."), - - //connection - InvalidPathParams(400, "{Language} SDK v{semver} Validation error. Path parameters aren't valid. Specify valid path parameters."), - EmptyPathParams(400, "{Language} SDK v{semver} Validation error. Path parameters are empty. Specify valid path parameters."), - InvalidRequestBody(400, "{Language} SDK v{semver} Validation error. Invalid request body. Specify the request body as an object."), - EmptyRequestBody(400, "{Language} SDK v{semver} Validation error. Request body can't be empty. Specify a valid request body."), - - //insert - RecordsKeyError(400, "{Language} SDK v{semver} Validation error. 'records' key is missing from the payload. Specify a 'records' key."), - FieldsKeyError(400, "{Language} SDK v{semver} Validation error. 'fields' key is missing from the payload. Specify a 'fields' key."), - TableKeyError(400, "{Language} SDK v{semver} Validation error. 'table' key is missing from the payload. Specify a 'table' key."), - TokenKeyError(400, "{Language} SDK v{semver} Validation error. 'token' key is missing from the payload. Specify a 'token' key."), - IdsKeyError(400, "{Language} SDK v{semver} Validation error. 'ids' key is missing from the payload. Specify an 'ids' key."), - RedactionKeyError(400, "{Language} SDK v{semver} Validation error. 'redaction' key is missing from the payload. Specify a 'redaction' key."), - UniqueColumnOrIdsKeyError(400, "{Language} SDK v{semver} Validation error. ids or columnName key is missing from the payload. Specify the ids or unique 'columnName' in payload."), - UpdateFieldKeyError(400, "{Language} SDK v{semver} Validation error. Fields are empty in an update payload. Specify at least one field."), - InvalidRecordsType(400, "{Language} SDK v{semver} Validation error. The 'records' key has a value of type %s1. Specify 'records' as a list."), - InvalidFieldsType(400, "{Language} SDK v{semver} Validation error. The 'fields' key has a value of type %s1. Specify 'fields' as a dictionary."), - InvalidTokensType(400, "{Language} SDK v{semver} Validation error. The 'tokens' key has a value of type %s1. Specify 'tokens' as a dictionary."), - EmptyTokensInInsert(400, "{Language} SDK v{semver} Validation error. The 'tokens' field is empty. Specify tokens for one or more fields."), - MismatchOfFieldsAndTokens(400, "{Language} SDK v{semver} Validation error. 'fields' and 'tokens' have different columns names. Verify that 'fields' and 'tokens' columns match."), - InvalidTableType(400, "{Language} SDK v{semver} Validation error. The 'table' key has a value of type %s1. Specify 'table' as a string."), - RedactionWithTokensNotSupported(400, "{Language} SDK v{semver} Validation error. 'redaction' can't be used when tokens are specified. Remove 'redaction' from payload if tokens are specified."), - TokensGetColumnNotSupported(400, "{Language} SDK v{semver} Validation error. Column name and/or column values can't be used when tokens are specified. Remove unique column values or tokens from the payload."), - BothIdsAndColumnDetailsSpecified(400, "{Language} SDK v{semver} Validation error. Both Skyflow IDs and column details can't be specified. Either specify Skyflow IDs or unique column details."), - PartialSuccess(400, "{Language} SDK v{semver} Validation error. Check 'SkyflowError.data' for details."), - InvalidUpsertOptionsType(400, "{Language} SDK v{semver} Validation error. 'upsert' key cannot be empty in options. At least one object of table and column is required."), - InvalidUpsertTableType(400, "{Language} SDK v{semver} Validation error. The 'table' key in the 'upsert' object has avalue of type %s1. Specify 'table' as a string."), - InvalidUpsertColumnType(400, "{Language} SDK v{semver} Validation error. The 'column' key in the 'upsert' object has a value of type %s1. Specify 'column' as a string."), - EmptyUpsertOptionTable(400, "{Language} SDK v{semver} Validation error. The 'table' key in the 'upsert' object can't be an empty string. Specify a 'table' value."), - EmptyUpsertOptionColumn(400, "{Language} SDK v{semver} Validation error. The 'column' key in the 'upsert' object can't be an empty string. Specify a 'column' value."), - BatchInsertPartialSuccess(400, "{Language} SDK v{semver} Insert operation completed with partial success."), - BatchInsertFailure(400, "{Language} SDK v{semver} Insert operation failed."), - InvalidByotType(400, "{Language} SDK v{semver} Validation error. The 'byot' key has a value of type %s1. Specify 'byot' as Skyflow.BYOT."), - NoTokensInInsert(400, "{Language} SDK v{semver} Validation error. Tokens weren't specified for records while 'byot' was %s1. Specify tokens."), - TokensPassedForByotDisable(400, "{Language} SDK v{semver} Validation error. 'byot' wasn't specified. Set 'byot' to 'ENABLE' to insert tokens."), - InsufficientTokensPassedForByotEnableStrict(400, "{Language} SDK v{semver} Validation error. 'byot' is set to 'ENABLE_STRICT', but some fields are missing tokens. Specify tokens for all fields."); - - + INVALID_INPUT(400), + INVALID_INDEX(404), + SERVER_ERROR(500), + PARTIAL_SUCCESS(500); private final int code; - private final String message; - ErrorCode(int code, String message) { + ErrorCode(int code) { this.code = code; - this.message = message; } public int getCode() { return code; } - - public String getMessage() { - return message; - } - } diff --git a/v2/src/main/java/com/skyflow/errors/ErrorMessage.java b/v2/src/main/java/com/skyflow/errors/ErrorMessage.java new file mode 100644 index 00000000..5d9905a3 --- /dev/null +++ b/v2/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -0,0 +1,131 @@ +package com.skyflow.errors; + +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; + +public enum ErrorMessage { + // client initialization + VaultIdAlreadyInConfigList("%s1 Validation error. VaultId is present in an existing config. Specify a new vaultId in config."), + VaultIdNotInConfigList("%s1 Validation error. VaultId is missing from the config. Specify the vaultIds from configs."), + ConnectionIdAlreadyInConfigList("%s1 Validation error. ConnectionId is present in an existing config. Specify a connectionId in config."), + ConnectionIdNotInConfigList("%s1 Validation error. ConnectionId is missing from the config. Specify the connectionIds from configs."), + EmptyCredentials("%s1 Validation error. Invalid credentials. Specify a valid credentials."), + + // vault config + InvalidVaultId("%s1 Initialization failed. Invalid vault ID. Specify a valid vault ID."), + EmptyVaultId("%s1 Initialization failed. Invalid vault ID. Vault ID must not be empty."), + InvalidClusterId("%s1 Initialization failed. Invalid cluster ID. Specify cluster ID."), + EmptyClusterId("%s1 Initialization failed. Invalid cluster ID. Specify a valid cluster ID."), + + // connection config + InvalidConnectionId("%s1 Initialization failed. Invalid connection ID. Specify a valid connection ID."), + EmptyConnectionId("%s1 Initialization failed. Invalid connection ID. Connection ID must not be empty."), + EmptyConnectionUrl("%s1 Initialization failed. Invalid connection URL. Connection URL must not be empty."), + InvalidConnectionUrl("%s1 Initialization failed. Invalid connection URL. Specify a valid connection URL."), + InvalidConnectionUrlFormat("%s1 Initialization failed. Connection URL is not a valid URL. Specify a valid connection URL."), + + // credentials + MultipleTokenGenerationMeansPassed("%s1 Initialization failed. Invalid credentials. Specify only one from 'path', 'credentialsString', 'token' or 'apiKey'."), + NoTokenGenerationMeansPassed("%s1 Initialization failed. Invalid credentials. Specify any one from 'path', 'credentialsString', 'token' or 'apiKey'."), + EmptyCredentialFilePath("%s1 Initialization failed. Invalid credentials. Credentials file path must not be empty."), + EmptyCredentialsString("%s1 Initialization failed. Invalid credentials. Credentials string must not be empty."), + EmptyToken("%s1 Initialization failed. Invalid credentials. Token mut not be empty."), + EmptyApikey("%s1 Initialization failed. Invalid credentials. Api key must not be empty."), + InvalidApikey("%s1 Initialization failed. Invalid credentials. Specify valid api key."), + EmptyRoles("%s1 Initialization failed. Invalid roles. Specify at least one role."), + EmptyRoleInRoles("%s1 Initialization failed. Invalid role. Specify a valid role."), + EmptyContext("%s1 Initialization failed. Invalid context. Specify a valid context."), + + // bearer token generation + FileNotFound("%s1 Initialization failed. Credential file not found at %s2. Verify the file path."), + FileInvalidJson("%s1 Initialization failed. File at %s2 is not in valid JSON format. Verify the file contents."), + CredentialsStringInvalidJson("%s1 Initialization failed. Credentials string is not in valid JSON format. Verify the credentials string contents."), + InvalidCredentials("%s1 Initialization failed. Invalid credentials provided. Specify valid credentials."), + MissingPrivateKey("%s1 Initialization failed. Unable to read private key in credentials. Verify your private key."), + MissingClientId("%s1 Initialization failed. Unable to read client ID in credentials. Verify your client ID."), + MissingKeyId("%s1 Initialization failed. Unable to read key ID in credentials. Verify your key ID."), + MissingTokenUri("%s1 Initialization failed. Unable to read token URI in credentials. Verify your token URI."), + InvalidTokenUri("%s1 Initialization failed. Token URI in not a valid URL in credentials. Verify your token URI."), + JwtInvalidFormat("%s1 Initialization failed. Invalid private key format. Verify your credentials."), + InvalidAlgorithm("%s1 Initialization failed. Invalid algorithm to parse private key. Specify valid algorithm."), + InvalidKeySpec("%s1 Initialization failed. Unable to parse RSA private key. Verify your credentials."), + JwtDecodeError("%s1 Validation error. Invalid access token. Verify your credentials."), + MissingAccessToken("%s1 Validation error. Access token not present in the response from bearer token generation. Verify your credentials."), + MissingTokenType("%s1 Validation error. Token type not present in the response from bearer token generation. Verify your credentials."), + + // insert + TableKeyError("%s1 Validation error. 'table' key is missing from the payload. Specify a 'table' key."), + EmptyTable("%s1 Validation error. 'table' can't be empty. Specify a table."), + ValuesKeyError("%s1 Validation error. 'values' key is missing from the payload. Specify a 'values' key."), + EmptyValues("%s1 Validation error. 'values' can't be empty. Specify values."), + EmptyKeyInValues("%s1 Validation error. Invalid key in values. Specify a valid key."), + EmptyValueInValues("%s1 Validation error. Invalid value in values. Specify a valid value."), + TokensKeyError("%s1 Validation error. 'tokens' key is missing from the payload. Specify a 'tokens' key."), + EmptyTokens("%s1 Validation error. The 'tokens' field is empty. Specify tokens for one or more fields."), + EmptyKeyInTokens("%s1 Validation error. Invalid key tokens. Specify a valid key."), + EmptyValueInTokens("%s1 Validation error. Invalid value in tokens. Specify a valid value."), + EmptyUpsert("%s1 Validation error. 'upsert' key can't be empty. Specify an upsert column."), + HomogenousNotSupportedWithUpsert("%s1 Validation error. 'homogenous' is not supported with 'upsert'. Specify either 'homogenous' or 'upsert'."), + TokensPassedForByotDisable("%s1 Validation error. 'tokenStrict' wasn't specified. Set 'tokenStrict' to 'ENABLE' to insert tokens."), + NoTokensWithByot("%s1 Validation error. Tokens weren't specified for records while 'tokenStrict' was %s2. Specify tokens."), + MismatchOfFieldsAndTokens("%s1 Validation error. 'fields' and 'tokens' have different columns names. Verify that 'fields' and 'tokens' columns match."), + InsufficientTokensPassedForByotEnableStrict("%s1 Validation error. 'tokenStrict' is set to 'ENABLE_STRICT', but some fields are missing tokens. Specify tokens for all fields."), + BatchInsertPartialSuccess("%s1 Insert operation completed with partial success."), + BatchInsertFailure("%s1 Insert operation failed."), + + // detokenize + InvalidDataTokens("%s1 Validation error. Invalid data tokens. Specify valid data tokens."), + EmptyDataTokens("%s1 Validation error. Invalid data tokens. Specify at least one data token."), + EmptyTokenInDataTokens("%s1 Validation error. Invalid data tokens. Specify a valid data token."), + + // get interface + IdsKeyError("%s1 Validation error. 'ids' key is missing from the payload. Specify an 'ids' key."), + EmptyIds("%s1 Validation error. 'ids' can't be empty. Specify at least one id."), + EmptyIdInIds("%s1 Validation error. Invalid id in 'ids'. Specify a valid id."), + EmptyFields("%s1 Validation error. Fields are empty in get payload. Specify at least one field."), + EmptyFieldInFields("%s1 Validation error. Invalid field in 'fields'. Specify a valid field."), + RedactionKeyError("%s1 Validation error. 'redaction' key is missing from the payload. Specify a 'redaction' key."), + RedactionWithTokensNotSupported("%s1 Validation error. 'redaction' can't be used when 'returnTokens' is specified. Remove 'redaction' from payload if 'returnTokens' is specified."), + TokensGetColumnNotSupported("%s1 Validation error. Column name and/or column values can't be used when 'returnTokens' is specified. Remove unique column values or 'returnTokens' from the payload."), + EmptyOffset("%s1 Validation error. 'offset' can't be empty. Specify an offset."), + EmptyLimit("%s1 Validation error. 'limit' can't be empty. Specify a limit."), + UniqueColumnOrIdsKeyError("%s1 Validation error. 'ids' or 'columnName' key is missing from the payload. Specify the ids or unique 'columnName' in payload."), + BothIdsAndColumnDetailsSpecified("%s1 Validation error. Both Skyflow IDs and column details can't be specified. Either specify Skyflow IDs or unique column details."), + ColumnNameKeyError("%s1 Validation error. 'columnName' isn't specified whereas 'columnValues' are specified. Either add 'columnName' or remove 'columnValues'."), + EmptyColumnName("%s1 Validation error. 'columnName' can't be empty. Specify a column name."), + ColumnValuesKeyErrorGet("%s1 Validation error. 'columnValues' aren't specified whereas 'columnName' is specified. Either add 'columnValues' or remove 'columnName'."), + EmptyColumnValues("%s1 Validation error. 'columnValues' can't be empty. Specify at least one column value"), + EmptyValueInColumnValues("%s1 Validation error. Invalid value in column values. Specify a valid column value."), + + TokenKeyError("%s1 Validation error. 'token' key is missing from the payload. Specify a 'token' key."), + PartialSuccess("%s1 Validation error. Check 'SkyflowError.data' for details."), + + // update + SkyflowIdKeyError("%s1 Validation error. 'id' key is missing from the payload. Specify an 'id' key."), + EmptySkyflowId("%s1 Validation error. 'id' can't be empty. Specify an id."), + + // query + QueryKeyError("%s1 Validation error. 'query' key is missing from the payload. Specify a 'query' key."), + EmptyQuery("%s1 Validation error. 'query' can't be empty. Specify a query"), + + // tokenize + ColumnValuesKeyErrorTokenize("%s1 Validation error. 'columnValues' key is missing from the payload. Specify a 'columnValues' key."), + EmptyColumnGroupInColumnValue("%s1 Validation error. Invalid column group in column value. Specify a valid column group."), + + //connection + InvalidPathParams("%s1 Validation error. Path parameters aren't valid. Specify valid path parameters."), + EmptyPathParams("%s1 Validation error. Path parameters are empty. Specify valid path parameters."), + InvalidRequestBody("%s1 Validation error. Invalid request body. Specify the request body as an object."), + EmptyRequestBody("%s1 Validation error. Request body can't be empty. Specify a valid request body."), + + ; + private final String message; + + ErrorMessage(String message) { + this.message = Utils.parameterizedString(message, Constants.SDK_PREFIX); + } + + public String getMessage() { + return message; + } +} diff --git a/v2/src/main/java/com/skyflow/errors/SkyflowException.java b/v2/src/main/java/com/skyflow/errors/SkyflowException.java index 20f70fb8..1d0c81ff 100644 --- a/v2/src/main/java/com/skyflow/errors/SkyflowException.java +++ b/v2/src/main/java/com/skyflow/errors/SkyflowException.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Map; +import java.util.Objects; public class SkyflowException extends Exception { private String requestId; @@ -34,13 +35,19 @@ public SkyflowException(String message, Throwable cause) { public SkyflowException(int code, String message) { super(message); this.code = code; + this.message = message; } public SkyflowException(int code, Throwable cause, Map> responseHeaders, String responseBody) { this(cause); this.code = code; + String contentType = responseHeaders.get("content-type").get(0); setRequestId(responseHeaders); - setResponseBody(responseBody); + if (Objects.equals(contentType, "application/json")) { + setResponseBody(responseBody); + } else if (Objects.equals(contentType, "text/plain")) { + this.message = responseBody; + } } private void setResponseBody(String responseBody) { @@ -86,8 +93,8 @@ public String getMessage() { @Override public String toString() { return String.format( - "%n requestId: %s%n code: %s%n message: %s%n details: %s", - this.requestId, this.code, this.message, this.details + "%n requestId: %s%n code: %s%n message: %s", + this.requestId, this.code, this.message ); } diff --git a/v2/src/main/java/com/skyflow/logs/ErrorLogs.java b/v2/src/main/java/com/skyflow/logs/ErrorLogs.java index b776f314..fa1f945d 100644 --- a/v2/src/main/java/com/skyflow/logs/ErrorLogs.java +++ b/v2/src/main/java/com/skyflow/logs/ErrorLogs.java @@ -1,41 +1,97 @@ package com.skyflow.logs; public enum ErrorLogs { - ClientConnetion(""), - VaultIdIsRequired("Interface: init - Invalid client credentials. vaultID is required."), - EmptyVaultIdInInit("Interface: init - Invalid client credentials. vaultID cannot be empty."), - VaultUrlIsRequired("Interface: init - Invalid client credentials. vaultURL is required."), - EmptyVaultUrlInInit("Interface: init - Invalid client credentials. vaultURL cannot be empty."), - InvalidVaultUrlInInit("Interface: init - Invalid client credentials. Expecting https://XYZ for vaultURL"), - GetBearerTokenIsRequired("Interface: init - Invalid client credentials. getBearerToken is required."), - BearerTokenRejected(""), - InvalidEncodeUriInGet("Interface: get method - Invalid encodeURI type in get."), - InvalidBearerToken("Bearer token is invalid or expired."), - InvalidVaultId("Vault Id is invalid or cannot be found."), - EmptyVaultId("VaultID is empty"), - InvalidCredentials("Invalid client credentials."), - InvalidContainerType("Invalid container type."), - InvalidCollectValue("Invalid value"), - InvalidCollectValueWithLabel("Invalid %s1"), - RecordsKeyNotFound("records object key value not found."), - EmptyRecords("records object is empty."), - RecordsKeyError("Key “records” is missing or payload is incorrectly formatted."), - MissingRecords(""), - InvalidRecords("Invalid Records"), - EmptyRecordIds(""), - EmptyRecordColumnvalues("Record column values cannot be empty."), - InvalidRecordIdType("Invalid Type of Records Id."), - InvalidRecordColumnValueType(""), - InvalidRecordLabel("Invalid Record Label Type."), - InvalidRecordAltText("Invalid Record altText Type."), - FetchRecordsRejected(""), - InsertRecordsRejected(""), - GetBySkyflowIdRejected(""), - SendInvokeConnectionRejected("Invoke connection request rejected."), - UpdateRequestRejected("Update request is rejected."), - InvalidTableName("Table Name passed doesn’t exist in the vault with id."), - EmptyTableName("Table Name is empty."), - EmptyTableAndFields("table or fields parameter cannot be passed as empty at index %s1 in records array."); + // Client initialization + VAULT_CONFIG_EXISTS("Vault config with vault ID %s1 already exists."), + VAULT_CONFIG_DOES_NOT_EXIST("Vault config with vault ID %s1 doesn't exist."), + VAULT_ID_IS_REQUIRED("Invalid vault config. Vault ID is required."), + EMPTY_VAULT_ID("Invalid vault config. Vault ID can not be empty."), + CLUSTER_ID_IS_REQUIRED("Invalid vault config. Cluster ID is required."), + EMPTY_CLUSTER_ID("Invalid vault config. Cluster ID can not be empty."), + CONNECTION_CONFIG_EXISTS("Connection config with connection ID %s1 already exists."), + CONNECTION_CONFIG_DOES_NOT_EXIST("Connection config with connection ID %s1 doesn't exist."), + CONNECTION_ID_IS_REQUIRED("Invalid connection config. Connection ID is required."), + EMPTY_CONNECTION_ID("Invalid connection config. Connection ID can not be empty."), + CONNECTION_URL_IS_REQUIRED("Invalid connection config. Connection URL is required."), + EMPTY_CONNECTION_URL("Invalid connection config. Connection URL can not be empty."), + INVALID_CONNECTION_URL("Invalid connection config. Connection URL is not a valid URL."), + MULTIPLE_TOKEN_GENERATION_MEANS_PASSED("Invalid credentials. Only one of 'path', 'credentialsString', 'token' or 'apiKey' is allowed."), + NO_TOKEN_GENERATION_MEANS_PASSED("Invalid credentials. Any one of 'path', 'credentialsString', 'token' or 'apiKey' is required."), + EMPTY_CREDENTIALS_PATH("Invalid credentials. Credentials path can not be empty."), + EMPTY_CREDENTIALS_STRING("Invalid credentials. Credentials string can not be empty."), + EMPTY_TOKEN_VALUE("Invalid credentials. Token can not be empty."), + EMPTY_API_KEY_VALUE("Invalid credentials. Api key can not be empty."), + INVALID_API_KEY("Invalid credentials. Api key is invalid."), + EMPTY_ROLES("Invalid credentials. Roles can not be empty."), + EMPTY_OR_NULL_ROLE_IN_ROLES("Invalid credentials. Role can not be null or empty in roles at index %s1."), + EMPTY_OR_NULL_CONTEXT("Invalid credentials. Context can not be empty."), + + // Bearer token generation + INVALID_BEARER_TOKEN("Bearer token is invalid or expired."), + INVALID_CREDENTIALS_FILE("Credentials file is either null or an invalid file."), + INVALID_CREDENTIALS_STRING("Credentials string is either null or empty."), + INVALID_CREDENTIALS_FILE_FORMAT("Credentials file is not in a valid JSON format."), + CREDENTIALS_FILE_NOT_FOUND("Credentials file not found at specified path."), + INVALID_CREDENTIALS_STRING_FORMAT("Credentials string is not in a valid JSON string format."), + PRIVATE_KEY_IS_REQUIRED("Private key is required."), + CLIENT_ID_IS_REQUIRED("Client ID is required."), + KEY_ID_IS_REQUIRED("Key ID is required."), + TOKEN_URI_IS_REQUIRED("Token URI is required."), + INVALID_TOKEN_URI("Invalid value for token URI in credentials."), + JWT_INVALID_FORMAT("Private key is not in a valid format."), + INVALID_ALGORITHM("Algorithm for parsing private key is invalid or does not exist."), + INVALID_KEY_SPEC("Unable to parse RSA private key."), + BEARER_TOKEN_REJECTED("Bearer token request resulted in failure."), + SIGNED_DATA_TOKENS_REJECTED("Signed data tokens request resulted in failure."), + + // Vault api interfaces + TABLE_IS_REQUIRED("Invalid %s1 request. Table is required."), + EMPTY_TABLE_NAME("Invalid %s1 request. Table name can not be empty."), + VALUES_IS_REQUIRED("Invalid %s1 request. Values are required."), + EMPTY_VALUES("Invalid %s1 request. Values can not be empty."), + EMPTY_OR_NULL_VALUE_IN_VALUES("Invalid %s1 request. Value can not be null or empty in values for key \"%s2\"."), + EMPTY_OR_NULL_KEY_IN_VALUES("Invalid %s1 request. Key can not be null or empty in values"), + EMPTY_UPSERT("Invalid %s1 request. Upsert can not be empty."), + HOMOGENOUS_NOT_SUPPORTED_WITH_UPSERT("Invalid %s1 request. Homogenous is not supported when upsert is passed."), + TOKENS_NOT_ALLOWED_WITH_BYOT_DISABLE("Invalid %s1 request. Tokens are not allowed when tokenStrict is DISABLE."), + TOKENS_REQUIRED_WITH_BYOT("Invalid %s1 request. Tokens are required when tokenStrict is %s2."), + EMPTY_TOKENS("Invalid %s1 request. Tokens can not be empty."), + EMPTY_OR_NULL_VALUE_IN_TOKENS("Invalid %s1 request. Value can not be null or empty in tokens for key \"%s2\"."), + EMPTY_OR_NULL_KEY_IN_TOKENS("Invalid %s1 request. Key can not be null or empty in tokens."), + INSUFFICIENT_TOKENS_PASSED_FOR_BYOT_ENABLE_STRICT("Invalid %s1 request. For tokenStrict as ENABLE_STRICT, tokens should be passed for all fields."), + MISMATCH_OF_FIELDS_AND_TOKENS("Invalid %s1 request. Keys for values and tokens are not matching."), + INSERT_RECORDS_REJECTED("Insert request resulted in failure."), + TOKENS_REQUIRED("Invalid %s1 request. Tokens are required."), + EMPTY_OR_NULL_TOKEN_IN_TOKENS("Invalid %s1 request. Token can not be null or empty in tokens at index %s2."), + REDACTION_IS_REQUIRED("Invalid %s1 request. Redaction is required."), + DETOKENIZE_REQUEST_REJECTED("Detokenize request resulted in failure."), + IDS_IS_REQUIRED("Invalid %s1 request. Ids are required."), + EMPTY_IDS("Invalid %s1 request. Ids can not be empty."), + EMPTY_OR_NULL_ID_IN_IDS("Invalid %s1 request. Id can not be null or empty in ids at index %s2."), + EMPTY_FIELDS("Invalid %s1 request. Fields can not be empty."), + EMPTY_OR_NULL_FIELD_IN_FIELDS("Invalid %s1 request. Field can not be null or empty in fields at index %s2."), + TOKENIZATION_NOT_SUPPORTED_WITH_REDACTION("Invalid %s1 request. Return tokens is not supported when redaction is applied."), + TOKENIZATION_SUPPORTED_ONLY_WITH_IDS("Invalid %s1 request. Return tokens is not supported when column name and values are passed."), + EMPTY_OFFSET("Invalid %s1 request. Offset can not be empty."), + EMPTY_LIMIT("Invalid %s1 request. Limit can not be empty."), + NEITHER_IDS_NOR_COLUMN_NAME_PASSED("Invalid %s1 request. Neither ids nor column name and values are passed."), + BOTH_IDS_AND_COLUMN_NAME_PASSED("Invalid %s1 request. Both ids and column name and values are passed."), + COLUMN_NAME_IS_REQUIRED("Invalid %s1 request. Column name is required when column values are passed."), + EMPTY_COLUMN_NAME("Invalid %s1 request. Column name can not be empty."), + COLUMN_VALUES_IS_REQUIRED_GET("Invalid %s1 request. Column values are required when column name is passed."), + EMPTY_COLUMN_VALUES("Invalid %s1 request. Column values can not be empty."), + EMPTY_OR_NULL_COLUMN_VALUE_IN_COLUMN_VALUES("Invalid %s1 request. Column value can not by null or empty in column values at index %s2."), + GET_REQUEST_REJECTED("Get request resulted in failure."), + SKYFLOW_ID_IS_REQUIRED("Invalid %s1 request. Skyflow Id is required."), + EMPTY_SKYFLOW_ID("Invalid %s1 request. Skyflow Id can not be empty."), + UPDATE_REQUEST_REJECTED("Update request resulted in failure."), + QUERY_IS_REQUIRED("Invalid %s1 request. Query is required."), + EMPTY_QUERY("Invalid %s1 request. Query can not be empty."), + QUERY_REQUEST_REJECTED("Query request resulted in failure."), + COLUMN_VALUES_IS_REQUIRED_TOKENIZE("Invalid %s1 request. ColumnValues are required."), + EMPTY_OR_NULL_COLUMN_GROUP_IN_COLUMN_VALUES("Invalid %s1 request. Column group can not be null or empty in column values at index %s2."), + TOKENIZE_REQUEST_REJECTED("Tokenize request resulted in failure."), + DELETE_REQUEST_REJECTED("Delete request resulted in failure."); private final String log; diff --git a/v2/src/main/java/com/skyflow/logs/InfoLogs.java b/v2/src/main/java/com/skyflow/logs/InfoLogs.java new file mode 100644 index 00000000..5beecfd3 --- /dev/null +++ b/v2/src/main/java/com/skyflow/logs/InfoLogs.java @@ -0,0 +1,85 @@ +package com.skyflow.logs; + +public enum InfoLogs { + // Client initialization + CLIENT_INITIALIZED("Initialized skyflow client."), + VALIDATING_VAULT_CONFIG("Validating vault config."), + VALIDATING_CONNECTION_CONFIG("Validating connection config."), + UNABLE_TO_GENERATE_SDK_METRIC("Unable to generate %s1 metric."), + VAULT_CONTROLLER_INITIALIZED("Initialized vault controller with vault ID %s1."), + CONNECTION_CONTROLLER_INITIALIZED("Initialized connection controller with connection ID %s1."), + LOGGER_SETUP_DONE("Set up logger."), + CURRENT_LOG_LEVEL("Current log level is %s1."), + + // Bearer token generation + EMPTY_BEARER_TOKEN("Bearer token is empty."), + BEARER_TOKEN_EXPIRED("Bearer token is expired."), + GET_BEARER_TOKEN_TRIGGERED("getBearerToken method triggered."), + GET_BEARER_TOKEN_SUCCESS("Bearer token generated."), + GET_SIGNED_DATA_TOKENS_TRIGGERED("getSignedDataTokens method triggered."), + GET_SIGNED_DATA_TOKEN_SUCCESS("Signed data tokens generated."), + REUSE_BEARER_TOKEN("Reusing bearer token."), + REUSE_API_KEY("Reusing api key."), + GENERATE_BEARER_TOKEN_FROM_CREDENTIALS_TRIGGERED("generateBearerTokenFromCredentials method triggered."), + GENERATE_BEARER_TOKEN_FROM_CREDENTIALS_STRING_TRIGGERED("generateBearerTokenFromCredentialString method triggered."), + GENERATE_SIGNED_TOKENS_FROM_CREDENTIALS_FILE_TRIGGERED("generateSignedTokensFromCredentialsFile method triggered."), + GENERATE_SIGNED_TOKENS_FROM_CREDENTIALS_STRING_TRIGGERED("generateSignedTokensFromCredentialsString method triggered."), + + // Insert interface + INSERT_TRIGGERED("Insert method triggered."), + VALIDATE_INSERT_REQUEST("Validating insert request."), + INSERT_REQUEST_RESOLVED("Insert request resolved."), + INSERT_SUCCESS("Data inserted."), + + // Detokenize interface + DETOKENIZE_TRIGGERED("Detokenize method triggered."), + VALIDATE_DETOKENIZE_REQUEST("Validating detokenize request."), + DETOKENIZE_REQUEST_RESOLVED("Detokenize request resolved."), + DETOKENIZE_PARTIAL_SUCCESS("Data detokenized partially."), + DETOKENIZE_SUCCESS("Data detokenized."), + + // Get interface + GET_TRIGGERED("Get method triggered."), + VALIDATE_GET_REQUEST("Validating get request."), + GET_REQUEST_RESOLVED("Get request resolved."), + GET_SUCCESS("Data revealed."), + + // Update interface + UPDATE_TRIGGERED("Update method triggered."), + VALIDATE_UPDATE_REQUEST("Validating update request."), + UPDATE_REQUEST_RESOLVED("Update request resolved."), + UPDATE_SUCCESS("Data updated."), + + // Delete interface + DELETE_TRIGGERED("Delete method triggered."), + VALIDATING_DELETE_REQUEST("Validating delete request."), + DELETE_REQUEST_RESOLVED("Delete request resolved."), + DELETE_SUCCESS("Data deleted."), + + // Query interface + QUERY_TRIGGERED("Query method triggered."), + VALIDATING_QUERY_REQUEST("Validating query request."), + QUERY_REQUEST_RESOLVED("Query request resolved."), + QUERY_SUCCESS("Query executed."), + + // Tokenize interface + TOKENIZE_TRIGGERED("Tokenize method triggered."), + VALIDATING_TOKENIZE_REQUEST("Validating tokenize request."), + TOKENIZE_REQUEST_RESOLVED("Tokenize request resolved."), + TOKENIZE_SUCCESS("Data tokenized."), + + // Invoke connection interface + INVOKE_CONNECTION_TRIGGERED("Invoke connection method triggered."), + VALIDATING_INVOKE_CONNECTION_REQUEST("Validating invoke connection request."), + INVOKE_CONNECTION_REQUEST_RESOLVED("Invoke connection request resolved."); + + private final String log; + + InfoLogs(String log) { + this.log = log; + } + + public final String getLog() { + return log; + } +} diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java b/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java index 0b396dc5..2040cf16 100644 --- a/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java +++ b/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java @@ -4,14 +4,19 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.ApiClient; import com.skyflow.generated.rest.ApiException; import com.skyflow.generated.rest.api.AuthenticationApi; import com.skyflow.generated.rest.models.V1GetAuthTokenRequest; import com.skyflow.generated.rest.models.V1GetAuthTokenResponse; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.logs.InfoLogs; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; +import com.skyflow.utils.logger.LogUtil; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; @@ -48,31 +53,41 @@ public static BearerTokenBuilder builder() { private static V1GetAuthTokenResponse generateBearerTokenFromCredentials( File credentialsFile, String context, ArrayList roles ) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.GENERATE_BEARER_TOKEN_FROM_CREDENTIALS_TRIGGERED.getLog()); try { if (credentialsFile == null || !credentialsFile.isFile()) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); } FileReader reader = new FileReader(String.valueOf(credentialsFile)); JsonObject serviceAccountCredentials = JsonParser.parseReader(reader).getAsJsonObject(); return getBearerTokenFromCredentials(serviceAccountCredentials, context, roles); } catch (JsonSyntaxException e) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE_FORMAT.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( + ErrorMessage.FileInvalidJson.getMessage(), credentialsFile.getAbsolutePath())); } catch (FileNotFoundException e) { - throw new RuntimeException(e); + LogUtil.printErrorLog(ErrorLogs.CREDENTIALS_FILE_NOT_FOUND.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( + ErrorMessage.FileNotFound.getMessage(), credentialsFile.getAbsolutePath())); } } private static V1GetAuthTokenResponse generateBearerTokenFromCredentialString( String credentials, String context, ArrayList roles ) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.GENERATE_BEARER_TOKEN_FROM_CREDENTIALS_STRING_TRIGGERED.getLog()); try { if (credentials == null || credentials.isEmpty()) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_STRING.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); } JsonObject serviceAccountCredentials = JsonParser.parseString(credentials).getAsJsonObject(); return getBearerTokenFromCredentials(serviceAccountCredentials, context, roles); } catch (JsonSyntaxException e) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_STRING_FORMAT.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.CredentialsStringInvalidJson.getMessage()); } } @@ -82,22 +97,26 @@ private static V1GetAuthTokenResponse getBearerTokenFromCredentials( try { JsonElement privateKey = credentials.get("privateKey"); if (privateKey == null) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.PRIVATE_KEY_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingPrivateKey.getMessage()); } JsonElement clientID = credentials.get("clientID"); if (clientID == null) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.CLIENT_ID_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingClientId.getMessage()); } JsonElement keyID = credentials.get("keyID"); if (keyID == null) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.KEY_ID_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingKeyId.getMessage()); } JsonElement tokenURI = credentials.get("tokenURI"); if (tokenURI == null) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.TOKEN_URI_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingTokenUri.getMessage()); } PrivateKey pvtKey = Utils.getPrivateKeyFromPem(privateKey.getAsString()); @@ -118,9 +137,11 @@ private static V1GetAuthTokenResponse getBearerTokenFromCredentials( } return authenticationApi.authenticationServiceGetAuthToken(body); } catch (MalformedURLException e) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.INVALID_TOKEN_URI.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidTokenUri.getMessage()); } catch (ApiException e) { - throw new RuntimeException(e); + LogUtil.printErrorLog(ErrorLogs.BEARER_TOKEN_REJECTED.getLog()); + throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } } @@ -151,19 +172,17 @@ private static String getScopeUsingRoles(ArrayList roles) { } public synchronized String getBearerToken() throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.GET_BEARER_TOKEN_TRIGGERED.getLog()); V1GetAuthTokenResponse response; String accessToken = null; - try { - if (this.credentialsFile != null && Objects.equals(this.credentialsType, "FILE")) { - response = generateBearerTokenFromCredentials(this.credentialsFile, this.ctx, this.roles); - accessToken = response.getAccessToken(); - } else if (this.credentialsString != null && Objects.equals(this.credentialsType, "STRING")) { - response = generateBearerTokenFromCredentialString(this.credentialsString, this.ctx, this.roles); - accessToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); + if (this.credentialsFile != null && Objects.equals(this.credentialsType, "FILE")) { + response = generateBearerTokenFromCredentials(this.credentialsFile, this.ctx, this.roles); + accessToken = response.getAccessToken(); + } else if (this.credentialsString != null && Objects.equals(this.credentialsType, "STRING")) { + response = generateBearerTokenFromCredentialString(this.credentialsString, this.ctx, this.roles); + accessToken = response.getAccessToken(); } + LogUtil.printInfoLog(InfoLogs.GET_BEARER_TOKEN_SUCCESS.getLog()); return accessToken; } diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java b/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java index d5fe52bf..47e50951 100644 --- a/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java +++ b/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java @@ -4,14 +4,19 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.logs.InfoLogs; import com.skyflow.utils.Utils; +import com.skyflow.utils.logger.LogUtil; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.io.File; +import java.io.FileNotFoundException; import java.io.FileReader; -import java.io.IOException; import java.security.PrivateKey; import java.util.ArrayList; import java.util.Date; @@ -39,75 +44,79 @@ public static SignedDataTokensBuilder builder() { return new SignedDataTokensBuilder(); } - private static List generateSignedTokens( + private static List generateSignedTokenFromCredentialsFile( File credentialsFile, ArrayList dataTokens, Integer timeToLive, String context ) throws SkyflowException { - // print info log + LogUtil.printInfoLog(InfoLogs.GENERATE_SIGNED_TOKENS_FROM_CREDENTIALS_FILE_TRIGGERED.getLog()); List responseToken; try { if (credentialsFile == null || !credentialsFile.isFile()) { - // print error log - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); } FileReader reader = new FileReader(String.valueOf(credentialsFile)); JsonObject serviceAccountCredentials = JsonParser.parseReader(reader).getAsJsonObject(); - responseToken = getSignedTokenFromCredentialsFile(serviceAccountCredentials, dataTokens, timeToLive, context); + responseToken = generateSignedTokensFromCredentials(serviceAccountCredentials, dataTokens, timeToLive, context); } catch (JsonSyntaxException e) { - // print error log - throw new SkyflowException(); - } catch (IOException e) { - throw new RuntimeException(e); + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE_FORMAT.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( + ErrorMessage.FileInvalidJson.getMessage(), credentialsFile.getAbsolutePath())); + } catch (FileNotFoundException e) { + LogUtil.printErrorLog(ErrorLogs.CREDENTIALS_FILE_NOT_FOUND.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( + ErrorMessage.FileNotFound.getMessage(), credentialsFile.getAbsolutePath())); } - return responseToken; } private static List generateSignedTokensFromCredentialsString( String credentials, ArrayList dataTokens, Integer timeToLive, String context ) throws SkyflowException { - // print info log + LogUtil.printInfoLog(InfoLogs.GENERATE_SIGNED_TOKENS_FROM_CREDENTIALS_STRING_TRIGGERED.getLog()); List responseToken; - // print info log try { if (credentials == null || credentials.isEmpty()) { - // print error log - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_STRING.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); } JsonObject serviceAccountCredentials = JsonParser.parseString(credentials).getAsJsonObject(); - responseToken = getSignedTokenFromCredentialsFile(serviceAccountCredentials, dataTokens, timeToLive, context); - + responseToken = generateSignedTokensFromCredentials(serviceAccountCredentials, dataTokens, timeToLive, context); } catch (JsonSyntaxException e) { - // print error log - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_STRING_FORMAT.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.CredentialsStringInvalidJson.getMessage()); } - return responseToken; } - private static List getSignedTokenFromCredentialsFile( + private static List generateSignedTokensFromCredentials( JsonObject credentials, ArrayList dataTokens, Integer timeToLive, String context ) throws SkyflowException { List signedDataTokens = null; try { JsonElement privateKey = credentials.get("privateKey"); if (privateKey == null) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.PRIVATE_KEY_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingPrivateKey.getMessage()); } JsonElement clientID = credentials.get("clientID"); if (clientID == null) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.CLIENT_ID_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingClientId.getMessage()); } JsonElement keyID = credentials.get("keyID"); if (keyID == null) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.KEY_ID_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingKeyId.getMessage()); } PrivateKey pvtKey = Utils.getPrivateKeyFromPem(privateKey.getAsString()); signedDataTokens = getSignedToken( clientID.getAsString(), keyID.getAsString(), pvtKey, dataTokens, timeToLive, context); } catch (RuntimeException e) { - // throw error + LogUtil.printErrorLog(ErrorLogs.SIGNED_DATA_TOKENS_REJECTED.getLog()); + throw new SkyflowException(e); } return signedDataTokens; } @@ -144,16 +153,18 @@ private static List getSignedToken( } public synchronized List getSignedDataTokens() throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.GET_SIGNED_DATA_TOKENS_TRIGGERED.getLog()); List signedToken = new ArrayList<>(); try { if (this.credentialsFile != null && Objects.equals(this.credentialsType, "FILE")) { - signedToken = generateSignedTokens(this.credentialsFile, this.dataTokens, this.timeToLive, this.ctx); + signedToken = generateSignedTokenFromCredentialsFile(this.credentialsFile, this.dataTokens, this.timeToLive, this.ctx); } else if (this.credentialsString != null && Objects.equals(this.credentialsType, "STRING")) { signedToken = generateSignedTokensFromCredentialsString(this.credentialsString, this.dataTokens, this.timeToLive, this.ctx); } } catch (SkyflowException e) { e.printStackTrace(); } + LogUtil.printInfoLog(InfoLogs.GET_SIGNED_DATA_TOKEN_SUCCESS.getLog()); return signedToken; } diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/Token.java b/v2/src/main/java/com/skyflow/serviceaccount/util/Token.java index 60e49947..90da0cf4 100644 --- a/v2/src/main/java/com/skyflow/serviceaccount/util/Token.java +++ b/v2/src/main/java/com/skyflow/serviceaccount/util/Token.java @@ -1,12 +1,16 @@ package com.skyflow.serviceaccount.util; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.logger.LogUtil; import org.apache.commons.codec.binary.Base64; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import java.io.File; import java.nio.charset.StandardCharsets; import java.util.Date; @@ -15,30 +19,28 @@ public static boolean isExpired(String token) { long expiryTime; long currentTime; try { - if (token == null || token.isEmpty()) { - // print info log + if (token == null || token.trim().isEmpty()) { + LogUtil.printInfoLog(InfoLogs.EMPTY_BEARER_TOKEN.getLog()); return true; } currentTime = new Date().getTime() / 1000; - expiryTime = (long) decoded(token).get("exp"); + expiryTime = decoded(token).get("exp").getAsLong(); - } catch (ParseException e) { - // display info log - return true; - } catch (SkyflowException e) { - // display info log + } catch (JsonSyntaxException | SkyflowException e) { + LogUtil.printErrorLog(ErrorLogs.INVALID_BEARER_TOKEN.getLog()); return true; } return currentTime > expiryTime; } - static JSONObject decoded(String encodedToken) throws ParseException, SkyflowException { + static JsonObject decoded(String encodedToken) throws JsonSyntaxException, SkyflowException { String[] split = encodedToken.split("\\."); if (split.length < 3) { - throw new SkyflowException("invalid bearer token"); + LogUtil.printErrorLog(ErrorLogs.INVALID_BEARER_TOKEN.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.JwtDecodeError.getMessage()); } byte[] decodedBytes = Base64.decodeBase64(split[1]); - return (JSONObject) new JSONParser().parse(new String(decodedBytes, StandardCharsets.UTF_8)); + return JsonParser.parseString(new String(decodedBytes, StandardCharsets.UTF_8)).getAsJsonObject(); } } diff --git a/v2/src/main/java/com/skyflow/utils/Constants.java b/v2/src/main/java/com/skyflow/utils/Constants.java index e80e9b29..f7c378f5 100644 --- a/v2/src/main/java/com/skyflow/utils/Constants.java +++ b/v2/src/main/java/com/skyflow/utils/Constants.java @@ -12,4 +12,8 @@ public final class Constants { public static final String SIGNED_DATA_TOKEN_PREFIX = "signed_token_"; public static final String ORDER_ASCENDING = "ASCENDING"; public static final String API_KEY_REGEX = "^sky-[a-zA-Z0-9]{5}-[a-fA-F0-9]{32}$"; + public static final String ENV_CREDENTIALS_KEY_NAME = "SKYFLOW_CREDENTIALS"; + public static final String SDK_NAME = "Skyflow Java SDK "; + public static final String SDK_VERSION = "v2"; + public static final String SDK_PREFIX = SDK_NAME + SDK_VERSION; } diff --git a/v2/src/main/java/com/skyflow/utils/Messages.java b/v2/src/main/java/com/skyflow/utils/Messages.java deleted file mode 100644 index 28144e0a..00000000 --- a/v2/src/main/java/com/skyflow/utils/Messages.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.skyflow.utils; - -public final class Messages { - public final static String INVALID_BEARER_TOKEN = "Invalid bearer token"; - public final static String INVALID_VAULT_ID = "Invalid vault id"; - public final static String INVALID_VAULT_URL = "Invalid vault url"; - // other error messages - - public final static String WARNING_MESSAGE = "Some warning message"; - // other warning messages - - public final static String INFO_MESSAGE = "Some info message"; - // other info messages - - public final static String DEBUG_MESSAGE = "Some debug message"; - // other debug messages -} diff --git a/v2/src/main/java/com/skyflow/utils/Utils.java b/v2/src/main/java/com/skyflow/utils/Utils.java index 7fbf0272..e6811fd3 100644 --- a/v2/src/main/java/com/skyflow/utils/Utils.java +++ b/v2/src/main/java/com/skyflow/utils/Utils.java @@ -2,8 +2,12 @@ import com.skyflow.config.Credentials; import com.skyflow.enums.Env; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; +import com.skyflow.logs.ErrorLogs; import com.skyflow.serviceaccount.util.BearerToken; +import com.skyflow.utils.logger.LogUtil; import org.apache.commons.codec.binary.Base64; import java.io.File; @@ -52,10 +56,8 @@ public static String generateBearerToken(Credentials credentials) throws Skyflow .setCtx(credentials.getContext()) .build() .getBearerToken(); - } else if (credentials.getToken() != null) { - return credentials.getToken(); } else { - return credentials.getApiKey(); + return credentials.getToken(); } } @@ -73,7 +75,8 @@ public static PrivateKey getPrivateKeyFromPem(String pemKey) throws SkyflowExcep privateKeyContent = privateKeyContent.replace("\r\n", ""); privateKey = parsePkcs8PrivateKey(Base64.decodeBase64(privateKeyContent)); } else { - // display error log and throw error + LogUtil.printErrorLog(ErrorLogs.JWT_INVALID_FORMAT.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.JwtInvalidFormat.getMessage()); } return privateKey; } @@ -85,6 +88,13 @@ public static String getBaseURL(String url) throws MalformedURLException { return String.format("%s://%s", protocol, host); } + public static String parameterizedString(String base, String... args) { + for (int index = 0; index < args.length; index++) { + base = base.replace("%s" + (index + 1), args[index]); + } + return base; + } + private static PrivateKey parsePkcs8PrivateKey(byte[] pkcs8Bytes) throws SkyflowException { KeyFactory keyFactory; PrivateKey privateKey = null; @@ -93,9 +103,11 @@ private static PrivateKey parsePkcs8PrivateKey(byte[] pkcs8Bytes) throws Skyflow keyFactory = KeyFactory.getInstance("RSA"); privateKey = keyFactory.generatePrivate(keySpec); } catch (NoSuchAlgorithmException e) { - // display error log and throw error + LogUtil.printErrorLog(ErrorLogs.INVALID_ALGORITHM.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidAlgorithm.getMessage()); } catch (InvalidKeySpecException e) { - // display error log and throw error + LogUtil.printErrorLog(ErrorLogs.INVALID_KEY_SPEC.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidKeySpec.getMessage()); } return privateKey; } diff --git a/v2/src/main/java/com/skyflow/utils/logger/LogUtil.java b/v2/src/main/java/com/skyflow/utils/logger/LogUtil.java new file mode 100644 index 00000000..78cfa038 --- /dev/null +++ b/v2/src/main/java/com/skyflow/utils/logger/LogUtil.java @@ -0,0 +1,100 @@ +package com.skyflow.utils.logger; + +import com.skyflow.enums.LogLevel; +import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.Constants; + +import java.util.logging.*; + +public final class LogUtil { + private static final Logger LOGGER = Logger.getLogger(LogUtil.class.getName()); + private static final String SDK_LOG_PREFIX = "[" + Constants.SDK_PREFIX + "] "; + private static boolean IS_LOGGER_SETUP_DONE = false; + + synchronized public static void setupLogger(LogLevel logLevel) { + IS_LOGGER_SETUP_DONE = true; + LogManager.getLogManager().reset(); + LOGGER.setUseParentHandlers(false); + Formatter formatter = new SimpleFormatter() { + private static final String format = "%s: %s %n"; + + // Override format method + @Override + public synchronized String format(LogRecord logRecord) { + return String.format( + format, + loggerLevelToLogLevelMap(logRecord.getLevel()), + logRecord.getMessage() + ); + } + }; + ConsoleHandler consoleHandler = new ConsoleHandler(); + consoleHandler.setFormatter(formatter); + consoleHandler.setLevel(Level.CONFIG); + + LOGGER.addHandler(consoleHandler); + LOGGER.setLevel(logLevelToLoggerLevelMap(logLevel)); + printInfoLog(InfoLogs.LOGGER_SETUP_DONE.getLog()); + } + + public static void printErrorLog(String message) { + if (IS_LOGGER_SETUP_DONE) + LOGGER.severe(SDK_LOG_PREFIX + message); + else { + setupLogger(LogLevel.ERROR); + LOGGER.severe(SDK_LOG_PREFIX + message); + } + } + + public static void printDebugLog(String message) { + if (IS_LOGGER_SETUP_DONE) + LOGGER.config(SDK_LOG_PREFIX + message); + } + + public static void printWarningLog(String message) { + if (IS_LOGGER_SETUP_DONE) + LOGGER.warning(SDK_LOG_PREFIX + message); + } + + public static void printInfoLog(String message) { + if (IS_LOGGER_SETUP_DONE) + LOGGER.info(SDK_LOG_PREFIX + message); + } + + + private static Level logLevelToLoggerLevelMap(LogLevel logLevel) { + Level loggerLevel; + switch (logLevel) { + case ERROR: + loggerLevel = Level.SEVERE; + break; + case WARN: + loggerLevel = Level.WARNING; + break; + case INFO: + loggerLevel = Level.INFO; + break; + case DEBUG: + loggerLevel = Level.CONFIG; + break; + default: + loggerLevel = Level.OFF; + } + return loggerLevel; + } + + private static LogLevel loggerLevelToLogLevelMap(Level loggerLevel) { + LogLevel logLevel; + if (Level.SEVERE.equals(loggerLevel)) { + logLevel = LogLevel.ERROR; + } else if (Level.WARNING.equals(loggerLevel)) { + logLevel = LogLevel.WARN; + } else if (Level.INFO.equals(loggerLevel)) { + logLevel = LogLevel.INFO; + } else if (Level.CONFIG.equals(loggerLevel)) { + logLevel = LogLevel.DEBUG; + } else + logLevel = LogLevel.OFF; + return logLevel; + } +} diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index e7b4dc1a..bd4a7cd6 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -4,12 +4,17 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; import com.skyflow.enums.Byot; -import com.skyflow.enums.Env; +import com.skyflow.enums.InterfaceName; import com.skyflow.enums.RedactionType; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.utils.ColumnValue; +import com.skyflow.logs.ErrorLogs; import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.logger.LogUtil; import com.skyflow.vault.data.*; +import com.skyflow.vault.tokens.ColumnValue; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; @@ -26,21 +31,19 @@ public class Validations { public static void validateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { String vaultId = vaultConfig.getVaultId(); String clusterId = vaultConfig.getClusterId(); - Env env = vaultConfig.getEnv(); Credentials credentials = vaultConfig.getCredentials(); - if (vaultId == null || vaultId.trim().isEmpty()) { - if (vaultId == null) { - // error log for required - } else { - // error log for empty - } - throw new SkyflowException(); - } else if (clusterId == null || clusterId.trim().isEmpty()) { - // error log - throw new SkyflowException(); - } else if (env == null) { - // error log - throw new SkyflowException(); + if (vaultId == null) { + LogUtil.printErrorLog(ErrorLogs.VAULT_ID_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidVaultId.getMessage()); + } else if (vaultId.trim().isEmpty()) { + LogUtil.printErrorLog(ErrorLogs.EMPTY_VAULT_ID.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyVaultId.getMessage()); + } else if (clusterId == null) { + LogUtil.printErrorLog(ErrorLogs.CLUSTER_ID_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidClusterId.getMessage()); + } else if (clusterId.trim().isEmpty()) { + LogUtil.printErrorLog(ErrorLogs.EMPTY_CLUSTER_ID.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyClusterId.getMessage()); } else if (credentials != null) { validateCredentials(credentials); } @@ -49,16 +52,25 @@ public static void validateVaultConfig(VaultConfig vaultConfig) throws SkyflowEx public static void validateConnectionConfig(ConnectionConfig connectionConfig) throws SkyflowException { String connectionId = connectionConfig.getConnectionId(); String connectionUrl = connectionConfig.getConnectionUrl(); - if (connectionId == null || connectionId.trim().isEmpty()) { - throw new SkyflowException(); - } else if (connectionUrl == null || connectionUrl.trim().isEmpty()) { - throw new SkyflowException(); - } + if (connectionId == null) { + LogUtil.printErrorLog(ErrorLogs.CONNECTION_ID_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidConnectionId.getMessage()); + } else if (connectionId.trim().isEmpty()) { + LogUtil.printErrorLog(ErrorLogs.EMPTY_CONNECTION_ID.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyConnectionId.getMessage()); + } else if (connectionUrl == null) { + LogUtil.printErrorLog(ErrorLogs.CONNECTION_URL_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidConnectionUrl.getMessage()); + } else if (connectionUrl.trim().isEmpty()) { + LogUtil.printErrorLog(ErrorLogs.EMPTY_CONNECTION_URL.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyConnectionUrl.getMessage()); + } try { URL url = new URL(connectionUrl); } catch (MalformedURLException e) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.INVALID_CONNECTION_URL.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidConnectionUrlFormat.getMessage()); } } @@ -68,49 +80,87 @@ public static void validateCredentials(Credentials credentials) throws SkyflowEx String credentialsString = credentials.getCredentialsString(); String token = credentials.getToken(); String apiKey = credentials.getApiKey(); + String context = credentials.getContext(); + ArrayList roles = credentials.getRoles(); if (path != null) nonNullMembers++; if (credentialsString != null) nonNullMembers++; if (token != null) nonNullMembers++; if (apiKey != null) nonNullMembers++; - if (nonNullMembers != 1) { - throw new SkyflowException(); + if (nonNullMembers > 1) { + LogUtil.printErrorLog(ErrorLogs.MULTIPLE_TOKEN_GENERATION_MEANS_PASSED.getLog()); + throw new SkyflowException( + ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MultipleTokenGenerationMeansPassed.getMessage() + ); + } else if (nonNullMembers < 1) { + LogUtil.printErrorLog(ErrorLogs.NO_TOKEN_GENERATION_MEANS_PASSED.getLog()); + throw new SkyflowException( + ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.NoTokenGenerationMeansPassed.getMessage() + ); } else if (path != null && path.trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.EMPTY_CREDENTIALS_PATH.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyCredentialFilePath.getMessage()); } else if (credentialsString != null && credentialsString.trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.EMPTY_CREDENTIALS_STRING.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyCredentialsString.getMessage()); } else if (token != null && token.trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.EMPTY_TOKEN_VALUE.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyToken.getMessage()); } else if (apiKey != null) { if (apiKey.trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.EMPTY_API_KEY_VALUE.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyApikey.getMessage()); } else { Pattern pattern = Pattern.compile(Constants.API_KEY_REGEX); Matcher matcher = pattern.matcher(apiKey); if (!matcher.matches()) { - // invalid api key - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.INVALID_API_KEY.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidApikey.getMessage()); } } + } else if (roles != null) { + if (roles.isEmpty()) { + LogUtil.printErrorLog(ErrorLogs.EMPTY_ROLES.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRoles.getMessage()); + } else { + for (int index = 0; index < roles.size(); index++) { + String role = roles.get(index); + if (role == null || role.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_ROLE_IN_ROLES.getLog(), Integer.toString(index) + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRoleInRoles.getMessage()); + } + } + } + } else if (context != null && context.trim().isEmpty()) { + LogUtil.printErrorLog(ErrorLogs.EMPTY_OR_NULL_CONTEXT.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyContext.getMessage()); } } public static void validateDetokenizeRequest(DetokenizeRequest detokenizeRequest) throws SkyflowException { ArrayList tokens = detokenizeRequest.getTokens(); - RedactionType redactionType = detokenizeRequest.getRedactionType(); - Boolean continueOnError = detokenizeRequest.getContinueOnError(); - if (tokens == null || tokens.isEmpty()) { - throw new SkyflowException(); - } else if (continueOnError == null) { - throw new SkyflowException(); - } else if (redactionType == null) { - throw new SkyflowException(); + if (tokens == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.TOKENS_REQUIRED.getLog(), InterfaceName.DETOKENIZE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidDataTokens.getMessage()); + } else if (tokens.isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_TOKENS.getLog(), InterfaceName.DETOKENIZE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyDataTokens.getMessage()); } else { for (int index = 0; index < tokens.size(); index++) { String token = tokens.get(index); if (token == null || token.trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_TOKEN_IN_TOKENS.getLog(), + InterfaceName.DETOKENIZE.getName(), Integer.toString(index) + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTokenInDataTokens.getMessage()); } } } @@ -124,31 +174,57 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky Boolean homogeneous = insertRequest.getHomogeneous(); Byot tokenStrict = insertRequest.getTokenStrict(); - if (table == null || table.trim().isEmpty()) { - if (table == null) { - // error log for required - } else { - // error log for empty - } - throw new SkyflowException(); - } else if (values == null || values.isEmpty()) { - throw new SkyflowException(); + if (table == null) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.TABLE_IS_REQUIRED.getLog(), InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TableKeyError.getMessage()); + } else if (table.trim().isEmpty()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_TABLE_NAME.getLog(), InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); + } else if (values == null) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.VALUES_IS_REQUIRED.getLog(), InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ValuesKeyError.getMessage()); + } else if (values.isEmpty()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_VALUES.getLog(), InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyValues.getMessage()); } else if (upsert != null) { if (upsert.trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_UPSERT.getLog(), InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyUpsert.getMessage()); } else if (homogeneous != null && homogeneous) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.HOMOGENOUS_NOT_SUPPORTED_WITH_UPSERT.getLog(), InterfaceName.INSERT.getName() + )); + throw new SkyflowException( + ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.HomogenousNotSupportedWithUpsert.getMessage() + ); } } for (HashMap valuesMap : values) { for (String key : valuesMap.keySet()) { if (key == null || key.trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_KEY_IN_VALUES.getLog(), InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyKeyInValues.getMessage()); } else { Object value = valuesMap.get(key); if (value == null || value.toString().trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_VALUE_IN_VALUES.getLog(), + InterfaceName.INSERT.getName(), key + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyValueInValues.getMessage()); } } } @@ -157,20 +233,41 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky switch (tokenStrict) { case DISABLE: if (tokens != null) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.TOKENS_NOT_ALLOWED_WITH_BYOT_DISABLE.getLog(), InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TokensPassedForByotDisable.getMessage()); } break; case ENABLE: if (tokens == null) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.TOKENS_REQUIRED_WITH_BYOT.getLog(), + InterfaceName.INSERT.getName(), Byot.ENABLE.toString() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE.toString()) + ); } validateTokensForInsertRequest(tokens, values); break; case ENABLE_STRICT: if (tokens == null) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.TOKENS_REQUIRED_WITH_BYOT.getLog(), + InterfaceName.INSERT.getName(), Byot.ENABLE_STRICT.toString() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString()) + ); } else if (tokens.size() != values.size()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_BYOT_ENABLE_STRICT.getLog(), + InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage() + ); } validateTokensForInsertRequest(tokens, values); break; @@ -185,72 +282,132 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep List fields = getRequest.getFields(); String offset = getRequest.getOffset(); String limit = getRequest.getLimit(); - Boolean downloadURL = getRequest.getDownloadURL(); String columnName = getRequest.getColumnName(); ArrayList columnValues = getRequest.getColumnValues(); String orderBy = getRequest.getOrderBy(); - if (table == null || table.trim().isEmpty()) { - throw new SkyflowException(); + if (table == null) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.TABLE_IS_REQUIRED.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TableKeyError.getMessage()); + } else if (table.trim().isEmpty()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_TABLE_NAME.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); } else if (ids != null) { if (ids.isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_IDS.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyIds.getMessage()); } else { for (int index = 0; index < ids.size(); index++) { String id = ids.get(index); if (id == null || id.trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_ID_IN_IDS.getLog(), + InterfaceName.GET.getName(), Integer.toString(index) + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyIdInIds.getMessage()); } } } } else if (fields != null) { if (fields.isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_FIELDS.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyFields.getMessage()); } else { for (int index = 0; index < fields.size(); index++) { String field = fields.get(index); if (field == null || field.trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_FIELD_IN_FIELDS.getLog(), + InterfaceName.GET.getName(), Integer.toString(index) + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyFieldInFields.getMessage()); } } } } else if (redactionType == null && (tokenization == null || !tokenization)) { - // missing redaction - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.REDACTION_IS_REQUIRED.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.RedactionKeyError.getMessage()); } else if (tokenization != null && tokenization) { if (redactionType != null) { - // redaction and tokenization does not work together - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.TOKENIZATION_NOT_SUPPORTED_WITH_REDACTION.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.RedactionWithTokensNotSupported.getMessage() + ); } else if (columnName != null || columnValues != null) { - // tokenization does not work with column name/values - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.TOKENIZATION_SUPPORTED_ONLY_WITH_IDS.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.TokensGetColumnNotSupported.getMessage() + ); } } else if (offset != null && offset.isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OFFSET.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyOffset.getMessage()); } else if (limit != null && limit.isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_LIMIT.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyLimit.getMessage()); } if (ids == null && columnName == null && columnValues == null) { - // either skyflow ids or column name/values must be passed - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.NEITHER_IDS_NOR_COLUMN_NAME_PASSED.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.UniqueColumnOrIdsKeyError.getMessage()); } else if (ids != null && (columnName != null || columnValues != null)) { - // skyflow ids and column name/values can not be passed together - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.BOTH_IDS_AND_COLUMN_NAME_PASSED.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.BothIdsAndColumnDetailsSpecified.getMessage()); } else if (columnName == null && columnValues != null) { - // column name and values must both be passed - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.COLUMN_NAME_IS_REQUIRED.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ColumnNameKeyError.getMessage()); } else if (columnName != null && columnValues == null) { - // column name and values must both be passed - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.COLUMN_VALUES_IS_REQUIRED_GET.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ColumnValuesKeyErrorGet.getMessage()); } else if (columnName != null) { - if (columnValues.isEmpty()) { - throw new SkyflowException(); + if (columnName.trim().isEmpty()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_COLUMN_NAME.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyColumnName.getMessage()); + } else if (columnValues.isEmpty()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_COLUMN_VALUES.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyColumnValues.getMessage()); } else { for (int index = 0; index < columnValues.size(); index++) { String columnValue = columnValues.get(index); if (columnValue == null || columnValue.trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_COLUMN_VALUE_IN_COLUMN_VALUES.getLog(), + InterfaceName.GET.getName(), Integer.toString(index) + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.EmptyValueInColumnValues.getMessage()); } } } @@ -260,58 +417,135 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep public static void validateUpdateRequest(UpdateRequest updateRequest) throws SkyflowException { String table = updateRequest.getTable(); String skyflowId = updateRequest.getId(); - Boolean returnTokens = updateRequest.getReturnTokens(); HashMap values = updateRequest.getValues(); HashMap tokens = updateRequest.getTokens(); + Byot tokenStrict = updateRequest.getTokenStrict(); - if (table == null || table.trim().isEmpty()) { - throw new SkyflowException(); - } else if (skyflowId == null || skyflowId.trim().isEmpty()) { - throw new SkyflowException(); - } else if (returnTokens == null) { - throw new SkyflowException(); + if (table == null) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.TABLE_IS_REQUIRED.getLog(), InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TableKeyError.getMessage()); + } else if (table.trim().isEmpty()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_TABLE_NAME.getLog(), InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); + } else if (skyflowId == null) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.SKYFLOW_ID_IS_REQUIRED.getLog(), InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.SkyflowIdKeyError.getMessage()); + } else if (skyflowId.trim().isEmpty()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_SKYFLOW_ID.getLog(), InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptySkyflowId.getMessage()); } else if (values == null || values.isEmpty()) { - throw new SkyflowException(); - } else if (tokens != null) { - if (tokens.isEmpty()) { - throw new SkyflowException(); - } else { - for (String key : tokens.keySet()) { - if (key == null || key.trim().isEmpty()) { - throw new SkyflowException(); - } else { - Object value = tokens.get(key); - if (value == null || value.toString().trim().isEmpty()) { - throw new SkyflowException(); - } - } - } - } + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_VALUES.getLog(), InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyValues.getMessage()); + } else if (tokens != null && tokens.isEmpty()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_TOKENS.getLog(), InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTokens.getMessage()); } for (String key : values.keySet()) { if (key == null || key.trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_KEY_IN_VALUES.getLog(), InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyKeyInValues.getMessage()); } else { Object value = values.get(key); if (value == null || value.toString().trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_VALUE_IN_VALUES.getLog(), InterfaceName.UPDATE.getName(), key + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.EmptyValueInValues.getMessage()); } } } + + switch (tokenStrict) { + case DISABLE: + if (tokens != null) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.TOKENS_NOT_ALLOWED_WITH_BYOT_DISABLE.getLog(), InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.TokensPassedForByotDisable.getMessage()); + } + break; + case ENABLE: + if (tokens == null) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.TOKENS_REQUIRED_WITH_BYOT.getLog(), + InterfaceName.INSERT.getName(), Byot.ENABLE.toString() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( + ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE.toString())); + } + validateTokensMapWithTokenStrict(tokens, values); + break; + case ENABLE_STRICT: + if (tokens == null) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.TOKENS_REQUIRED_WITH_BYOT.getLog(), + InterfaceName.INSERT.getName(), Byot.ENABLE_STRICT.toString() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( + ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString())); + } else if (tokens.size() != values.size()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_BYOT_ENABLE_STRICT.getLog(), + InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage()); + } + validateTokensMapWithTokenStrict(tokens, values); + break; + } } public static void validateDeleteRequest(DeleteRequest deleteRequest) throws SkyflowException { String table = deleteRequest.getTable(); ArrayList ids = deleteRequest.getIds(); - if (table == null || table.trim().isEmpty()) { - throw new SkyflowException(); - } else if (ids == null || ids.isEmpty()) { - throw new SkyflowException(); + if (table == null) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.TABLE_IS_REQUIRED.getLog(), InterfaceName.DELETE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TableKeyError.getMessage()); + } else if (table.trim().isEmpty()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_TABLE_NAME.getLog(), InterfaceName.DELETE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); + + } else if (ids == null) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.IDS_IS_REQUIRED.getLog(), InterfaceName.DELETE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.IdsKeyError.getMessage()); + } else if (ids.isEmpty()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_IDS.getLog(), InterfaceName.DELETE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyIds.getMessage()); } else { - for (String id : ids) { + for (int index = 0; index < ids.size(); index++) { + String id = ids.get(index); if (id.trim().isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_ID_IN_IDS.getLog(), + InterfaceName.DELETE.getName(), Integer.toString(index) + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyIdInIds.getMessage()); } } } @@ -319,8 +553,16 @@ public static void validateDeleteRequest(DeleteRequest deleteRequest) throws Sky public static void validateQueryRequest(QueryRequest queryRequest) throws SkyflowException { String query = queryRequest.getQuery(); - if (query == null || query.trim().isEmpty()) { - throw new SkyflowException(); + if (query == null) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.QUERY_IS_REQUIRED.getLog(), InterfaceName.QUERY.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.QueryKeyError.getMessage()); + } else if (query.trim().isEmpty()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_QUERY.getLog(), InterfaceName.QUERY.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyQuery.getMessage()); } } @@ -328,13 +570,33 @@ public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) thro List columnValues = tokenizeRequest.getColumnValues(); if (columnValues == null || columnValues.isEmpty()) { - throw new SkyflowException(); + if (columnValues == null) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.COLUMN_VALUES_IS_REQUIRED_TOKENIZE.getLog(), InterfaceName.TOKENIZE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ColumnValuesKeyErrorTokenize.getMessage()); + } else { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_COLUMN_VALUES.getLog(), InterfaceName.TOKENIZE.getName() + )); + } + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyColumnValues.getMessage()); } else { - for (ColumnValue value : columnValues) { + for (int index = 0; index < columnValues.size(); index++) { + ColumnValue value = columnValues.get(index); if (value.getValue() == null || value.getValue().isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_COLUMN_VALUE_IN_COLUMN_VALUES.getLog(), + InterfaceName.TOKENIZE.getName(), Integer.toString(index) + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyValueInColumnValues.getMessage()); } else if (value.getColumnGroup() == null || value.getColumnGroup().isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_COLUMN_GROUP_IN_COLUMN_VALUES.getLog(), + InterfaceName.TOKENIZE.getName(), Integer.toString(index) + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.EmptyColumnGroupInColumnValue.getMessage()); } } } @@ -345,23 +607,41 @@ private static void validateTokensForInsertRequest( ArrayList> values ) throws SkyflowException { if (tokens.isEmpty()) { - throw new SkyflowException(); + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_TOKENS.getLog(), InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTokens.getMessage()); } for (int index = 0; index < tokens.size(); index++) { HashMap tokensMap = tokens.get(index); HashMap valuesMap = values.get(index); + validateTokensMapWithTokenStrict(tokensMap, valuesMap); + } + } - for (String key : tokensMap.keySet()) { - if (key == null || key.trim().isEmpty()) { - throw new SkyflowException(); - } else if (!valuesMap.containsKey(key)) { - throw new SkyflowException(); - } else { - Object value = tokensMap.get(key); - if (value == null || value.toString().trim().isEmpty()) { - throw new SkyflowException(); - } + private static void validateTokensMapWithTokenStrict( + HashMap tokensMap, HashMap valuesMap + ) throws SkyflowException { + for (String key : tokensMap.keySet()) { + if (key == null || key.trim().isEmpty()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_KEY_IN_TOKENS.getLog(), InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyKeyInTokens.getMessage()); + } else if (!valuesMap.containsKey(key)) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.MISMATCH_OF_FIELDS_AND_TOKENS.getLog(), InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MismatchOfFieldsAndTokens.getMessage()); + } else { + Object value = tokensMap.get(key); + if (value == null || value.toString().trim().isEmpty()) { + LogUtil.printInfoLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_VALUE_IN_TOKENS.getLog(), + InterfaceName.INSERT.getName(), key + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyValueInTokens.getMessage()); } } } diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index 69abdcee..08204181 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -8,10 +8,10 @@ import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.ApiException; -import com.skyflow.generated.rest.auth.HttpBearerAuth; import com.skyflow.generated.rest.models.*; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.utils.Utils; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.logger.LogUtil; import com.skyflow.utils.validations.Validations; import com.skyflow.vault.data.*; import com.skyflow.vault.tokens.*; @@ -142,17 +142,20 @@ private static synchronized HashMap getFormattedQueryRecord(V1Fi } public InsertResponse insert(InsertRequest insertRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.INSERT_TRIGGERED.getLog()); V1InsertRecordResponse bulkInsertResult = null; V1BatchOperationResponse batchInsertResult = null; ArrayList> insertedFields = new ArrayList<>(); ArrayList> errorFields = new ArrayList<>(); Boolean continueOnError = insertRequest.getContinueOnError(); try { + LogUtil.printInfoLog(InfoLogs.VALIDATE_INSERT_REQUEST.getLog()); Validations.validateInsertRequest(insertRequest); setBearerToken(); if (continueOnError) { RecordServiceBatchOperationBody insertBody = super.getBatchInsertRequestBody(insertRequest); batchInsertResult = super.getRecordsApi().recordServiceBatchOperation(super.getVaultConfig().getVaultId(), insertBody); + LogUtil.printInfoLog(InfoLogs.INSERT_REQUEST_RESOLVED.getLog()); List records = batchInsertResult.getResponses(); for (int index = 0; index < records.size(); index++) { Object record = records.get(index); @@ -167,6 +170,7 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio RecordServiceInsertRecordBody insertBody = super.getBulkInsertRequestBody(insertRequest); bulkInsertResult = super.getRecordsApi().recordServiceInsertRecord( super.getVaultConfig().getVaultId(), insertRequest.getTable(), insertBody); + LogUtil.printInfoLog(InfoLogs.INSERT_REQUEST_RESOLVED.getLog()); List records = bulkInsertResult.getRecords(); if (records != null) { for (V1RecordMetaProperties record : records) { @@ -176,20 +180,25 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio } } } catch (ApiException e) { + LogUtil.printErrorLog(ErrorLogs.INSERT_RECORDS_REJECTED.getLog()); throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } + LogUtil.printInfoLog(InfoLogs.INSERT_SUCCESS.getLog()); return new InsertResponse(insertedFields, errorFields); } public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.DETOKENIZE_TRIGGERED.getLog()); V1DetokenizeResponse result = null; ArrayList detokenizedFields = new ArrayList<>(); ArrayList errorRecords = new ArrayList<>(); try { + LogUtil.printInfoLog(InfoLogs.VALIDATE_DETOKENIZE_REQUEST.getLog()); Validations.validateDetokenizeRequest(detokenizeRequest); setBearerToken(); V1DetokenizePayload payload = super.getDetokenizePayload(detokenizeRequest); result = super.getTokensApi().recordServiceDetokenize(super.getVaultConfig().getVaultId(), payload); + LogUtil.printInfoLog(InfoLogs.DETOKENIZE_REQUEST_RESOLVED.getLog()); List records = result.getRecords(); if (records != null) { for (V1DetokenizeRecordResponse record : records) { @@ -202,21 +211,25 @@ public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws } } } catch (ApiException e) { + LogUtil.printErrorLog(ErrorLogs.DETOKENIZE_REQUEST_REJECTED.getLog()); throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } if (!errorRecords.isEmpty()) { - // handle partial case, throw error and send data in error - // or simply log as a partial success and return proper response + LogUtil.printInfoLog(InfoLogs.DETOKENIZE_PARTIAL_SUCCESS.getLog()); + } else { + LogUtil.printInfoLog(InfoLogs.DETOKENIZE_SUCCESS.getLog()); } return new DetokenizeResponse(detokenizedFields, errorRecords); } public GetResponse get(GetRequest getRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.GET_TRIGGERED.getLog()); V1BulkGetRecordResponse result = null; ArrayList> data = new ArrayList<>(); ArrayList> errors = new ArrayList<>(); try { + LogUtil.printInfoLog(InfoLogs.VALIDATE_GET_REQUEST.getLog()); Validations.validateGetRequest(getRequest); setBearerToken(); RedactionType redactionType = getRequest.getRedactionType(); @@ -234,6 +247,7 @@ public GetResponse get(GetRequest getRequest) throws SkyflowException { getRequest.getColumnValues(), getRequest.getOrderBy() ); + LogUtil.printInfoLog(InfoLogs.GET_REQUEST_RESOLVED.getLog()); List records = result.getRecords(); if (records != null) { for (V1FieldRecords record : records) { @@ -241,16 +255,20 @@ public GetResponse get(GetRequest getRequest) throws SkyflowException { } } } catch (ApiException e) { + LogUtil.printErrorLog(ErrorLogs.GET_REQUEST_REJECTED.getLog()); throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } + LogUtil.printInfoLog(InfoLogs.GET_SUCCESS.getLog()); return new GetResponse(data, errors); } public UpdateResponse update(UpdateRequest updateRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.UPDATE_TRIGGERED.getLog()); V1UpdateRecordResponse result; String skyflowId; HashMap tokensMap; try { + LogUtil.printInfoLog(InfoLogs.VALIDATE_UPDATE_REQUEST.getLog()); Validations.validateUpdateRequest(updateRequest); setBearerToken(); RecordServiceUpdateRecordBody updateBody = super.getUpdateRequestBody(updateRequest); @@ -260,17 +278,22 @@ public UpdateResponse update(UpdateRequest updateRequest) throws SkyflowExceptio updateRequest.getId(), updateBody ); + LogUtil.printInfoLog(InfoLogs.UPDATE_REQUEST_RESOLVED.getLog()); skyflowId = result.getSkyflowId(); tokensMap = getFormattedUpdateRecord(result); } catch (ApiException e) { + LogUtil.printErrorLog(ErrorLogs.UPDATE_REQUEST_REJECTED.getLog()); throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } + LogUtil.printInfoLog(InfoLogs.UPDATE_SUCCESS.getLog()); return new UpdateResponse(skyflowId, tokensMap); } public DeleteResponse delete(DeleteRequest deleteRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.DELETE_TRIGGERED.getLog()); V1BulkDeleteRecordResponse result; try { + LogUtil.printInfoLog(InfoLogs.VALIDATING_DELETE_REQUEST.getLog()); Validations.validateDeleteRequest(deleteRequest); setBearerToken(); RecordServiceBulkDeleteRecordBody deleteBody = new RecordServiceBulkDeleteRecordBody(); @@ -279,9 +302,12 @@ public DeleteResponse delete(DeleteRequest deleteRequest) throws SkyflowExceptio } result = super.getRecordsApi().recordServiceBulkDeleteRecord( super.getVaultConfig().getVaultId(), deleteRequest.getTable(), deleteBody); + LogUtil.printInfoLog(InfoLogs.DELETE_REQUEST_RESOLVED.getLog()); } catch (ApiException e) { + LogUtil.printErrorLog(ErrorLogs.DELETE_REQUEST_REJECTED.getLog()); throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } + LogUtil.printInfoLog(InfoLogs.DELETE_SUCCESS.getLog()); return new DeleteResponse((ArrayList) result.getRecordIDResponse()); } @@ -290,34 +316,41 @@ public Object uploadFile(Object uploadFileRequest) { } public QueryResponse query(QueryRequest queryRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.QUERY_TRIGGERED.getLog()); V1GetQueryResponse result; ArrayList> fields = new ArrayList<>(); try { + LogUtil.printInfoLog(InfoLogs.VALIDATING_QUERY_REQUEST.getLog()); Validations.validateQueryRequest(queryRequest); setBearerToken(); result = super.getQueryApi().queryServiceExecuteQuery( super.getVaultConfig().getVaultId(), new QueryServiceExecuteQueryBody().query(queryRequest.getQuery())); + LogUtil.printInfoLog(InfoLogs.QUERY_REQUEST_RESOLVED.getLog()); if (result.getRecords() != null) { for (V1FieldRecords record : result.getRecords()) { fields.add(getFormattedQueryRecord(record)); } } } catch (ApiException e) { + LogUtil.printErrorLog(ErrorLogs.QUERY_REQUEST_REJECTED.getLog()); throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } + LogUtil.printInfoLog(InfoLogs.QUERY_SUCCESS.getLog()); return new QueryResponse(fields); } public TokenizeResponse tokenize(TokenizeRequest tokenizeRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.TOKENIZE_TRIGGERED.getLog()); V1TokenizeResponse result = null; List list = new ArrayList<>(); try { + LogUtil.printInfoLog(InfoLogs.VALIDATING_TOKENIZE_REQUEST.getLog()); Validations.validateTokenizeRequest(tokenizeRequest); setBearerToken(); V1TokenizePayload payload = super.getTokenizePayload(tokenizeRequest); result = super.getTokensApi().recordServiceTokenize(super.getVaultConfig().getVaultId(), payload); + LogUtil.printInfoLog(InfoLogs.TOKENIZE_REQUEST_RESOLVED.getLog()); if (result != null && result.getRecords().size() > 0) { - for (V1TokenizeRecordResponse response : result.getRecords()) { if (response.getToken() != null) { list.add(response.getToken()); @@ -325,8 +358,10 @@ public TokenizeResponse tokenize(TokenizeRequest tokenizeRequest) throws Skyflow } } } catch (ApiException e) { - throw new SkyflowException(e.getResponseBody()); + LogUtil.printErrorLog(ErrorLogs.TOKENIZE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } + LogUtil.printInfoLog(InfoLogs.TOKENIZE_SUCCESS.getLog()); return new TokenizeResponse(list); } @@ -350,13 +385,4 @@ public DetectController detect() { } return this.detectController; } - - private void setBearerToken() throws SkyflowException { - Validations.validateCredentials(super.getFinalCredentials()); - if (token == null || Token.isExpired(token)) { - token = Utils.generateBearerToken(super.getFinalCredentials()); - } - HttpBearerAuth Bearer = (HttpBearerAuth) super.getApiClient().getAuthentication("Bearer"); - Bearer.setBearerToken(token); - } } diff --git a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java index 402e070c..0a123e33 100644 --- a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java @@ -30,7 +30,7 @@ public RedactionType getRedactionType() { } public Boolean getReturnTokens() { - return returnTokens; + return this.builder.returnTokens; } public List getFields() { diff --git a/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java b/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java index f569e409..e0eaf098 100644 --- a/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java +++ b/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java @@ -1,16 +1,9 @@ package com.skyflow.vault.data; -import com.google.gson.internal.LinkedTreeMap; -import com.skyflow.errors.SkyflowException; -import com.skyflow.generated.rest.models.V1InsertRecordResponse; -import com.skyflow.generated.rest.models.V1RecordMetaProperties; - import java.util.ArrayList; import java.util.HashMap; -import java.util.List; public class InsertResponse { -// private final V1InsertRecordResponse generatedResponse; private final ArrayList> insertedFields; private final ArrayList> errorFields; @@ -19,13 +12,6 @@ public InsertResponse(ArrayList> insertedFields, ArrayLi this.errorFields = errorFields; } -// public InsertResponse(V1InsertRecordResponse response) throws SkyflowException { -// this.generatedResponse = response; -// this.insertedFields = new ArrayList<>(); -// this.errorFields = new ArrayList<>(); -// this.createResponse(); -// } - public ArrayList> getInsertedFields() { return insertedFields; } @@ -34,39 +20,6 @@ public ArrayList> getErrorFields() { return errorFields; } -// private void createResponse() throws SkyflowException { -// List records = this.generatedResponse.getRecords(); -// if (records != null && !records.isEmpty()) { -// createSuccessResponse(records); -// } -// } - -// private void createSuccessResponse(List records) throws SkyflowException { -// try { -// for (V1RecordMetaProperties record : records) { -// HashMap insertRecord = new HashMap<>(); -// -// String skyflowId = record.getSkyflowId(); -// insertRecord.put("skyflowId", skyflowId); -// -// /* -// Getting unchecked cast warning, however, this type is inferred -// from an exception trying to cast into another type. Therefore, -// this type cast will not fail. -// */ -// LinkedTreeMap tokensMap = (LinkedTreeMap) record.getTokens(); -// if (tokensMap != null) { -// for (String key : tokensMap.keySet()) { -// insertRecord.put(key, tokensMap.get(key)); -// } -// } -// insertedFields.add(insertRecord); -// } -// } catch (Exception e) { -// throw new SkyflowException(e); -// } -// } - @Override public String toString() { StringBuilder response = new StringBuilder("{"); diff --git a/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java b/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java index 76c1c4b5..78abcd20 100644 --- a/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java @@ -63,7 +63,7 @@ public UpdateRequestBuilder id(String id) { } public UpdateRequestBuilder returnTokens(Boolean returnTokens) { - this.returnTokens = returnTokens; + this.returnTokens = returnTokens == null || returnTokens; return this; } @@ -78,7 +78,7 @@ public UpdateRequestBuilder tokens(HashMap tokens) { } public UpdateRequestBuilder tokenStrict(Byot tokenStrict) { - this.tokenStrict = tokenStrict; + this.tokenStrict = tokenStrict == null ? Byot.DISABLE : tokenStrict; return this; } diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java index 8c80c932..205ecef7 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java @@ -48,7 +48,7 @@ public DetokenizeRequestBuilder redactionType(RedactionType redactionType) { } public DetokenizeRequestBuilder continueOnError(Boolean continueOnError) { - this.continueOnError = continueOnError; + this.continueOnError = continueOnError == null || continueOnError; return this; } From 4e61b527216a9bbc561f273809e90c5997a2339c Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 1 Nov 2024 21:09:32 +0530 Subject: [PATCH 035/126] =?UTF-8?q?SK-1684=20Add=20unit=20tests=20-=20Adde?= =?UTF-8?q?d=20unit=20tests=20for=20Detokenize=20request=20validations=20-?= =?UTF-8?q?=20Added=20unit=20tests=20for=20Insert=20request=20validations?= =?UTF-8?q?=E2=80=8B=20=E2=80=8B-=20Added=20unit=20tests=20for=20Get=20req?= =?UTF-8?q?uest=20validations=E2=80=8B=20=E2=80=8B-=20Added=20unit=20tests?= =?UTF-8?q?=20for=20Update=20request=20validations=E2=80=8B=20-=20Added=20?= =?UTF-8?q?unit=20tests=20for=20Delete=20request=20validations=E2=80=8B=20?= =?UTF-8?q?=E2=80=8B=E2=80=8B-=20Added=20unit=20tests=20for=20Query=20requ?= =?UTF-8?q?est=20validations=E2=80=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- v2/pom.xml | 15 + v2/src/main/java/com/skyflow/Skyflow.java | 3 +- .../com/skyflow/vault/data/GetRequest.java | 7 +- .../com/skyflow/vault/data/DeleteTests.java | 155 ++++++ .../java/com/skyflow/vault/data/GetTests.java | 471 ++++++++++++++++++ .../com/skyflow/vault/data/InsertTests.java | 375 ++++++++++++++ .../com/skyflow/vault/data/QueryTests.java | 95 ++++ .../com/skyflow/vault/data/UpdateTests.java | 372 ++++++++++++++ .../skyflow/vault/tokens/DetokenizeTests.java | 213 ++++++++ 9 files changed, 1701 insertions(+), 5 deletions(-) create mode 100644 v2/src/test/java/com/skyflow/vault/data/DeleteTests.java create mode 100644 v2/src/test/java/com/skyflow/vault/data/GetTests.java create mode 100644 v2/src/test/java/com/skyflow/vault/data/InsertTests.java create mode 100644 v2/src/test/java/com/skyflow/vault/data/QueryTests.java create mode 100644 v2/src/test/java/com/skyflow/vault/data/UpdateTests.java create mode 100644 v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java diff --git a/v2/pom.xml b/v2/pom.xml index 4e314ed9..bddf1ae2 100644 --- a/v2/pom.xml +++ b/v2/pom.xml @@ -18,6 +18,8 @@ 4.12.0 2.10.1 1.9.0 + 5.10.3 + 1.10.0 @@ -51,5 +53,18 @@ logging-interceptor ${okhttp-version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit-version} + test + + + org.junit.platform + junit-platform-runner + ${junit-platform-runner.version} + test + \ No newline at end of file diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/v2/src/main/java/com/skyflow/Skyflow.java index abc1eea2..cafa32ca 100644 --- a/v2/src/main/java/com/skyflow/Skyflow.java +++ b/v2/src/main/java/com/skyflow/Skyflow.java @@ -128,7 +128,8 @@ public SkyflowClientBuilder addVaultConfig(VaultConfig vaultConfig) throws Skyfl } else { this.vaultConfigMap.put(vaultConfig.getVaultId(), vaultConfig); this.vaultClientsMap.put(vaultConfig.getVaultId(), new VaultController(vaultConfig, this.skyflowCredentials)); - LogUtil.printInfoLog(InfoLogs.VAULT_CONTROLLER_INITIALIZED.getLog()); + LogUtil.printInfoLog(Utils.parameterizedString( + InfoLogs.VAULT_CONTROLLER_INITIALIZED.getLog(), vaultConfig.getVaultId())); } return this; } diff --git a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java index 0a123e33..04626e35 100644 --- a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java +++ b/v2/src/main/java/com/skyflow/vault/data/GetRequest.java @@ -4,7 +4,6 @@ import com.skyflow.utils.Constants; import java.util.ArrayList; -import java.util.List; public class GetRequest { private final GetRequestBuilder builder; @@ -33,7 +32,7 @@ public Boolean getReturnTokens() { return this.builder.returnTokens; } - public List getFields() { + public ArrayList getFields() { return this.builder.fields; } @@ -66,7 +65,7 @@ public static final class GetRequestBuilder { private ArrayList ids; private RedactionType redactionType; private Boolean returnTokens; - private List fields; + private ArrayList fields; private String offset; private String limit; private Boolean downloadURL; @@ -99,7 +98,7 @@ public GetRequestBuilder returnTokens(Boolean returnTokens) { return this; } - public GetRequestBuilder fields(List fields) { + public GetRequestBuilder fields(ArrayList fields) { this.fields = fields; return this; } diff --git a/v2/src/test/java/com/skyflow/vault/data/DeleteTests.java b/v2/src/test/java/com/skyflow/vault/data/DeleteTests.java new file mode 100644 index 00000000..5660522e --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/data/DeleteTests.java @@ -0,0 +1,155 @@ +package com.skyflow.vault.data; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.ArrayList; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") +public class DeleteTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static String skyflowID = null; + private static String table = null; + private static ArrayList ids = null; + private static Skyflow skyflowClient = null; + + @BeforeClass + public static void setup() throws SkyflowException { + PowerMockito.mockStatic(Token.class); + PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); + PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); + + vaultID = "vault123"; + clusterID = "cluster123"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.DEV); +// vaultConfig.setCredentials(credentials); + +// skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + + skyflowID = "test_delete_id_1"; + ids = new ArrayList<>(); + table = "test_table"; + } + + @Test + public void testValidInputInDeleteRequestValidations() { + try { + ids.add(skyflowID); + DeleteRequest request = DeleteRequest.builder().ids(ids).table(table).build(); + Validations.validateDeleteRequest(request); + Assert.assertEquals(1, ids.size()); + Assert.assertEquals(table, request.getTable()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoIdsInDeleteRequestValidations() { + DeleteRequest request = DeleteRequest.builder().table(table).build(); + try { + Validations.validateDeleteRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.IdsKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyIdsInDeleteRequestValidations() { + ids.clear(); + DeleteRequest request = DeleteRequest.builder().ids(ids).table(table).build(); + try { + Validations.validateDeleteRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyIds.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyIdInIdsInDeleteRequestValidations() { + ids.add(skyflowID); + ids.add(""); + DeleteRequest request = DeleteRequest.builder().ids(ids).table(table).build(); + try { + Validations.validateDeleteRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyIdInIds.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoTableInDeleteRequestValidations() { + ids.clear(); + ids.add(skyflowID); + DeleteRequest request = DeleteRequest.builder().ids(ids).build(); + try { + Validations.validateDeleteRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyTableInDeleteRequestValidations() { + ids.clear(); + ids.add(skyflowID); + DeleteRequest request = DeleteRequest.builder().ids(ids).table("").build(); + try { + Validations.validateDeleteRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyTable.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } +} diff --git a/v2/src/test/java/com/skyflow/vault/data/GetTests.java b/v2/src/test/java/com/skyflow/vault/data/GetTests.java new file mode 100644 index 00000000..66e5cddb --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/data/GetTests.java @@ -0,0 +1,471 @@ +package com.skyflow.vault.data; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.ArrayList; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") +public class GetTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static String skyflowID = null; + private static String field = null; + private static String table = null; + private static ArrayList ids = null; + private static ArrayList fields = null; + private static String columnName = null; + private static String columnValue = null; + private static ArrayList columnValues = null; + private static Skyflow skyflowClient = null; + + @BeforeClass + public static void setup() throws SkyflowException { + PowerMockito.mockStatic(Token.class); + PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); + PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); + + vaultID = "vault123"; + clusterID = "cluster123"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.DEV); + vaultConfig.setCredentials(credentials); + +// skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + + skyflowID = "test_get_id_1"; + ids = new ArrayList<>(); + field = "test_get_field"; + fields = new ArrayList<>(); + columnName = "test_column_name"; + columnValue = "test_column_value"; + columnValues = new ArrayList<>(); + table = "test_table"; + } + + @Test + public void testValidGetByIdInputInGetRequestValidations() { + try { + ids.add(skyflowID); + fields.add(field); + GetRequest request = GetRequest.builder() + .ids(ids) + .table(table) + .returnTokens(true) + .downloadURL(true) + .offset("2") + .limit("1") + .fields(fields) + .orderBy(Constants.ORDER_ASCENDING) + .build(); + Validations.validateGetRequest(request); + Assert.assertEquals(table, request.getTable()); + Assert.assertEquals(1, request.getIds().size()); + Assert.assertEquals(1, request.getFields().size()); + Assert.assertEquals("2", request.getOffset()); + Assert.assertEquals("1", request.getLimit()); + Assert.assertEquals(Constants.ORDER_ASCENDING, request.getOrderBy()); + Assert.assertTrue(request.getDownloadURL()); + Assert.assertTrue(request.getReturnTokens()); + Assert.assertNull(request.getRedactionType()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testValidGetByColumnValuesInputInGetRequestValidations() { + try { + columnValues.add(columnValue); + GetRequest request = GetRequest.builder() + .table(table) + .columnName(columnName) + .columnValues(columnValues) + .redactionType(RedactionType.PLAIN_TEXT) + .downloadURL(true) + .offset("2") + .limit("1") + .fields(fields) + .orderBy(Constants.ORDER_ASCENDING) + .build(); + Validations.validateGetRequest(request); + Assert.assertEquals(table, request.getTable()); + Assert.assertEquals(columnName, request.getColumnName()); + Assert.assertEquals(1, request.getColumnValues().size()); + Assert.assertEquals(1, request.getFields().size()); + Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); + Assert.assertEquals("2", request.getOffset()); + Assert.assertEquals("1", request.getLimit()); + Assert.assertEquals(Constants.ORDER_ASCENDING, request.getOrderBy()); + Assert.assertTrue(request.getDownloadURL()); + Assert.assertNull(request.getReturnTokens()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoTableInGetRequestValidations() { + ids.clear(); + ids.add(skyflowID); + GetRequest request = GetRequest.builder().ids(ids).build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyTableInGetRequestValidations() { + ids.clear(); + ids.add(skyflowID); + GetRequest request = GetRequest.builder().ids(ids).table("").build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyTable.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyIdsInGetRequestValidations() { + ids.clear(); + GetRequest request = GetRequest.builder().ids(ids).table(table).build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyIds.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyIdInIdsInGetRequestValidations() { + ids.add(skyflowID); + ids.add(""); + GetRequest request = GetRequest.builder().ids(ids).table(table).build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyIdInIds.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyFieldsInGetRequestValidations() { + ids.clear(); + ids.add(skyflowID); + fields.clear(); + GetRequest request = GetRequest.builder().ids(ids).table(table).fields(fields).build(); + try { + System.out.println(ids); + System.out.println(fields); + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyFields.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyFieldInFieldsInGetRequestValidations() { + fields.add(field); + fields.add(""); + GetRequest request = GetRequest.builder().ids(ids).table(table).fields(fields).build(); + try { + System.out.println(ids); + System.out.println(fields); + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyFieldInFields.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoRedactionInGetRequestValidations() { + GetRequest request = GetRequest.builder().table(table).build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.RedactionKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testReturnTokensWithRedactionInGetRequestValidations() { + GetRequest request = GetRequest.builder() + .table(table).redactionType(RedactionType.PLAIN_TEXT).returnTokens(true) + .build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.RedactionWithTokensNotSupported.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testReturnTokensWithColumnNameInGetRequestValidations() { + GetRequest request = GetRequest.builder().table(table).returnTokens(true).columnName(columnName).build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TokensGetColumnNotSupported.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testReturnTokensWithColumnValuesInGetRequestValidations() { + GetRequest request = GetRequest.builder().table(table).returnTokens(true).columnValues(columnValues).build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TokensGetColumnNotSupported.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyOffsetInGetRequestValidations() { + GetRequest request = GetRequest.builder() + .table(table).redactionType(RedactionType.PLAIN_TEXT).offset("") + .build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyOffset.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyLimitInGetRequestValidations() { + GetRequest request = GetRequest.builder() + .table(table).redactionType(RedactionType.PLAIN_TEXT).limit("") + .build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyLimit.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoIdsOrColumnNameInGetRequestValidations() { + GetRequest request = GetRequest.builder().table(table).redactionType(RedactionType.PLAIN_TEXT).build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.UniqueColumnOrIdsKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testBothIdsAndColumnNameInGetRequestValidations() { + GetRequest request = GetRequest.builder() + .table(table).redactionType(RedactionType.PLAIN_TEXT).ids(ids).columnName(columnName) + .build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.BothIdsAndColumnDetailsSpecified.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testBothIdsAndColumnValuesInGetRequestValidations() { + GetRequest request = GetRequest.builder() + .table(table).redactionType(RedactionType.PLAIN_TEXT).ids(ids).columnValues(columnValues) + .build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.BothIdsAndColumnDetailsSpecified.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testColumnNameWithoutColumnValuesInGetRequestValidations() { + GetRequest request = GetRequest.builder() + .table(table).redactionType(RedactionType.PLAIN_TEXT).columnName(columnName) + .build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.ColumnValuesKeyErrorGet.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testColumnValuesWithoutColumnNameInGetRequestValidations() { + GetRequest request = GetRequest.builder() + .table(table).redactionType(RedactionType.PLAIN_TEXT).columnValues(columnValues) + .build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.ColumnNameKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyColumnNameInGetRequestValidations() { + GetRequest request = GetRequest.builder() + .table(table).redactionType(RedactionType.PLAIN_TEXT).columnName("").columnValues(columnValues) + .build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyColumnName.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyColumnValuesInGetRequestValidations() { + columnValues.clear(); + GetRequest request = GetRequest.builder() + .table(table).redactionType(RedactionType.PLAIN_TEXT).columnName(columnName).columnValues(columnValues) + .build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyColumnValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyValueInColumnValuesInGetRequestValidations() { + columnValues.add(columnValue); + columnValues.add(""); + GetRequest request = GetRequest.builder() + .table(table).redactionType(RedactionType.PLAIN_TEXT).columnName(columnName).columnValues(columnValues) + .build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyValueInColumnValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } +} diff --git a/v2/src/test/java/com/skyflow/vault/data/InsertTests.java b/v2/src/test/java/com/skyflow/vault/data/InsertTests.java new file mode 100644 index 00000000..2b1c8432 --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/data/InsertTests.java @@ -0,0 +1,375 @@ +package com.skyflow.vault.data; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Byot; +import com.skyflow.enums.Env; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.ArrayList; +import java.util.HashMap; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") +public class InsertTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static String table = null; + private static ArrayList> values = null; + private static ArrayList> tokens = null; + private static HashMap valueMap = null; + private static HashMap tokenMap = null; + private static String upsert = null; + private static Skyflow skyflowClient = null; + + @BeforeClass + public static void setup() throws SkyflowException { + PowerMockito.mockStatic(Token.class); + PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); + PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); + + vaultID = "vault123"; + clusterID = "cluster123"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.DEV); + vaultConfig.setCredentials(credentials); + +// skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + + table = "test_table"; + values = new ArrayList<>(); + tokens = new ArrayList<>(); + valueMap = new HashMap<>(); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap = new HashMap<>(); + tokenMap.put("test_column_1", "test_token_1"); + upsert = "upsert_column"; + } + + @Test + public void testValidInputInInsertRequestValidations() { + try { + values.add(valueMap); + tokens.add(tokenMap); + InsertRequest request = InsertRequest.builder() + .table(table) + .continueOnError(true) + .returnTokens(true) + .homogeneous(false) + .upsert(upsert) + .values(values) + .tokens(tokens) + .tokenMode(true) + .tokenStrict(Byot.ENABLE) + .build(); + Validations.validateInsertRequest(request); + + Assert.assertEquals(table, request.getTable()); + Assert.assertEquals(upsert, request.getUpsert()); + Assert.assertEquals(1, request.getValues().size()); + Assert.assertEquals(1, request.getTokens().size()); + Assert.assertEquals(Byot.ENABLE, request.getTokenStrict()); + Assert.assertTrue(request.getContinueOnError()); + Assert.assertFalse(request.getHomogeneous()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoTableInInsertRequestValidations() { + InsertRequest request = InsertRequest.builder().build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyTableInInsertRequestValidations() { + InsertRequest request = InsertRequest.builder().table("").build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyTable.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoValuesInInsertRequestValidations() { + InsertRequest request = InsertRequest.builder().table(table).build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.ValuesKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyValuesInInsertRequestValidations() { + values.clear(); + InsertRequest request = InsertRequest.builder().table(table).values(values).build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyKeyInValuesInInsertRequestValidations() { + valueMap.put("", "test_value_3"); + values.add(valueMap); + InsertRequest request = InsertRequest.builder().table(table).values(values).build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyKeyInValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyValueInValuesInInsertRequestValidations() { + valueMap.remove(""); + valueMap.put("test_column_3", ""); + InsertRequest request = InsertRequest.builder().table(table).values(values).build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyValueInValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyUpsertInInsertRequestValidations() { + valueMap.remove("test_column_3"); + InsertRequest request = InsertRequest.builder().table(table).values(values).upsert("").build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyUpsert.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testUpsertWithHomogenousInInsertRequestValidations() { + InsertRequest request = InsertRequest.builder() + .table(table).values(values).upsert(upsert).homogeneous(true) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.HomogenousNotSupportedWithUpsert.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testTokensWithTokenStrictDisableInInsertRequestValidations() { + InsertRequest request = InsertRequest.builder().table(table).values(values).tokens(tokens).build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TokensPassedForByotDisable.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoTokensWithTokenStrictEnableInInsertRequestValidations() { + InsertRequest request = InsertRequest.builder() + .table(table).values(values).tokenStrict(Byot.ENABLE) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE.toString()), + e.getMessage() + ); + } + } + + @Test + public void testNoTokensWithTokenStrictEnableStrictInInsertRequestValidations() { + InsertRequest request = InsertRequest.builder() + .table(table).values(values).tokenStrict(Byot.ENABLE_STRICT) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString()), + e.getMessage() + ); + } + } + + @Test + public void testEmptyTokensWithTokenStrictEnableInInsertRequestValidations() { + tokens.clear(); + InsertRequest request = InsertRequest.builder() + .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testInsufficientTokensWithTokenStrictEnableStrictInInsertRequestValidations1() { + tokens.add(tokenMap); + System.out.println(values); + System.out.println(tokens); + InsertRequest request = InsertRequest.builder() + .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage(), e.getMessage()); + } + } + + @Test + public void testInsufficientTokensWithTokenStrictEnableStrictInInsertRequestValidations2() { + values.add(valueMap); + InsertRequest request = InsertRequest.builder() + .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage(), e.getMessage()); + } + } + + @Test + public void testTokenValueMismatchInInsertRequestValidations() { + tokenMap.put("test_column_3", "test_token_3"); + values.remove(1); + InsertRequest request = InsertRequest.builder() + .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.MismatchOfFieldsAndTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyKeyInTokensInInsertRequestValidations() { + tokenMap.remove("test_column_2"); + tokenMap.remove("test_column_3"); + tokenMap.put("", "test_token_2"); + InsertRequest request = InsertRequest.builder() + .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyKeyInTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyValueInTokensInInsertRequestValidations() { + tokenMap.remove(""); + tokenMap.put("test_column_2", ""); + InsertRequest request = InsertRequest.builder() + .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyValueInTokens.getMessage(), e.getMessage()); + } + } + +} diff --git a/v2/src/test/java/com/skyflow/vault/data/QueryTests.java b/v2/src/test/java/com/skyflow/vault/data/QueryTests.java new file mode 100644 index 00000000..141704a1 --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/data/QueryTests.java @@ -0,0 +1,95 @@ +package com.skyflow.vault.data; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") +public class QueryTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static String query = null; + private static Skyflow skyflowClient = null; + + @BeforeClass + public static void setup() throws SkyflowException { + PowerMockito.mockStatic(Token.class); + PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); + PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); + + vaultID = "vault123"; + clusterID = "cluster123"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.DEV); + vaultConfig.setCredentials(credentials); + + query = "test_query"; + +// skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + } + + @Test + public void testValidInputInQueryRequestValidations() { + try { + QueryRequest request = QueryRequest.builder().query(query).build(); + Validations.validateQueryRequest(request); + Assert.assertEquals(query, request.getQuery()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoQueryInQueryRequestValidations() { + QueryRequest request = QueryRequest.builder().build(); + try { + Validations.validateQueryRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.QueryKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyQueryInQueryRequestValidations() { + QueryRequest request = QueryRequest.builder().query("").build(); + try { + Validations.validateQueryRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyQuery.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } +} diff --git a/v2/src/test/java/com/skyflow/vault/data/UpdateTests.java b/v2/src/test/java/com/skyflow/vault/data/UpdateTests.java new file mode 100644 index 00000000..5a72001c --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/data/UpdateTests.java @@ -0,0 +1,372 @@ +package com.skyflow.vault.data; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Byot; +import com.skyflow.enums.Env; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.HashMap; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") +public class UpdateTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static String skyflowID = null; + private static String table = null; + private static HashMap valueMap = null; + private static HashMap tokenMap = null; + private static Skyflow skyflowClient = null; + + @BeforeClass + public static void setup() throws SkyflowException { + PowerMockito.mockStatic(Token.class); + PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); + PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); + + vaultID = "vault123"; + clusterID = "cluster123"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.DEV); + vaultConfig.setCredentials(credentials); + +// skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + + skyflowID = "test_update_id_1"; + table = "test_table"; + valueMap = new HashMap<>(); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap = new HashMap<>(); + tokenMap.put("test_column_1", "test_token_1"); + } + + @Test + public void testValidInputInUpdateRequestValidations() { + try { + UpdateRequest request = UpdateRequest.builder() + .id(skyflowID) + .table(table) + .values(valueMap) + .tokens(tokenMap) + .returnTokens(true) + .tokenStrict(Byot.ENABLE) + .build(); + Validations.validateUpdateRequest(request); + Assert.assertEquals(table, request.getTable()); + Assert.assertEquals(skyflowID, request.getId()); + Assert.assertEquals(2, request.getValues().size()); + Assert.assertEquals(1, request.getTokens().size()); + Assert.assertTrue(request.getReturnTokens()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoSkyflowIdInUpdateRequestValidations() { + UpdateRequest request = UpdateRequest.builder().table(table).build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.SkyflowIdKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptySkyflowIdInUpdateRequestValidations() { + UpdateRequest request = UpdateRequest.builder().id("").table(table).build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptySkyflowId.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoTableInUpdateRequestValidations() { + UpdateRequest request = UpdateRequest.builder().id(skyflowID).build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyTableInUpdateRequestValidations() { + UpdateRequest request = UpdateRequest.builder().id(skyflowID).table("").build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyTable.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoValuesInUpdateRequestValidations() { + UpdateRequest request = UpdateRequest.builder().id(skyflowID).table(table).build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.ValuesKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyValuesInUpdateRequestValidations() { + HashMap emptyValueMap = new HashMap<>(); + UpdateRequest request = UpdateRequest.builder().id(skyflowID).table(table).values(emptyValueMap).build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyKeyInValuesInUpdateRequestValidations() { + valueMap.put("", "test_value_3"); + UpdateRequest request = UpdateRequest.builder().id(skyflowID).table(table).values(valueMap).build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyKeyInValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyValueInValuesInUpdateRequestValidations() { + valueMap.remove(""); + valueMap.put("test_column_3", ""); + UpdateRequest request = UpdateRequest.builder().id(skyflowID).table(table).values(valueMap).build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyValueInValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testTokensWithTokenStrictDisableInUpdateRequestValidations() { + valueMap.remove("test_column_3"); + UpdateRequest request = UpdateRequest.builder() + .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.DISABLE) + .build(); + try { + System.out.println(valueMap); + System.out.println(tokenMap); + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TokensPassedForByotDisable.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoTokensWithTokenStrictEnableInUpdateRequestValidations() { + UpdateRequest request = UpdateRequest.builder() + .id(skyflowID).table(table).values(valueMap).tokenStrict(Byot.ENABLE) + .build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE.toString()), + e.getMessage() + ); + } + } + + @Test + public void testNoTokensWithTokenStrictEnableStrictInUpdateRequestValidations() { + UpdateRequest request = UpdateRequest.builder() + .id(skyflowID).table(table).values(valueMap).tokenStrict(Byot.ENABLE_STRICT) + .build(); + try { + System.out.println(valueMap); + System.out.println(tokenMap); + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString()), + e.getMessage() + ); + } + } + + @Test + public void testEmptyTokensWithTokenStrictEnableInUpdateRequestValidations() { + HashMap emptyTokenMap = new HashMap<>(); + UpdateRequest request = UpdateRequest.builder() + .id(skyflowID).table(table).values(valueMap).tokens(emptyTokenMap).tokenStrict(Byot.ENABLE) + .build(); + try { + System.out.println(valueMap); + System.out.println(tokenMap); + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestValidations1() { + UpdateRequest request = UpdateRequest.builder() + .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) + .build(); + try { + System.out.println(valueMap); + System.out.println(tokenMap); + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage(), e.getMessage()); + } + } + + @Test + public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestValidations2() { + UpdateRequest request = UpdateRequest.builder() + .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) + .build(); + try { + System.out.println(valueMap); + System.out.println(tokenMap); + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage(), e.getMessage()); + } + } + + @Test + public void testTokenValueMismatchInUpdateRequestValidations() { + tokenMap.put("test_column_3", "test_token_3"); + UpdateRequest request = UpdateRequest.builder() + .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) + .build(); + try { + System.out.println(valueMap); + System.out.println(tokenMap); + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.MismatchOfFieldsAndTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyKeyInTokensInUpdateRequestValidations() { + tokenMap.remove("test_column_2"); + tokenMap.remove("test_column_3"); + tokenMap.put("", "test_token_2"); + UpdateRequest request = UpdateRequest.builder() + .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) + .build(); + try { + System.out.println(valueMap); + System.out.println(tokenMap); + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyKeyInTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyValueInTokensInUpdateRequestValidations() { + tokenMap.remove(""); + tokenMap.put("test_column_2", ""); + UpdateRequest request = UpdateRequest.builder() + .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) + .build(); + try { + System.out.println(valueMap); + System.out.println(tokenMap); + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyValueInTokens.getMessage(), e.getMessage()); + } + } + +} diff --git a/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java new file mode 100644 index 00000000..04dd406d --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -0,0 +1,213 @@ +package com.skyflow.vault.tokens; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.ApiException; +import com.skyflow.generated.rest.api.TokensApi; +import com.skyflow.generated.rest.models.V1DetokenizeResponse; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.ArgumentMatchers; +import org.powermock.api.mockito.PowerMockito; + +import java.util.ArrayList; + +//@RunWith(PowerMockRunner.class) +//@PrepareForTest(fullyQualifiedNames = { +// "com.skyflow.serviceaccount.util.Token", +// "com.skyflow.generated.rest.ApiClient", +// "com.skyflow.generated.rest.api.TokensApi", +//}) +public class DetokenizeTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static VaultConfig vaultConfig = null; + private static String token = null; + private static ArrayList tokens = null; + private static Skyflow skyflowClient = null; + + @BeforeClass + public static void setup() throws SkyflowException, NoSuchMethodException { +// PowerMockito.mockStatic(Token.class); +// PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); +// PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); +// PowerMockito.mock(ApiClient.class); + + vaultID = "vault123"; + clusterID = "cluster123"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.DEV); + vaultConfig.setCredentials(credentials); + + token = "test_token_1"; + tokens = new ArrayList<>(); + } + + @Test + public void testValidInputInDetokenizeRequestValidations() { + try { + tokens.add(token); + DetokenizeRequest request = DetokenizeRequest.builder(). + tokens(tokens).redactionType(RedactionType.MASKED).continueOnError(false).build(); + Validations.validateDetokenizeRequest(request); + Assert.assertEquals(1, tokens.size()); + Assert.assertEquals(RedactionType.MASKED, request.getRedactionType()); + Assert.assertFalse(request.getContinueOnError()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoTokensInDetokenizeRequestValidations() { + DetokenizeRequest request = DetokenizeRequest.builder().build(); + try { + Validations.validateDetokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.InvalidDataTokens.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); + Assert.assertTrue(request.getContinueOnError()); + } + } + + @Test + public void testEmptyTokensInDetokenizeRequestValidations() { + tokens.clear(); + DetokenizeRequest request = DetokenizeRequest.builder().tokens(tokens).build(); + try { + Validations.validateDetokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyDataTokens.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); + Assert.assertTrue(request.getContinueOnError()); + } + } + + @Test + public void testEmptyTokenInTokensInDetokenizeRequestValidations() { + tokens.add(token); + tokens.add(""); + DetokenizeRequest request = DetokenizeRequest.builder().tokens(tokens).build(); + try { + Validations.validateDetokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyTokenInDataTokens.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); + Assert.assertTrue(request.getContinueOnError()); + } + } + + @Test + public void testRedactionAndContinueOnErrorInDetokenizeRequestValidations() { + tokens.clear(); + tokens.add(token); + DetokenizeRequest request = DetokenizeRequest.builder(). + tokens(tokens).redactionType(null).continueOnError(null).build(); + try { + Validations.validateDetokenizeRequest(request); + Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); + Assert.assertTrue(request.getContinueOnError()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoTokensInDetokenizeMethod() { + DetokenizeRequest request = DetokenizeRequest.builder().build(); + try { + V1DetokenizeResponse mockResponse = new V1DetokenizeResponse(); + TokensApi mockApi = PowerMockito.mock(TokensApi.class); + PowerMockito + .when(mockApi.recordServiceDetokenize(ArgumentMatchers.anyString(), ArgumentMatchers.any())) + .thenReturn(mockResponse); + + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + DetokenizeResponse response = skyflowClient.vault().detokenize(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.InvalidDataTokens.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); + Assert.assertTrue(request.getContinueOnError()); + } catch (ApiException e) { + Assert.fail(); + } + } + + @Test + public void testEmptyTokensInDetokenizeMethod() { + tokens.clear(); + DetokenizeRequest request = DetokenizeRequest.builder().tokens(tokens).build(); + try { + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + DetokenizeResponse response = skyflowClient.vault().detokenize(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyDataTokens.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); + Assert.assertTrue(request.getContinueOnError()); + } + } + + @Test + public void testEmptyTokenInTokensInDetokenizeMethod() { + tokens.add(token); + tokens.add(""); + DetokenizeRequest request = DetokenizeRequest.builder().tokens(tokens).build(); + try { + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + DetokenizeResponse response = skyflowClient.vault().detokenize(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyTokenInDataTokens.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); + Assert.assertTrue(request.getContinueOnError()); + } + } +} From 184124b2a8ba70d917b9caa234e3a8193ce2607b Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 1 Nov 2024 21:11:44 +0530 Subject: [PATCH 036/126] SK-1680 Changed info logs to error logs in validation checks - SK-1681 Updated validation checks for Get request interface --- .../utils/validations/Validations.java | 155 ++++++++++-------- 1 file changed, 87 insertions(+), 68 deletions(-) diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index bd4a7cd6..266bb0aa 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -175,33 +175,33 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky Byot tokenStrict = insertRequest.getTokenStrict(); if (table == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TABLE_IS_REQUIRED.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TableKeyError.getMessage()); } else if (table.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_TABLE_NAME.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); } else if (values == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.VALUES_IS_REQUIRED.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ValuesKeyError.getMessage()); } else if (values.isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_VALUES.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyValues.getMessage()); } else if (upsert != null) { if (upsert.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_UPSERT.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyUpsert.getMessage()); } else if (homogeneous != null && homogeneous) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.HOMOGENOUS_NOT_SUPPORTED_WITH_UPSERT.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException( @@ -213,14 +213,14 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky for (HashMap valuesMap : values) { for (String key : valuesMap.keySet()) { if (key == null || key.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_KEY_IN_VALUES.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyKeyInValues.getMessage()); } else { Object value = valuesMap.get(key); if (value == null || value.toString().trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_VALUE_IN_VALUES.getLog(), InterfaceName.INSERT.getName(), key )); @@ -233,7 +233,7 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky switch (tokenStrict) { case DISABLE: if (tokens != null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TOKENS_NOT_ALLOWED_WITH_BYOT_DISABLE.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TokensPassedForByotDisable.getMessage()); @@ -241,7 +241,7 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky break; case ENABLE: if (tokens == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TOKENS_REQUIRED_WITH_BYOT.getLog(), InterfaceName.INSERT.getName(), Byot.ENABLE.toString() )); @@ -249,11 +249,11 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE.toString()) ); } - validateTokensForInsertRequest(tokens, values); + validateTokensForInsertRequest(tokens, values, tokenStrict); break; case ENABLE_STRICT: if (tokens == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TOKENS_REQUIRED_WITH_BYOT.getLog(), InterfaceName.INSERT.getName(), Byot.ENABLE_STRICT.toString() )); @@ -261,7 +261,7 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString()) ); } else if (tokens.size() != values.size()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_BYOT_ENABLE_STRICT.getLog(), InterfaceName.INSERT.getName() )); @@ -269,7 +269,7 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage() ); } - validateTokensForInsertRequest(tokens, values); + validateTokensForInsertRequest(tokens, values, tokenStrict); break; } } @@ -279,7 +279,7 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep ArrayList ids = getRequest.getIds(); RedactionType redactionType = getRequest.getRedactionType(); Boolean tokenization = getRequest.getReturnTokens(); - List fields = getRequest.getFields(); + ArrayList fields = getRequest.getFields(); String offset = getRequest.getOffset(); String limit = getRequest.getLimit(); String columnName = getRequest.getColumnName(); @@ -287,18 +287,18 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep String orderBy = getRequest.getOrderBy(); if (table == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TABLE_IS_REQUIRED.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TableKeyError.getMessage()); } else if (table.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_TABLE_NAME.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); } else if (ids != null) { if (ids.isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_IDS.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyIds.getMessage()); @@ -306,7 +306,7 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep for (int index = 0; index < ids.size(); index++) { String id = ids.get(index); if (id == null || id.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_ID_IN_IDS.getLog(), InterfaceName.GET.getName(), Integer.toString(index) )); @@ -314,9 +314,10 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep } } } - } else if (fields != null) { + } + if (fields != null) { if (fields.isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_FIELDS.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyFields.getMessage()); @@ -324,7 +325,7 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep for (int index = 0; index < fields.size(); index++) { String field = fields.get(index); if (field == null || field.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_FIELD_IN_FIELDS.getLog(), InterfaceName.GET.getName(), Integer.toString(index) )); @@ -332,69 +333,72 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep } } } - } else if (redactionType == null && (tokenization == null || !tokenization)) { - LogUtil.printInfoLog(Utils.parameterizedString( + } + if (redactionType == null && (tokenization == null || !tokenization)) { + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.REDACTION_IS_REQUIRED.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.RedactionKeyError.getMessage()); - } else if (tokenization != null && tokenization) { + } + if (tokenization != null && tokenization) { if (redactionType != null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TOKENIZATION_NOT_SUPPORTED_WITH_REDACTION.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.RedactionWithTokensNotSupported.getMessage() ); } else if (columnName != null || columnValues != null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TOKENIZATION_SUPPORTED_ONLY_WITH_IDS.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TokensGetColumnNotSupported.getMessage() ); } - } else if (offset != null && offset.isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + } + if (offset != null && offset.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OFFSET.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyOffset.getMessage()); - } else if (limit != null && limit.isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + } + if (limit != null && limit.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_LIMIT.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyLimit.getMessage()); } - if (ids == null && columnName == null && columnValues == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.NEITHER_IDS_NOR_COLUMN_NAME_PASSED.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.UniqueColumnOrIdsKeyError.getMessage()); } else if (ids != null && (columnName != null || columnValues != null)) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.BOTH_IDS_AND_COLUMN_NAME_PASSED.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.BothIdsAndColumnDetailsSpecified.getMessage()); } else if (columnName == null && columnValues != null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.COLUMN_NAME_IS_REQUIRED.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ColumnNameKeyError.getMessage()); } else if (columnName != null && columnValues == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.COLUMN_VALUES_IS_REQUIRED_GET.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ColumnValuesKeyErrorGet.getMessage()); } else if (columnName != null) { if (columnName.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_COLUMN_NAME.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyColumnName.getMessage()); } else if (columnValues.isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_COLUMN_VALUES.getLog(), InterfaceName.GET.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyColumnValues.getMessage()); @@ -402,7 +406,7 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep for (int index = 0; index < columnValues.size(); index++) { String columnValue = columnValues.get(index); if (columnValue == null || columnValue.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_COLUMN_VALUE_IN_COLUMN_VALUES.getLog(), InterfaceName.GET.getName(), Integer.toString(index) )); @@ -422,32 +426,37 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky Byot tokenStrict = updateRequest.getTokenStrict(); if (table == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TABLE_IS_REQUIRED.getLog(), InterfaceName.UPDATE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TableKeyError.getMessage()); } else if (table.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_TABLE_NAME.getLog(), InterfaceName.UPDATE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); } else if (skyflowId == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.SKYFLOW_ID_IS_REQUIRED.getLog(), InterfaceName.UPDATE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.SkyflowIdKeyError.getMessage()); } else if (skyflowId.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_SKYFLOW_ID.getLog(), InterfaceName.UPDATE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptySkyflowId.getMessage()); - } else if (values == null || values.isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + } else if (values == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.VALUES_IS_REQUIRED.getLog(), InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ValuesKeyError.getMessage()); + } else if (values.isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_VALUES.getLog(), InterfaceName.UPDATE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyValues.getMessage()); } else if (tokens != null && tokens.isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_TOKENS.getLog(), InterfaceName.UPDATE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTokens.getMessage()); @@ -455,14 +464,14 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky for (String key : values.keySet()) { if (key == null || key.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_KEY_IN_VALUES.getLog(), InterfaceName.UPDATE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyKeyInValues.getMessage()); } else { Object value = values.get(key); if (value == null || value.toString().trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_VALUE_IN_VALUES.getLog(), InterfaceName.UPDATE.getName(), key )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), @@ -474,7 +483,7 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky switch (tokenStrict) { case DISABLE: if (tokens != null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TOKENS_NOT_ALLOWED_WITH_BYOT_DISABLE.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), @@ -483,7 +492,7 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky break; case ENABLE: if (tokens == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TOKENS_REQUIRED_WITH_BYOT.getLog(), InterfaceName.INSERT.getName(), Byot.ENABLE.toString() )); @@ -494,14 +503,14 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky break; case ENABLE_STRICT: if (tokens == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TOKENS_REQUIRED_WITH_BYOT.getLog(), InterfaceName.INSERT.getName(), Byot.ENABLE_STRICT.toString() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString())); } else if (tokens.size() != values.size()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_BYOT_ENABLE_STRICT.getLog(), InterfaceName.INSERT.getName() )); @@ -517,23 +526,23 @@ public static void validateDeleteRequest(DeleteRequest deleteRequest) throws Sky String table = deleteRequest.getTable(); ArrayList ids = deleteRequest.getIds(); if (table == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TABLE_IS_REQUIRED.getLog(), InterfaceName.DELETE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TableKeyError.getMessage()); } else if (table.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_TABLE_NAME.getLog(), InterfaceName.DELETE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); } else if (ids == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.IDS_IS_REQUIRED.getLog(), InterfaceName.DELETE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.IdsKeyError.getMessage()); } else if (ids.isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_IDS.getLog(), InterfaceName.DELETE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyIds.getMessage()); @@ -541,7 +550,7 @@ public static void validateDeleteRequest(DeleteRequest deleteRequest) throws Sky for (int index = 0; index < ids.size(); index++) { String id = ids.get(index); if (id.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_ID_IN_IDS.getLog(), InterfaceName.DELETE.getName(), Integer.toString(index) )); @@ -554,12 +563,12 @@ public static void validateDeleteRequest(DeleteRequest deleteRequest) throws Sky public static void validateQueryRequest(QueryRequest queryRequest) throws SkyflowException { String query = queryRequest.getQuery(); if (query == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.QUERY_IS_REQUIRED.getLog(), InterfaceName.QUERY.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.QueryKeyError.getMessage()); } else if (query.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_QUERY.getLog(), InterfaceName.QUERY.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyQuery.getMessage()); @@ -571,12 +580,12 @@ public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) thro if (columnValues == null || columnValues.isEmpty()) { if (columnValues == null) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.COLUMN_VALUES_IS_REQUIRED_TOKENIZE.getLog(), InterfaceName.TOKENIZE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ColumnValuesKeyErrorTokenize.getMessage()); } else { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_COLUMN_VALUES.getLog(), InterfaceName.TOKENIZE.getName() )); } @@ -585,13 +594,13 @@ public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) thro for (int index = 0; index < columnValues.size(); index++) { ColumnValue value = columnValues.get(index); if (value.getValue() == null || value.getValue().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_COLUMN_VALUE_IN_COLUMN_VALUES.getLog(), InterfaceName.TOKENIZE.getName(), Integer.toString(index) )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyValueInColumnValues.getMessage()); } else if (value.getColumnGroup() == null || value.getColumnGroup().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_COLUMN_GROUP_IN_COLUMN_VALUES.getLog(), InterfaceName.TOKENIZE.getName(), Integer.toString(index) )); @@ -604,10 +613,11 @@ public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) thro private static void validateTokensForInsertRequest( ArrayList> tokens, - ArrayList> values + ArrayList> values, + Byot tokenStrict ) throws SkyflowException { if (tokens.isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_TOKENS.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTokens.getMessage()); @@ -616,6 +626,15 @@ private static void validateTokensForInsertRequest( for (int index = 0; index < tokens.size(); index++) { HashMap tokensMap = tokens.get(index); HashMap valuesMap = values.get(index); + if (tokensMap.size() != valuesMap.size() && tokenStrict == Byot.ENABLE_STRICT) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_BYOT_ENABLE_STRICT.getLog(), + InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage() + ); + } validateTokensMapWithTokenStrict(tokensMap, valuesMap); } } @@ -625,19 +644,19 @@ private static void validateTokensMapWithTokenStrict( ) throws SkyflowException { for (String key : tokensMap.keySet()) { if (key == null || key.trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_KEY_IN_TOKENS.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyKeyInTokens.getMessage()); } else if (!valuesMap.containsKey(key)) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.MISMATCH_OF_FIELDS_AND_TOKENS.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MismatchOfFieldsAndTokens.getMessage()); } else { Object value = tokensMap.get(key); if (value == null || value.toString().trim().isEmpty()) { - LogUtil.printInfoLog(Utils.parameterizedString( + LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_VALUE_IN_TOKENS.getLog(), InterfaceName.INSERT.getName(), key )); From 8df4058d66aafd78d911e7d4227a453609462a42 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 5 Nov 2024 20:32:14 +0530 Subject: [PATCH 037/126] SK-1684 Add unit tests - Add unit tests for configs i.e. vault, connection and credentials - Add unit tests for response pojo classes for few vault API interfaces --- .../com/skyflow/config/ConnectionConfig.java | 4 + .../java/com/skyflow/config/VaultConfig.java | 5 - .../utils/validations/Validations.java | 3 +- .../skyflow/vault/data/DeleteResponse.java | 2 +- .../com/skyflow/vault/data/QueryResponse.java | 2 +- .../skyflow/vault/data/UpdateResponse.java | 4 +- .../vault/config/ConnectionConfigTests.java | 144 ++++++++++ .../vault/config/CredentialsTests.java | 262 ++++++++++++++++++ .../vault/config/VaultConfigTests.java | 174 ++++++++++++ .../com/skyflow/vault/data/DeleteTests.java | 12 + .../java/com/skyflow/vault/data/GetTests.java | 22 +- .../com/skyflow/vault/data/InsertTests.java | 4 +- .../com/skyflow/vault/data/QueryTests.java | 23 ++ .../com/skyflow/vault/data/UpdateTests.java | 31 +-- .../vault/serviceaccount/util/TokenTests.java | 46 +++ 15 files changed, 700 insertions(+), 38 deletions(-) create mode 100644 v2/src/test/java/com/skyflow/vault/config/ConnectionConfigTests.java create mode 100644 v2/src/test/java/com/skyflow/vault/config/CredentialsTests.java create mode 100644 v2/src/test/java/com/skyflow/vault/config/VaultConfigTests.java create mode 100644 v2/src/test/java/com/skyflow/vault/serviceaccount/util/TokenTests.java diff --git a/v2/src/main/java/com/skyflow/config/ConnectionConfig.java b/v2/src/main/java/com/skyflow/config/ConnectionConfig.java index f0821de7..7661df0d 100644 --- a/v2/src/main/java/com/skyflow/config/ConnectionConfig.java +++ b/v2/src/main/java/com/skyflow/config/ConnectionConfig.java @@ -27,6 +27,10 @@ public void setConnectionUrl(String connectionUrl) { this.connectionUrl = connectionUrl; } + public Credentials getCredentials() { + return credentials; + } + public void setCredentials(Credentials credentials) { this.credentials = credentials; } diff --git a/v2/src/main/java/com/skyflow/config/VaultConfig.java b/v2/src/main/java/com/skyflow/config/VaultConfig.java index 2e757c7b..fd36d384 100644 --- a/v2/src/main/java/com/skyflow/config/VaultConfig.java +++ b/v2/src/main/java/com/skyflow/config/VaultConfig.java @@ -1,7 +1,6 @@ package com.skyflow.config; import com.skyflow.enums.Env; -import com.skyflow.utils.Utils; public class VaultConfig { private String vaultId; @@ -48,10 +47,6 @@ public void setCredentials(Credentials credentials) { this.credentials = credentials; } - public String getVaultURL() { - return Utils.getVaultURL(this.clusterId, this.env); - } - @Override public String toString() { return "VaultConfig {" + diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index 266bb0aa..f0c44956 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -134,7 +134,8 @@ public static void validateCredentials(Credentials credentials) throws SkyflowEx } } } - } else if (context != null && context.trim().isEmpty()) { + } + if (context != null && context.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_OR_NULL_CONTEXT.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyContext.getMessage()); } diff --git a/v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java b/v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java index 0024c68a..21adc788 100644 --- a/v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java +++ b/v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java @@ -3,7 +3,7 @@ import java.util.ArrayList; public class DeleteResponse { - private ArrayList deletedIds; + private final ArrayList deletedIds; public DeleteResponse(ArrayList deletedIds) { this.deletedIds = deletedIds; diff --git a/v2/src/main/java/com/skyflow/vault/data/QueryResponse.java b/v2/src/main/java/com/skyflow/vault/data/QueryResponse.java index 72d1e316..e8103506 100644 --- a/v2/src/main/java/com/skyflow/vault/data/QueryResponse.java +++ b/v2/src/main/java/com/skyflow/vault/data/QueryResponse.java @@ -4,7 +4,7 @@ import java.util.HashMap; public class QueryResponse { - private ArrayList> fields; + private final ArrayList> fields; private ArrayList> tokenizedData; public QueryResponse(ArrayList> fields) { diff --git a/v2/src/main/java/com/skyflow/vault/data/UpdateResponse.java b/v2/src/main/java/com/skyflow/vault/data/UpdateResponse.java index 05ae30bd..0f860b22 100644 --- a/v2/src/main/java/com/skyflow/vault/data/UpdateResponse.java +++ b/v2/src/main/java/com/skyflow/vault/data/UpdateResponse.java @@ -3,8 +3,8 @@ import java.util.HashMap; public class UpdateResponse { - private String skyflowId; - private HashMap tokens; + private final String skyflowId; + private final HashMap tokens; public UpdateResponse(String skyflowId, HashMap tokens) { this.skyflowId = skyflowId; diff --git a/v2/src/test/java/com/skyflow/vault/config/ConnectionConfigTests.java b/v2/src/test/java/com/skyflow/vault/config/ConnectionConfigTests.java new file mode 100644 index 00000000..648ad98d --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/config/ConnectionConfigTests.java @@ -0,0 +1,144 @@ +package com.skyflow.vault.config; + +import com.skyflow.config.ConnectionConfig; +import com.skyflow.config.Credentials; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") +public class ConnectionConfigTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String connectionID = null; + private static String connectionURL = null; + private static String invalidConnectionURL = null; + private static Credentials credentials = null; + + @BeforeClass + public static void setup() throws SkyflowException, NoSuchMethodException { + PowerMockito.mockStatic(Token.class); + PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); + PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); + PowerMockito.mock(ApiClient.class); + + connectionID = "connection123"; + connectionURL = "https://connection.url.com"; + invalidConnectionURL = "invalid.connection.url.com"; + + credentials = new Credentials(); + credentials.setToken("valid-token"); + } + + @Test + public void testValidConnectionConfigWithCredentials() { + try { + ConnectionConfig connectionConfig = new ConnectionConfig(); + connectionConfig.setConnectionId(connectionID); + connectionConfig.setConnectionUrl(connectionURL); + connectionConfig.setCredentials(credentials); + Validations.validateConnectionConfig(connectionConfig); + + Assert.assertEquals(connectionID, connectionConfig.getConnectionId()); + Assert.assertEquals(connectionURL, connectionConfig.getConnectionUrl()); + Assert.assertNotNull(connectionConfig.getCredentials()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testValidConnectionConfigWithoutCredentials() { + try { + ConnectionConfig connectionConfig = new ConnectionConfig(); + connectionConfig.setConnectionId(connectionID); + connectionConfig.setConnectionUrl(connectionURL); + Validations.validateConnectionConfig(connectionConfig); + + Assert.assertEquals(connectionID, connectionConfig.getConnectionId()); + Assert.assertEquals(connectionURL, connectionConfig.getConnectionUrl()); + Assert.assertNull(connectionConfig.getCredentials()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoConnectionIdInConnectionConfig() { + ConnectionConfig connectionConfig = new ConnectionConfig(); + try { + connectionConfig.setConnectionUrl(connectionURL); + Validations.validateConnectionConfig(connectionConfig); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidConnectionId.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyConnectionIdInConnectionConfig() { + try { + ConnectionConfig connectionConfig = new ConnectionConfig(); + connectionConfig.setConnectionId(""); + connectionConfig.setConnectionUrl(connectionURL); + Validations.validateConnectionConfig(connectionConfig); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyConnectionId.getMessage(), e.getMessage()); + } + } + + @Test + public void testNoConnectionURLInConnectionConfig() { + try { + ConnectionConfig connectionConfig = new ConnectionConfig(); + connectionConfig.setConnectionId(connectionID); + Validations.validateConnectionConfig(connectionConfig); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidConnectionUrl.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyConnectionURLInConnectionConfig() { + try { + ConnectionConfig connectionConfig = new ConnectionConfig(); + connectionConfig.setConnectionId(connectionID); + connectionConfig.setConnectionUrl(""); + Validations.validateConnectionConfig(connectionConfig); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyConnectionUrl.getMessage(), e.getMessage()); + } + } + + @Test + public void testInvalidConnectionURLInConnectionConfig() { + try { + ConnectionConfig connectionConfig = new ConnectionConfig(); + connectionConfig.setConnectionId(connectionID); + connectionConfig.setConnectionUrl(invalidConnectionURL); + Validations.validateConnectionConfig(connectionConfig); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidConnectionUrlFormat.getMessage(), e.getMessage()); + } + } +} diff --git a/v2/src/test/java/com/skyflow/vault/config/CredentialsTests.java b/v2/src/test/java/com/skyflow/vault/config/CredentialsTests.java new file mode 100644 index 00000000..554f7f0d --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/config/CredentialsTests.java @@ -0,0 +1,262 @@ +package com.skyflow.vault.config; + +import com.skyflow.config.Credentials; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.ArrayList; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") +public class CredentialsTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String path = null; + private static String credentialsString = null; + private static String token = null; + private static String validApiKey = null; + private static String invalidApiKey = null; + private static ArrayList roles = null; + private static String role = null; + private static String context = null; + + @BeforeClass + public static void setup() throws SkyflowException, NoSuchMethodException { + PowerMockito.mockStatic(Token.class); + PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); + PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); + PowerMockito.mock(ApiClient.class); + + path = "valid-path-to-credentials-file"; + credentialsString = "valid-credentials-string"; + token = "valid-token"; + validApiKey = "sky-ab123-abcd1234cdef1234abcd4321cdef4321"; + invalidApiKey = "invalid-api-key"; + roles = new ArrayList<>(); + role = "test_credentials_role"; + context = "test_context_value"; + } + + @Test + public void testValidCredentialsWithPath() { + try { + Credentials credentials = new Credentials(); + credentials.setPath(path); + Validations.validateCredentials(credentials); + Assert.assertNull(credentials.getCredentialsString()); + Assert.assertNull(credentials.getToken()); + Assert.assertNull(credentials.getApiKey()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testValidCredentialsWithCredentialsString() { + try { + Credentials credentials = new Credentials(); + credentials.setCredentialsString(credentialsString); + Validations.validateCredentials(credentials); + Assert.assertNull(credentials.getPath()); + Assert.assertNull(credentials.getToken()); + Assert.assertNull(credentials.getApiKey()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testValidCredentialsWithToken() { + try { + Credentials credentials = new Credentials(); + credentials.setToken(token); + Validations.validateCredentials(credentials); + Assert.assertNull(credentials.getPath()); + Assert.assertNull(credentials.getCredentialsString()); + Assert.assertNull(credentials.getApiKey()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testValidCredentialsWithApikey() { + try { + Credentials credentials = new Credentials(); + credentials.setApiKey(validApiKey); + Validations.validateCredentials(credentials); + Assert.assertNull(credentials.getPath()); + Assert.assertNull(credentials.getCredentialsString()); + Assert.assertNull(credentials.getToken()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testValidCredentialsWithRolesAndContext() { + try { + roles.add(role); + Credentials credentials = new Credentials(); + credentials.setApiKey(validApiKey); + credentials.setRoles(roles); + credentials.setContext(context); + Validations.validateCredentials(credentials); + Assert.assertNull(credentials.getPath()); + Assert.assertNull(credentials.getCredentialsString()); + Assert.assertNull(credentials.getToken()); + Assert.assertEquals(context, credentials.getContext()); + Assert.assertEquals(1, credentials.getRoles().size()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testEmptyPathInCredentials() { + try { + Credentials credentials = new Credentials(); + credentials.setPath(""); + Validations.validateCredentials(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyCredentialFilePath.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyCredentialsStringInCredentials() { + try { + Credentials credentials = new Credentials(); + credentials.setCredentialsString(""); + Validations.validateCredentials(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyCredentialsString.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyTokenInCredentials() { + try { + Credentials credentials = new Credentials(); + credentials.setToken(""); + Validations.validateCredentials(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyToken.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyApikeyInCredentials() { + try { + Credentials credentials = new Credentials(); + credentials.setApiKey(""); + Validations.validateCredentials(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyApikey.getMessage(), e.getMessage()); + } + } + + @Test + public void testInvalidApikeyInCredentials() { + try { + Credentials credentials = new Credentials(); + credentials.setApiKey(invalidApiKey); + Validations.validateCredentials(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidApikey.getMessage(), e.getMessage()); + } + } + + @Test + public void testBothTokenAndPathInCredentials() { + try { + Credentials credentials = new Credentials(); + credentials.setPath(path); + credentials.setToken(token); + Validations.validateCredentials(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.MultipleTokenGenerationMeansPassed.getMessage(), e.getMessage()); + } + } + + @Test + public void testNothingPassedInCredentials() { + try { + Credentials credentials = new Credentials(); + Validations.validateCredentials(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.NoTokenGenerationMeansPassed.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyRolesInCredentials() { + try { + roles.clear(); + Credentials credentials = new Credentials(); + credentials.setPath(path); + credentials.setRoles(roles); + Validations.validateCredentials(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyRoles.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyRoleInRolesInCredentials() { + try { + Credentials credentials = new Credentials(); + credentials.setPath(path); + roles.add(role); + roles.add(""); + credentials.setRoles(roles); + Validations.validateCredentials(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyRoleInRoles.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyContextInCredentials() { + try { + Credentials credentials = new Credentials(); + credentials.setPath(path); + credentials.setContext(""); + Validations.validateCredentials(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyContext.getMessage(), e.getMessage()); + } + } + +} diff --git a/v2/src/test/java/com/skyflow/vault/config/VaultConfigTests.java b/v2/src/test/java/com/skyflow/vault/config/VaultConfigTests.java new file mode 100644 index 00000000..011f2990 --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/config/VaultConfigTests.java @@ -0,0 +1,174 @@ +package com.skyflow.vault.config; + +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") +public class VaultConfigTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static Credentials credentials = null; + + + @BeforeClass + public static void setup() throws SkyflowException, NoSuchMethodException { + PowerMockito.mockStatic(Token.class); + PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); + PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); + PowerMockito.mock(ApiClient.class); + + vaultID = "vault123"; + clusterID = "cluster123"; + + credentials = new Credentials(); + credentials.setToken("valid-token"); + + } + + @Test + public void testValidVaultConfigWithCredentials() { + try { + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.SANDBOX); + vaultConfig.setCredentials(credentials); + Validations.validateVaultConfig(vaultConfig); + + Assert.assertEquals(vaultID, vaultConfig.getVaultId()); + Assert.assertEquals(clusterID, vaultConfig.getClusterId()); + Assert.assertEquals(Env.SANDBOX, vaultConfig.getEnv()); + Assert.assertNotNull(vaultConfig.getCredentials()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testValidVaultConfigWithoutCredentials() { + try { + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.SANDBOX); + Validations.validateVaultConfig(vaultConfig); + + Assert.assertEquals(vaultID, vaultConfig.getVaultId()); + Assert.assertEquals(clusterID, vaultConfig.getClusterId()); + Assert.assertEquals(Env.SANDBOX, vaultConfig.getEnv()); + Assert.assertNull(vaultConfig.getCredentials()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testDefaultEnvInVaultConfigWithCredentials() { + try { + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setCredentials(credentials); + Validations.validateVaultConfig(vaultConfig); + + Assert.assertEquals(vaultID, vaultConfig.getVaultId()); + Assert.assertEquals(clusterID, vaultConfig.getClusterId()); + Assert.assertEquals(Env.PROD, vaultConfig.getEnv()); + Assert.assertNotNull(vaultConfig.getCredentials()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testDefaultEnvInVaultConfigWithoutCredentials() { + try { + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + Validations.validateVaultConfig(vaultConfig); + + Assert.assertEquals(vaultID, vaultConfig.getVaultId()); + Assert.assertEquals(clusterID, vaultConfig.getClusterId()); + Assert.assertEquals(Env.PROD, vaultConfig.getEnv()); + Assert.assertNull(vaultConfig.getCredentials()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoVaultIdInVaultConfig() { + VaultConfig vaultConfig = new VaultConfig(); + try { + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.SANDBOX); + Validations.validateVaultConfig(vaultConfig); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidVaultId.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyVaultIdInVaultConfig() { + try { + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.SANDBOX); + Validations.validateVaultConfig(vaultConfig); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyVaultId.getMessage(), e.getMessage()); + } + } + + @Test + public void testNoClusterIdInVaultConfig() { + try { + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setEnv(Env.SANDBOX); + Validations.validateVaultConfig(vaultConfig); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidClusterId.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyClusterIdInVaultConfig() { + try { + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(""); + vaultConfig.setEnv(Env.SANDBOX); + Validations.validateVaultConfig(vaultConfig); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyClusterId.getMessage(), e.getMessage()); + } + } +} diff --git a/v2/src/test/java/com/skyflow/vault/data/DeleteTests.java b/v2/src/test/java/com/skyflow/vault/data/DeleteTests.java index 5660522e..9ab78af6 100644 --- a/v2/src/test/java/com/skyflow/vault/data/DeleteTests.java +++ b/v2/src/test/java/com/skyflow/vault/data/DeleteTests.java @@ -152,4 +152,16 @@ public void testEmptyTableInDeleteRequestValidations() { ); } } + + @Test + public void testDeleteResponse() { + try { + DeleteResponse response = new DeleteResponse(ids); + String responseString = "{\n\t\"deletedIds\": [\n\t\t\"" + skyflowID + "\"]\n}"; + Assert.assertEquals(1, response.getDeletedIds().size()); + Assert.assertEquals(responseString, response.toString()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } } diff --git a/v2/src/test/java/com/skyflow/vault/data/GetTests.java b/v2/src/test/java/com/skyflow/vault/data/GetTests.java index 66e5cddb..ac6625fe 100644 --- a/v2/src/test/java/com/skyflow/vault/data/GetTests.java +++ b/v2/src/test/java/com/skyflow/vault/data/GetTests.java @@ -13,6 +13,7 @@ import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @@ -69,6 +70,13 @@ public static void setup() throws SkyflowException { table = "test_table"; } + @Before + public void setupTest() { + ids.clear(); + fields.clear(); + columnValues.clear(); + } + @Test public void testValidGetByIdInputInGetRequestValidations() { try { @@ -103,6 +111,7 @@ public void testValidGetByIdInputInGetRequestValidations() { public void testValidGetByColumnValuesInputInGetRequestValidations() { try { columnValues.add(columnValue); + fields.add(field); GetRequest request = GetRequest.builder() .table(table) .columnName(columnName) @@ -132,7 +141,6 @@ public void testValidGetByColumnValuesInputInGetRequestValidations() { @Test public void testNoTableInGetRequestValidations() { - ids.clear(); ids.add(skyflowID); GetRequest request = GetRequest.builder().ids(ids).build(); try { @@ -149,7 +157,6 @@ public void testNoTableInGetRequestValidations() { @Test public void testEmptyTableInGetRequestValidations() { - ids.clear(); ids.add(skyflowID); GetRequest request = GetRequest.builder().ids(ids).table("").build(); try { @@ -166,7 +173,6 @@ public void testEmptyTableInGetRequestValidations() { @Test public void testEmptyIdsInGetRequestValidations() { - ids.clear(); GetRequest request = GetRequest.builder().ids(ids).table(table).build(); try { Validations.validateGetRequest(request); @@ -199,13 +205,9 @@ public void testEmptyIdInIdsInGetRequestValidations() { @Test public void testEmptyFieldsInGetRequestValidations() { - ids.clear(); ids.add(skyflowID); - fields.clear(); GetRequest request = GetRequest.builder().ids(ids).table(table).fields(fields).build(); try { - System.out.println(ids); - System.out.println(fields); Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { @@ -219,12 +221,11 @@ public void testEmptyFieldsInGetRequestValidations() { @Test public void testEmptyFieldInFieldsInGetRequestValidations() { + ids.add(skyflowID); fields.add(field); fields.add(""); GetRequest request = GetRequest.builder().ids(ids).table(table).fields(fields).build(); try { - System.out.println(ids); - System.out.println(fields); Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { @@ -349,6 +350,7 @@ public void testNoIdsOrColumnNameInGetRequestValidations() { @Test public void testBothIdsAndColumnNameInGetRequestValidations() { + ids.add(skyflowID); GetRequest request = GetRequest.builder() .table(table).redactionType(RedactionType.PLAIN_TEXT).ids(ids).columnName(columnName) .build(); @@ -366,6 +368,7 @@ public void testBothIdsAndColumnNameInGetRequestValidations() { @Test public void testBothIdsAndColumnValuesInGetRequestValidations() { + ids.add(skyflowID); GetRequest request = GetRequest.builder() .table(table).redactionType(RedactionType.PLAIN_TEXT).ids(ids).columnValues(columnValues) .build(); @@ -434,7 +437,6 @@ public void testEmptyColumnNameInGetRequestValidations() { @Test public void testEmptyColumnValuesInGetRequestValidations() { - columnValues.clear(); GetRequest request = GetRequest.builder() .table(table).redactionType(RedactionType.PLAIN_TEXT).columnName(columnName).columnValues(columnValues) .build(); diff --git a/v2/src/test/java/com/skyflow/vault/data/InsertTests.java b/v2/src/test/java/com/skyflow/vault/data/InsertTests.java index 2b1c8432..f49f9c20 100644 --- a/v2/src/test/java/com/skyflow/vault/data/InsertTests.java +++ b/v2/src/test/java/com/skyflow/vault/data/InsertTests.java @@ -93,6 +93,8 @@ public void testValidInputInInsertRequestValidations() { Assert.assertEquals(1, request.getTokens().size()); Assert.assertEquals(Byot.ENABLE, request.getTokenStrict()); Assert.assertTrue(request.getContinueOnError()); + Assert.assertTrue(request.getReturnTokens()); + Assert.assertTrue(request.getTokenMode()); Assert.assertFalse(request.getHomogeneous()); } catch (SkyflowException e) { Assert.fail(INVALID_EXCEPTION_THROWN); @@ -294,8 +296,6 @@ public void testEmptyTokensWithTokenStrictEnableInInsertRequestValidations() { @Test public void testInsufficientTokensWithTokenStrictEnableStrictInInsertRequestValidations1() { tokens.add(tokenMap); - System.out.println(values); - System.out.println(tokens); InsertRequest request = InsertRequest.builder() .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) .build(); diff --git a/v2/src/test/java/com/skyflow/vault/data/QueryTests.java b/v2/src/test/java/com/skyflow/vault/data/QueryTests.java index 141704a1..3197a83c 100644 --- a/v2/src/test/java/com/skyflow/vault/data/QueryTests.java +++ b/v2/src/test/java/com/skyflow/vault/data/QueryTests.java @@ -19,6 +19,9 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import java.util.ArrayList; +import java.util.HashMap; + @RunWith(PowerMockRunner.class) @PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") public class QueryTests { @@ -28,6 +31,7 @@ public class QueryTests { private static String clusterID = null; private static String query = null; private static Skyflow skyflowClient = null; + private static HashMap queryRecord = null; @BeforeClass public static void setup() throws SkyflowException { @@ -48,6 +52,9 @@ public static void setup() throws SkyflowException { vaultConfig.setCredentials(credentials); query = "test_query"; + queryRecord = new HashMap<>(); + queryRecord.put("name", "test_name"); + queryRecord.put("card_number", "test_card_number"); // skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); } @@ -92,4 +99,20 @@ public void testEmptyQueryInQueryRequestValidations() { ); } } + + @Test + public void testQueryResponse() { + try { + ArrayList> fields = new ArrayList<>(); + fields.add(queryRecord); + QueryResponse response = new QueryResponse(fields); + String responseString = "{\n\t\"fields\": " + + "[{\n\t\t\"card_number\": \"test_card_number\",\n\t\t\"name\": \"test_name\"," + + "\n\t\t\"tokenizedData\": " + null + "\n\t}]\n}"; + Assert.assertEquals(1, response.getFields().size()); + Assert.assertEquals(responseString, response.toString()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } } diff --git a/v2/src/test/java/com/skyflow/vault/data/UpdateTests.java b/v2/src/test/java/com/skyflow/vault/data/UpdateTests.java index 5a72001c..3780a417 100644 --- a/v2/src/test/java/com/skyflow/vault/data/UpdateTests.java +++ b/v2/src/test/java/com/skyflow/vault/data/UpdateTests.java @@ -217,8 +217,6 @@ public void testTokensWithTokenStrictDisableInUpdateRequestValidations() { .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.DISABLE) .build(); try { - System.out.println(valueMap); - System.out.println(tokenMap); Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { @@ -253,8 +251,6 @@ public void testNoTokensWithTokenStrictEnableStrictInUpdateRequestValidations() .id(skyflowID).table(table).values(valueMap).tokenStrict(Byot.ENABLE_STRICT) .build(); try { - System.out.println(valueMap); - System.out.println(tokenMap); Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { @@ -273,8 +269,6 @@ public void testEmptyTokensWithTokenStrictEnableInUpdateRequestValidations() { .id(skyflowID).table(table).values(valueMap).tokens(emptyTokenMap).tokenStrict(Byot.ENABLE) .build(); try { - System.out.println(valueMap); - System.out.println(tokenMap); Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { @@ -289,8 +283,6 @@ public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestVali .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) .build(); try { - System.out.println(valueMap); - System.out.println(tokenMap); Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { @@ -305,8 +297,6 @@ public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestVali .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) .build(); try { - System.out.println(valueMap); - System.out.println(tokenMap); Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { @@ -322,8 +312,6 @@ public void testTokenValueMismatchInUpdateRequestValidations() { .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) .build(); try { - System.out.println(valueMap); - System.out.println(tokenMap); Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { @@ -341,8 +329,6 @@ public void testEmptyKeyInTokensInUpdateRequestValidations() { .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) .build(); try { - System.out.println(valueMap); - System.out.println(tokenMap); Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { @@ -359,8 +345,6 @@ public void testEmptyValueInTokensInUpdateRequestValidations() { .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) .build(); try { - System.out.println(valueMap); - System.out.println(tokenMap); Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { @@ -369,4 +353,19 @@ public void testEmptyValueInTokensInUpdateRequestValidations() { } } + @Test + public void testUpdateResponse() { + try { + tokenMap.put("test_column_2", "test_token_2"); + UpdateResponse response = new UpdateResponse(skyflowID, tokenMap); + String responseString = "{\n\t\"skyflowId\": " + skyflowID + "\n\t\"tokens\": " + + "{\n\t\t\"test_column_1\": \"test_token_1\"," + + "\n\t\t\"test_column_2\": \"test_token_2\",\n\t}\n}"; + Assert.assertEquals(skyflowID, response.getSkyflowId()); + Assert.assertEquals(2, response.getTokens().size()); + Assert.assertEquals(responseString, response.toString()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } } diff --git a/v2/src/test/java/com/skyflow/vault/serviceaccount/util/TokenTests.java b/v2/src/test/java/com/skyflow/vault/serviceaccount/util/TokenTests.java new file mode 100644 index 00000000..3a3d8f6e --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/serviceaccount/util/TokenTests.java @@ -0,0 +1,46 @@ +package com.skyflow.vault.serviceaccount.util; + +import com.skyflow.serviceaccount.util.Token; +import org.junit.Assert; +import org.junit.Test; + +public class TokenTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + + @Test + public void testNoTokenForIsExpiredToken() { + try { + Assert.assertTrue(Token.isExpired(null)); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testEmptyTokenForIsExpiredToken() { + try { + Assert.assertTrue(Token.isExpired("")); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testInvalidTokenForIsExpiredToken() { + try { + Assert.assertTrue(Token.isExpired("invalid-token")); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testExpiredTokenForIsExpiredToken() { + try { + String token = System.getProperty("TEST_EXPIRED_TOKEN"); + Assert.assertTrue(Token.isExpired(token)); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} From be856d008b90ef36ace543b0e830798b98088a92 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 6 Nov 2024 21:12:15 +0530 Subject: [PATCH 038/126] SK-1684 Add unit tests for bearer token utilities --- .../serviceaccount/util/BearerToken.java | 4 +- .../serviceaccount/util/SignedDataTokens.java | 4 +- .../config/ConnectionConfigTests.java | 2 +- .../{vault => }/config/CredentialsTests.java | 2 +- .../{vault => }/config/VaultConfigTests.java | 20 +- .../serviceaccount/util/BearerTokenTests.java | 220 ++++++++++++++++++ .../serviceaccount/util/TokenTests.java | 3 +- .../java/com/skyflow/utils/UtilsTests.java | 136 +++++++++++ .../skyflow/vault/tokens/DetokenizeTests.java | 23 +- .../invalidPrivateKeyCredentials.json | 1 + .../resources/invalidTokenURICredentials.json | 1 + .../test/resources/noClientIDCredentials.json | 1 + v2/src/test/resources/noKeyIDCredentials.json | 1 + .../resources/noPrivateKeyCredentials.json | 1 + .../test/resources/noTokenURICredentials.json | 1 + v2/src/test/resources/notJson.txt | 1 + 16 files changed, 401 insertions(+), 20 deletions(-) rename v2/src/test/java/com/skyflow/{vault => }/config/ConnectionConfigTests.java (99%) rename v2/src/test/java/com/skyflow/{vault => }/config/CredentialsTests.java (99%) rename v2/src/test/java/com/skyflow/{vault => }/config/VaultConfigTests.java (91%) create mode 100644 v2/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java rename v2/src/test/java/com/skyflow/{vault => }/serviceaccount/util/TokenTests.java (92%) create mode 100644 v2/src/test/java/com/skyflow/utils/UtilsTests.java create mode 100644 v2/src/test/resources/invalidPrivateKeyCredentials.json create mode 100644 v2/src/test/resources/invalidTokenURICredentials.json create mode 100644 v2/src/test/resources/noClientIDCredentials.json create mode 100644 v2/src/test/resources/noKeyIDCredentials.json create mode 100644 v2/src/test/resources/noPrivateKeyCredentials.json create mode 100644 v2/src/test/resources/noTokenURICredentials.json create mode 100644 v2/src/test/resources/notJson.txt diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java b/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java index 2040cf16..f235da49 100644 --- a/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java +++ b/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java @@ -65,11 +65,11 @@ private static V1GetAuthTokenResponse generateBearerTokenFromCredentials( } catch (JsonSyntaxException e) { LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE_FORMAT.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( - ErrorMessage.FileInvalidJson.getMessage(), credentialsFile.getAbsolutePath())); + ErrorMessage.FileInvalidJson.getMessage(), credentialsFile.getPath())); } catch (FileNotFoundException e) { LogUtil.printErrorLog(ErrorLogs.CREDENTIALS_FILE_NOT_FOUND.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( - ErrorMessage.FileNotFound.getMessage(), credentialsFile.getAbsolutePath())); + ErrorMessage.FileNotFound.getMessage(), credentialsFile.getPath())); } } diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java b/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java index 47e50951..88312ff7 100644 --- a/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java +++ b/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java @@ -60,11 +60,11 @@ private static List generateSignedTokenFromCredentialsF } catch (JsonSyntaxException e) { LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE_FORMAT.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( - ErrorMessage.FileInvalidJson.getMessage(), credentialsFile.getAbsolutePath())); + ErrorMessage.FileInvalidJson.getMessage(), credentialsFile.getPath())); } catch (FileNotFoundException e) { LogUtil.printErrorLog(ErrorLogs.CREDENTIALS_FILE_NOT_FOUND.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( - ErrorMessage.FileNotFound.getMessage(), credentialsFile.getAbsolutePath())); + ErrorMessage.FileNotFound.getMessage(), credentialsFile.getPath())); } return responseToken; } diff --git a/v2/src/test/java/com/skyflow/vault/config/ConnectionConfigTests.java b/v2/src/test/java/com/skyflow/config/ConnectionConfigTests.java similarity index 99% rename from v2/src/test/java/com/skyflow/vault/config/ConnectionConfigTests.java rename to v2/src/test/java/com/skyflow/config/ConnectionConfigTests.java index 648ad98d..03b1021e 100644 --- a/v2/src/test/java/com/skyflow/vault/config/ConnectionConfigTests.java +++ b/v2/src/test/java/com/skyflow/config/ConnectionConfigTests.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.config; +package com.skyflow.config; import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; diff --git a/v2/src/test/java/com/skyflow/vault/config/CredentialsTests.java b/v2/src/test/java/com/skyflow/config/CredentialsTests.java similarity index 99% rename from v2/src/test/java/com/skyflow/vault/config/CredentialsTests.java rename to v2/src/test/java/com/skyflow/config/CredentialsTests.java index 554f7f0d..64f34c94 100644 --- a/v2/src/test/java/com/skyflow/vault/config/CredentialsTests.java +++ b/v2/src/test/java/com/skyflow/config/CredentialsTests.java @@ -1,4 +1,4 @@ -package com.skyflow.vault.config; +package com.skyflow.config; import com.skyflow.config.Credentials; import com.skyflow.errors.ErrorCode; diff --git a/v2/src/test/java/com/skyflow/vault/config/VaultConfigTests.java b/v2/src/test/java/com/skyflow/config/VaultConfigTests.java similarity index 91% rename from v2/src/test/java/com/skyflow/vault/config/VaultConfigTests.java rename to v2/src/test/java/com/skyflow/config/VaultConfigTests.java index 011f2990..478f8cf0 100644 --- a/v2/src/test/java/com/skyflow/vault/config/VaultConfigTests.java +++ b/v2/src/test/java/com/skyflow/config/VaultConfigTests.java @@ -1,7 +1,5 @@ -package com.skyflow.vault.config; +package com.skyflow.config; -import com.skyflow.config.Credentials; -import com.skyflow.config.VaultConfig; import com.skyflow.enums.Env; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; @@ -43,7 +41,7 @@ public static void setup() throws SkyflowException, NoSuchMethodException { } @Test - public void testValidVaultConfigWithCredentials() { + public void testValidVaultConfigWithCredentialsInValidations() { try { VaultConfig vaultConfig = new VaultConfig(); vaultConfig.setVaultId(vaultID); @@ -62,7 +60,7 @@ public void testValidVaultConfigWithCredentials() { } @Test - public void testValidVaultConfigWithoutCredentials() { + public void testValidVaultConfigWithoutCredentialsInValidations() { try { VaultConfig vaultConfig = new VaultConfig(); vaultConfig.setVaultId(vaultID); @@ -80,7 +78,7 @@ public void testValidVaultConfigWithoutCredentials() { } @Test - public void testDefaultEnvInVaultConfigWithCredentials() { + public void testDefaultEnvInVaultConfigWithCredentialsInValidations() { try { VaultConfig vaultConfig = new VaultConfig(); vaultConfig.setVaultId(vaultID); @@ -98,7 +96,7 @@ public void testDefaultEnvInVaultConfigWithCredentials() { } @Test - public void testDefaultEnvInVaultConfigWithoutCredentials() { + public void testDefaultEnvInVaultConfigWithoutCredentialsInValidations() { try { VaultConfig vaultConfig = new VaultConfig(); vaultConfig.setVaultId(vaultID); @@ -115,7 +113,7 @@ public void testDefaultEnvInVaultConfigWithoutCredentials() { } @Test - public void testNoVaultIdInVaultConfig() { + public void testNoVaultIdInVaultConfigInValidations() { VaultConfig vaultConfig = new VaultConfig(); try { vaultConfig.setClusterId(clusterID); @@ -129,7 +127,7 @@ public void testNoVaultIdInVaultConfig() { } @Test - public void testEmptyVaultIdInVaultConfig() { + public void testEmptyVaultIdInVaultConfigInValidations() { try { VaultConfig vaultConfig = new VaultConfig(); vaultConfig.setVaultId(""); @@ -144,7 +142,7 @@ public void testEmptyVaultIdInVaultConfig() { } @Test - public void testNoClusterIdInVaultConfig() { + public void testNoClusterIdInVaultConfigInValidations() { try { VaultConfig vaultConfig = new VaultConfig(); vaultConfig.setVaultId(vaultID); @@ -158,7 +156,7 @@ public void testNoClusterIdInVaultConfig() { } @Test - public void testEmptyClusterIdInVaultConfig() { + public void testEmptyClusterIdInVaultConfigInValidations() { try { VaultConfig vaultConfig = new VaultConfig(); vaultConfig.setVaultId(vaultID); diff --git a/v2/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java b/v2/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java new file mode 100644 index 00000000..3993e476 --- /dev/null +++ b/v2/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java @@ -0,0 +1,220 @@ +package com.skyflow.serviceaccount.util; + +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.Utils; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.util.ArrayList; + +public class BearerTokenTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String invalidJsonFilePath = null; + private static String credentialsFilePath = null; + private static String invalidFilePath = null; + private static String credentialsString = null; + private static String context = null; + private static ArrayList roles = null; + private static String role = null; + + @BeforeClass + public static void setup() { + credentialsFilePath = "./credentials.json"; + invalidJsonFilePath = "./src/test/resources/notJson.txt"; + invalidFilePath = "./src/test/credentials.json"; + credentialsString = "{\"key\":\"value\"}"; + context = "test_context"; + roles = new ArrayList<>(); + role = "test_role"; + } + + @Test + public void testBearerTokenBuilderWithCredentialsFile() { + try { + roles.add(role); + File file = new File(credentialsFilePath); + BearerToken.builder().setCredentials(file).setCtx(context).setRoles(roles).build(); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testBearerTokenBuilderWithCredentialsString() { + try { + BearerToken.builder().setCredentials(credentialsString).setCtx(context).setRoles(roles).build(); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + + } + + @Test + public void testEmptyCredentialsFilePath() { + try { + File file = new File(""); + BearerToken bearerToken = BearerToken.builder().setCredentials(file).build(); + bearerToken.getBearerToken(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); + } + } + + @Test + public void testInvalidFilePath() { + try { + File file = new File(invalidFilePath); + BearerToken bearerToken = BearerToken.builder().setCredentials(file).build(); + bearerToken.getBearerToken(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); + } + } + + @Test + public void testInvalidCredentialsFile() { + try { + File file = new File(invalidJsonFilePath); + BearerToken bearerToken = BearerToken.builder().setCredentials(file).build(); + bearerToken.getBearerToken(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.FileInvalidJson.getMessage(), invalidJsonFilePath), + e.getMessage() + ); + } + } + + @Test + public void testEmptyCredentialsString() { + try { + BearerToken bearerToken = BearerToken.builder().setCredentials("").build(); + bearerToken.getBearerToken(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); + } + } + + @Test + public void testInvalidCredentialsString() { + try { + BearerToken bearerToken = BearerToken.builder().setCredentials(invalidFilePath).build(); + bearerToken.getBearerToken(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); + } + } + + + @Test + public void testNoPrivateKeyInCredentialsForCredentials() { + String filePath = "./src/test/resources/noPrivateKeyCredentials.json"; + File file = new File(filePath); + try { + BearerToken bearerToken = BearerToken.builder().setCredentials(file).build(); + bearerToken.getBearerToken(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.MissingPrivateKey.getMessage(), e.getMessage()); + } + } + + @Test + public void testNoClientIDInCredentialsForCredentials() { + String filePath = "./src/test/resources/noClientIDCredentials.json"; + File file = new File(filePath); + try { + BearerToken bearerToken = BearerToken.builder().setCredentials(file).build(); + bearerToken.getBearerToken(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.MissingClientId.getMessage(), e.getMessage()); + } + } + + @Test + public void testNoKeyIDInCredentialsForCredentials() { + String filePath = "./src/test/resources/noKeyIDCredentials.json"; + File file = new File(filePath); + try { + BearerToken bearerToken = BearerToken.builder().setCredentials(file).build(); + bearerToken.getBearerToken(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.MissingKeyId.getMessage(), e.getMessage()); + } + } + + @Test + public void testNoTokenURIInCredentialsForCredentials() { + String filePath = "./src/test/resources/noTokenURICredentials.json"; + File file = new File(filePath); + try { + BearerToken bearerToken = BearerToken.builder().setCredentials(file).build(); + bearerToken.getBearerToken(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.MissingTokenUri.getMessage(), e.getMessage()); + } + } + + @Test + public void testInvalidPrivateKeyInCredentialsForCredentials() { + String filePath = "./src/test/resources/invalidPrivateKeyCredentials.json"; + File file = new File(filePath); + try { + BearerToken bearerToken = BearerToken.builder().setCredentials(file).build(); + bearerToken.getBearerToken(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.JwtInvalidFormat.getMessage(), e.getMessage()); + } + } + + @Test + public void testInvalidKeySpecInCredentialsForCredentials() { + String credentialsString = "{\"privateKey\": \"-----BEGIN PRIVATE KEY-----\\ncHJpdmF0ZV9rZXlfdmFsdWU=\\n-----END PRIVATE KEY-----\", \"clientID\": \"client_id_value\", \"keyID\": \"key_id_value\", \"tokenURI\": \"invalid_token_uri\"}"; + try { + BearerToken bearerToken = BearerToken.builder().setCredentials(credentialsString).build(); + bearerToken.getBearerToken(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidKeySpec.getMessage(), e.getMessage()); + } + } + + @Test + public void testInvalidTokenURIInCredentialsForCredentials() throws SkyflowException { + String filePath = "./src/test/resources/invalidTokenURICredentials.json"; + File file = new File(filePath); + try { + BearerToken bearerToken = BearerToken.builder().setCredentials(file).build(); + bearerToken.getBearerToken(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidTokenUri.getMessage(), e.getMessage()); + } + } +} diff --git a/v2/src/test/java/com/skyflow/vault/serviceaccount/util/TokenTests.java b/v2/src/test/java/com/skyflow/serviceaccount/util/TokenTests.java similarity index 92% rename from v2/src/test/java/com/skyflow/vault/serviceaccount/util/TokenTests.java rename to v2/src/test/java/com/skyflow/serviceaccount/util/TokenTests.java index 3a3d8f6e..d1ac044b 100644 --- a/v2/src/test/java/com/skyflow/vault/serviceaccount/util/TokenTests.java +++ b/v2/src/test/java/com/skyflow/serviceaccount/util/TokenTests.java @@ -1,6 +1,5 @@ -package com.skyflow.vault.serviceaccount.util; +package com.skyflow.serviceaccount.util; -import com.skyflow.serviceaccount.util.Token; import org.junit.Assert; import org.junit.Test; diff --git a/v2/src/test/java/com/skyflow/utils/UtilsTests.java b/v2/src/test/java/com/skyflow/utils/UtilsTests.java new file mode 100644 index 00000000..33a83f59 --- /dev/null +++ b/v2/src/test/java/com/skyflow/utils/UtilsTests.java @@ -0,0 +1,136 @@ +package com.skyflow.utils; + +import com.skyflow.config.Credentials; +import com.skyflow.enums.Env; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.ArrayList; + +public class UtilsTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String clusterId = null; + private static String url = null; + private static String filePath = null; + private static String credentialsString = null; + private static String token = null; + private static String context = null; + private static ArrayList roles = null; + + @BeforeClass + public static void setup() { + clusterId = "test_cluster_id"; + url = "https://test-url.com/java/unit/tests"; + filePath = "invalid/file/path/credentials.json"; + credentialsString = "invalid credentials string"; + token = "invalid-token"; + context = "test_context"; + roles = new ArrayList<>(); + String role = "test_role"; + roles.add(role); + } + + @Test + public void testGetVaultURLForDev() { + try { + String vaultURL = Utils.getVaultURL(clusterId, Env.DEV); + String devUrl = "https://test_cluster_id.vault.skyflowapis.dev"; + Assert.assertEquals(devUrl, vaultURL); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetVaultURLForStage() { + try { + String vaultURL = Utils.getVaultURL(clusterId, Env.STAGE); + String stageUrl = "https://test_cluster_id.vault.skyflowapis.tech"; + Assert.assertEquals(stageUrl, vaultURL); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetVaultURLForSandbox() { + try { + String vaultURL = Utils.getVaultURL(clusterId, Env.SANDBOX); + String sandboxUrl = "https://test_cluster_id.vault.skyflowapis-preview.com"; + Assert.assertEquals(sandboxUrl, vaultURL); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetVaultURLForProd() { + try { + String vaultURL = Utils.getVaultURL(clusterId, Env.PROD); + String prodUrl = "https://test_cluster_id.vault.skyflowapis.com"; + Assert.assertEquals(prodUrl, vaultURL); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetBaseURL() { + try { + String baseURL = Utils.getBaseURL(url); + String url = "https://test-url.com"; + Assert.assertEquals(url, baseURL); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGenerateBearerTokenWithCredentialsFile() { + try { + Credentials credentials = new Credentials(); + credentials.setPath(filePath); + credentials.setContext(context); + credentials.setRoles(roles); + Utils.generateBearerToken(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); + } + } + + @Test + public void testGenerateBearerTokenWithCredentialsString() { + try { + Credentials credentials = new Credentials(); + credentials.setCredentialsString(credentialsString); + credentials.setContext(context); + credentials.setRoles(roles); + Utils.generateBearerToken(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); + } + } + + @Test + public void testGenerateBearerTokenWithToken() { + try { + Credentials credentials = new Credentials(); + credentials.setToken(token); + credentials.setContext(context); + credentials.setRoles(roles); + String bearerToken = Utils.generateBearerToken(credentials); + Assert.assertEquals(token, bearerToken); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} diff --git a/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index 04dd406d..d7a7d7fc 100644 --- a/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -9,17 +9,23 @@ import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.ApiClient; import com.skyflow.generated.rest.ApiException; import com.skyflow.generated.rest.api.TokensApi; import com.skyflow.generated.rest.models.V1DetokenizeResponse; +import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; @@ -38,13 +44,14 @@ public class DetokenizeTests { private static String token = null; private static ArrayList tokens = null; private static Skyflow skyflowClient = null; + private ApiClient mockApiClient; + private TokensApi mockTokensApi; @BeforeClass public static void setup() throws SkyflowException, NoSuchMethodException { // PowerMockito.mockStatic(Token.class); // PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); // PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); -// PowerMockito.mock(ApiClient.class); vaultID = "vault123"; clusterID = "cluster123"; @@ -60,8 +67,22 @@ public static void setup() throws SkyflowException, NoSuchMethodException { token = "test_token_1"; tokens = new ArrayList<>(); + +// System.setProperty("ssl.TrustManagerFactory.algorithm", "PKIX"); } +// @Before +// public void setupMock() throws ApiException { +// mockApiClient = PowerMockito.mock(ApiClient.class); +// mockTokensApi = PowerMockito.mock(TokensApi.class); +// +// V1DetokenizeResponse mockResponse = new V1DetokenizeResponse(); +// PowerMockito +// .when(mockTokensApi.recordServiceDetokenize(ArgumentMatchers.anyString(), ArgumentMatchers.any())) +// .thenReturn(mockResponse); +// +// } + @Test public void testValidInputInDetokenizeRequestValidations() { try { diff --git a/v2/src/test/resources/invalidPrivateKeyCredentials.json b/v2/src/test/resources/invalidPrivateKeyCredentials.json new file mode 100644 index 00000000..3615e623 --- /dev/null +++ b/v2/src/test/resources/invalidPrivateKeyCredentials.json @@ -0,0 +1 @@ +{"privateKey": "private_key_value", "clientID": "client_id_value", "keyID": "key_id_value", "tokenURI": "invalid_token_uri"} \ No newline at end of file diff --git a/v2/src/test/resources/invalidTokenURICredentials.json b/v2/src/test/resources/invalidTokenURICredentials.json new file mode 100644 index 00000000..ac9346aa --- /dev/null +++ b/v2/src/test/resources/invalidTokenURICredentials.json @@ -0,0 +1 @@ +{"privateKey":"-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCzLp0TVwidRMtZ\n4tGLHPDEF6ihmE4OHSR/r5rZGqE+PNtw/uwXzBrfz1Mktb0hddMZNwC2IKhHE0Yw\nvtBT0jsfy4OUQR13Mohn9znz+5TES/yXjkvZjhZKzs5rxNw/cO8lpKYUYdwbFzwl\n9e3joCsWBXBDCbXdLQGPyggJV+KBI0LBal+LngNLU/U680LRlybCKCTyyrF0SERD\npytcpnq41CS2Q0ZDfkK/zLrvsCkEBU8xYeAf/TphXMKeqvMGTqxxg6IPOKfYya7Q\nnH9eZ1pn1SCe6N5XBUpQpB4K+1IZKvadOYpYWzRgM+tT5k4UVsg6s7kUm8k9n85/\nNQMjMY2XAgMBAAECggEASlg05ClgcaBxn0H1H3tKipImbaX7/O8qjbAW162s6V3m\nzuN2ogkVvXcQUFL3vkJc7EFeEjNKnvLoVKFXXvADiBWw6np591MINdrmOM1R1ICS\ntW9dGU9TAIb+LsjneYsqLrw6DIruAG+LjVSU97UlK2XmRmppAvQBid+Rpg7I9Dsy\naJyGjDHeC3RyYYNfpei2dBPUYlUjOkBqgYGOOyjYxHzzgYtdVZku0JPtsAey3WKL\nSbu8ryugu7r23fxP50H3FtYz91TPlVu1zVEk9Viizp2c9642ZKEoA0bB/bSNMUnt\nZ/kemZENAzC7tnoYgwN09rI3h0+U5jaU1BhXbrLpAQKBgQDt8eaywv6j+Hdv8i7S\nyMnZE4CaM70Z319ctJPlt2QdCZp8dtac858qnnrrZSCWV3n3yMv//bf1WZB4Lssw\nuxBzSCFI/imG6eY9uQA6yXLl1TY9DA5IJ8s2LGzwmtA1q+vC+jzWs+0+S/evUewo\nTZGQuNjHMHoM22jeLErqQZkHUQKBgQDAxz1WY56ZHdC3Y4aXkDeb5Ag+ZJV8Uqwn\nootA2zHCaEx8gM9CzChCl4pQcghHFXv4eEKqezdWSK+SIRA1CtR+q8g5dP8YtAkR\n9Uav6/fEkM8iCUvhZg+1DPRShu15nQF0ZAleSJ9OiSW5pIfAbY79RHru8H31azhE\nDOWezXbcZwKBgB9LAAckg+62n6aWWDgadglZekFNaqI7cUQ073p3mvACslGKI4Fy\nvM0TGKFapGWBTaYbv1CEYqwewlQ7+zcGcwxmQRJjcryuiDw312Lj2XuGheKTclFl\nAmG2iAFAqv9UA+aZmGS4NwxJW2KwSHmocetxk/jmVDbaqDkH5DZYuDJxAoGBAJqn\n/PRujVEnk0dc6CB1ybcd9OMhTK/ln0lY5MDOWRgvFpWXvS9InE/4RTWOlkd42/EV\ngd5FZbqqK3hfYCI9owZQiBxYWUMXRGOM0/3Un/ypdBNJQ//7IkTMtMH0j1XOeNlI\nXB+wwWV/L63EakgdXOag5sMEWvjl4MjvU9PX4DCnAoGAR0c567DWbkTXvcNIjvNF\nNK8suq/fGt4dpbkkFOEHjgqFd5RsjFHKc98JVrudPweUR7YjpeKQaeNKXfVFd4+N\nDPOs0zWSsaHckh1g9djkZlidha9SD/V6cOpxi3g2okcn/LI7h8NyNlAwDSn2mPEi\nMd3mrgMCZwJsXLndGQSDVUw=\n-----END PRIVATE KEY-----\n", "clientID": "client_id_value", "keyID": "key_id_value", "tokenURI": "invalid_token_uri"} \ No newline at end of file diff --git a/v2/src/test/resources/noClientIDCredentials.json b/v2/src/test/resources/noClientIDCredentials.json new file mode 100644 index 00000000..6e7edd20 --- /dev/null +++ b/v2/src/test/resources/noClientIDCredentials.json @@ -0,0 +1 @@ +{"privateKey":"private_key_value"} \ No newline at end of file diff --git a/v2/src/test/resources/noKeyIDCredentials.json b/v2/src/test/resources/noKeyIDCredentials.json new file mode 100644 index 00000000..64ff438e --- /dev/null +++ b/v2/src/test/resources/noKeyIDCredentials.json @@ -0,0 +1 @@ +{"privateKey":"private_key_value","clientID":"client_id_value"} \ No newline at end of file diff --git a/v2/src/test/resources/noPrivateKeyCredentials.json b/v2/src/test/resources/noPrivateKeyCredentials.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/v2/src/test/resources/noPrivateKeyCredentials.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/v2/src/test/resources/noTokenURICredentials.json b/v2/src/test/resources/noTokenURICredentials.json new file mode 100644 index 00000000..f88b0792 --- /dev/null +++ b/v2/src/test/resources/noTokenURICredentials.json @@ -0,0 +1 @@ +{"privateKey":"private_key_value","clientID":"client_id_value","keyID":"key_id_value"} \ No newline at end of file diff --git a/v2/src/test/resources/notJson.txt b/v2/src/test/resources/notJson.txt new file mode 100644 index 00000000..bdf08de0 --- /dev/null +++ b/v2/src/test/resources/notJson.txt @@ -0,0 +1 @@ +test file \ No newline at end of file From fc336f0a6b83b3d2f86eb1a353b3c5fb84fb1971 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 7 Nov 2024 20:15:43 +0530 Subject: [PATCH 039/126] SK-1684 Add unit tests for signed data tokens SK-1684 Add unit tests for Tokenize request validations --- .../serviceaccount/util/SignedDataTokens.java | 12 +- .../utils/validations/Validations.java | 20 +- .../skyflow/vault/tokens/TokenizeRequest.java | 2 - .../util/SignedDataTokensTests.java | 209 ++++++++++++++++++ .../skyflow/vault/tokens/TokenizeTests.java | 109 +++++++++ 5 files changed, 331 insertions(+), 21 deletions(-) create mode 100644 v2/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java create mode 100644 v2/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java b/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java index 88312ff7..2f486c42 100644 --- a/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java +++ b/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java @@ -155,14 +155,10 @@ private static List getSignedToken( public synchronized List getSignedDataTokens() throws SkyflowException { LogUtil.printInfoLog(InfoLogs.GET_SIGNED_DATA_TOKENS_TRIGGERED.getLog()); List signedToken = new ArrayList<>(); - try { - if (this.credentialsFile != null && Objects.equals(this.credentialsType, "FILE")) { - signedToken = generateSignedTokenFromCredentialsFile(this.credentialsFile, this.dataTokens, this.timeToLive, this.ctx); - } else if (this.credentialsString != null && Objects.equals(this.credentialsType, "STRING")) { - signedToken = generateSignedTokensFromCredentialsString(this.credentialsString, this.dataTokens, this.timeToLive, this.ctx); - } - } catch (SkyflowException e) { - e.printStackTrace(); + if (this.credentialsFile != null && Objects.equals(this.credentialsType, "FILE")) { + signedToken = generateSignedTokenFromCredentialsFile(this.credentialsFile, this.dataTokens, this.timeToLive, this.ctx); + } else if (this.credentialsString != null && Objects.equals(this.credentialsType, "STRING")) { + signedToken = generateSignedTokensFromCredentialsString(this.credentialsString, this.dataTokens, this.timeToLive, this.ctx); } LogUtil.printInfoLog(InfoLogs.GET_SIGNED_DATA_TOKEN_SUCCESS.getLog()); return signedToken; diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index f0c44956..a35f3f64 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -579,17 +579,15 @@ public static void validateQueryRequest(QueryRequest queryRequest) throws Skyflo public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) throws SkyflowException { List columnValues = tokenizeRequest.getColumnValues(); - if (columnValues == null || columnValues.isEmpty()) { - if (columnValues == null) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.COLUMN_VALUES_IS_REQUIRED_TOKENIZE.getLog(), InterfaceName.TOKENIZE.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ColumnValuesKeyErrorTokenize.getMessage()); - } else { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.EMPTY_COLUMN_VALUES.getLog(), InterfaceName.TOKENIZE.getName() - )); - } + if (columnValues == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.COLUMN_VALUES_IS_REQUIRED_TOKENIZE.getLog(), InterfaceName.TOKENIZE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ColumnValuesKeyErrorTokenize.getMessage()); + } else if (columnValues.isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_COLUMN_VALUES.getLog(), InterfaceName.TOKENIZE.getName() + )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyColumnValues.getMessage()); } else { for (int index = 0; index < columnValues.size(); index++) { diff --git a/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java b/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java index f7570714..a1a5ca33 100644 --- a/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java +++ b/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java @@ -1,6 +1,5 @@ package com.skyflow.vault.tokens; -import java.util.ArrayList; import java.util.List; public class TokenizeRequest { @@ -22,7 +21,6 @@ public static final class TokenizeRequestBuilder { private List columnValues; private TokenizeRequestBuilder() { - this.columnValues = new ArrayList<>(); } public TokenizeRequestBuilder values(List columnValues) { diff --git a/v2/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java b/v2/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java new file mode 100644 index 00000000..e5ce56b1 --- /dev/null +++ b/v2/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java @@ -0,0 +1,209 @@ +package com.skyflow.serviceaccount.util; + +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.Utils; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.util.ArrayList; + +public class SignedDataTokensTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String invalidJsonFilePath = null; + private static String credentialsFilePath = null; + private static String invalidFilePath = null; + private static String credentialsString = null; + private static String context = null; + private static ArrayList dataTokens = null; + private static String dataToken = null; + private static Integer ttl = null; + + @BeforeClass + public static void setup() { + credentialsFilePath = "./credentials.json"; + invalidJsonFilePath = "./src/test/resources/notJson.txt"; + invalidFilePath = "./src/test/credentials.json"; + credentialsString = "{\"key\":\"value\"}"; + context = "test_context"; + dataTokens = new ArrayList<>(); + dataToken = "test_data_token"; + ttl = 60; + } + + @Test + public void testSignedDataTokensBuilderWithCredentialsFile() { + try { + File file = new File(credentialsFilePath); + dataTokens.add(dataToken); + SignedDataTokens.builder() + .setCredentials(file).setCtx(context).setDataTokens(dataTokens).setTimeToLive(ttl) + .build(); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testSignedDataTokensBuilderWithCredentialsString() { + try { + SignedDataTokens.builder() + .setCredentials(credentialsString).setCtx(context).setDataTokens(dataTokens).setTimeToLive(ttl) + .build(); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + + } + + @Test + public void testEmptyCredentialsFilePath() { + try { + File file = new File(""); + SignedDataTokens signedTokens = SignedDataTokens.builder().setCredentials(file).build(); + signedTokens.getSignedDataTokens(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); + } + } + + @Test + public void testInvalidFilePath() { + try { + File file = new File(invalidFilePath); + SignedDataTokens signedTokens = SignedDataTokens.builder().setCredentials(file).build(); + signedTokens.getSignedDataTokens(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); + } + } + + @Test + public void testInvalidCredentialsFile() { + try { + File file = new File(invalidJsonFilePath); + SignedDataTokens signedTokens = SignedDataTokens.builder().setCredentials(file).build(); + signedTokens.getSignedDataTokens(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.FileInvalidJson.getMessage(), invalidJsonFilePath), + e.getMessage() + ); + } + } + + @Test + public void testEmptyCredentialsString() { + try { + SignedDataTokens signedTokens = SignedDataTokens.builder().setCredentials("").build(); + signedTokens.getSignedDataTokens(); + System.out.println("in try block"); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + System.out.println("caught skyflow exception"); + System.out.println(e); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.InvalidCredentials.getMessage(), invalidJsonFilePath), + e.getMessage() + ); + } catch (Exception e) { + System.out.println("catching exception"); + System.out.println(e); + } + } + + @Test + public void testInvalidCredentialsString() { + try { + SignedDataTokens signedTokens = SignedDataTokens.builder().setCredentials(invalidFilePath).build(); + signedTokens.getSignedDataTokens(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.CredentialsStringInvalidJson.getMessage(), invalidJsonFilePath), + e.getMessage() + ); + } + } + + @Test + public void testNoPrivateKeyInCredentials() { + String filePath = "./src/test/resources/noPrivateKeyCredentials.json"; + File file = new File(filePath); + try { + SignedDataTokens signedTokens = SignedDataTokens.builder().setCredentials(file).build(); + signedTokens.getSignedDataTokens(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.MissingPrivateKey.getMessage(), e.getMessage()); + } + } + + @Test + public void testNoClientIDInCredentials() { + String filePath = "./src/test/resources/noClientIDCredentials.json"; + File file = new File(filePath); + try { + SignedDataTokens signedTokens = SignedDataTokens.builder().setCredentials(file).build(); + signedTokens.getSignedDataTokens(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.MissingClientId.getMessage(), e.getMessage()); + } + } + + @Test + public void testNoKeyIDInCredentials() { + String filePath = "./src/test/resources/noKeyIDCredentials.json"; + File file = new File(filePath); + try { + SignedDataTokens signedTokens = SignedDataTokens.builder().setCredentials(file).build(); + signedTokens.getSignedDataTokens(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.MissingKeyId.getMessage(), e.getMessage()); + } + } + + @Test + public void testInvalidPrivateKeyInCredentials() { + String filePath = "./src/test/resources/invalidPrivateKeyCredentials.json"; + File file = new File(filePath); + try { + SignedDataTokens signedTokens = SignedDataTokens.builder().setCredentials(file).build(); + signedTokens.getSignedDataTokens(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.JwtInvalidFormat.getMessage(), e.getMessage()); + } + } + + @Test + public void testInvalidKeySpecInCredentials() { + String credentialsString = "{\"privateKey\": \"-----BEGIN PRIVATE KEY-----\\ncHJpdmF0ZV9rZXlfdmFsdWU=\\n-----END PRIVATE KEY-----\", \"clientID\": \"client_id_value\", \"keyID\": \"key_id_value\", \"tokenURI\": \"invalid_token_uri\"}"; + try { + SignedDataTokens signedTokens = SignedDataTokens.builder().setCredentials(credentialsString).build(); + signedTokens.getSignedDataTokens(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidKeySpec.getMessage(), e.getMessage()); + } + } +} diff --git a/v2/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java b/v2/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java new file mode 100644 index 00000000..4f801a44 --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java @@ -0,0 +1,109 @@ +package com.skyflow.vault.tokens; + +import com.skyflow.Skyflow; +import com.skyflow.config.VaultConfig; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +public class TokenizeTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static VaultConfig vaultConfig = null; + private static String token = null; + private static ArrayList tokens = null; + private static Skyflow skyflowClient = null; + private static List columnValues = null; + private static ColumnValue columnValue = null; + private static String value = null; + private static String group = null; + + @BeforeClass + public static void setup() { + columnValues = new ArrayList<>(); + value = "test_value"; + group = "test_group"; + } + + @Before + public void setupTest() { + columnValues.clear(); + } + + @Test + public void testValidInputInTokenizeRequestValidations() { + try { + columnValue = ColumnValue.builder().value(value).columnGroup(group).build(); + columnValues.add(columnValue); + TokenizeRequest request = TokenizeRequest.builder().values(columnValues).build(); + Validations.validateTokenizeRequest(request); + Assert.assertEquals(1, request.getColumnValues().size()); + Assert.assertEquals(value, request.getColumnValues().get(0).getValue()); + Assert.assertEquals(group, request.getColumnValues().get(0).getColumnGroup()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoColumnValuesInTokenizeRequestValidations() { + try { + TokenizeRequest request = TokenizeRequest.builder().build(); + Validations.validateTokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.ColumnValuesKeyErrorTokenize.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyColumnValuesInTokenizeRequestValidations() { + try { + TokenizeRequest request = TokenizeRequest.builder().values(columnValues).build(); + Validations.validateTokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyColumnValues.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyColumnValueInColumnValuesInTokenizeRequestValidations() { + try { + columnValue = ColumnValue.builder().value("").columnGroup(group).build(); + columnValues.add(columnValue); + TokenizeRequest request = TokenizeRequest.builder().values(columnValues).build(); + Validations.validateTokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyValueInColumnValues.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyColumnGroupInColumnValuesInTokenizeRequestValidations() { + try { + columnValue = ColumnValue.builder().value(value).columnGroup("").build(); + columnValues.add(columnValue); + TokenizeRequest request = TokenizeRequest.builder().values(columnValues).build(); + Validations.validateTokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyColumnGroupInColumnValue.getMessage(), e.getMessage()); + } + } +} From 9f3bd92e854455b63fb09efb449c65bfbe434787 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 8 Nov 2024 21:06:52 +0530 Subject: [PATCH 040/126] SK-1684 Add unit tests for Java SDK v2 --- .../vault/controller/VaultController.java | 2 - .../com/skyflow/vault/data/GetResponse.java | 2 +- .../skyflow/vault/data/InsertResponse.java | 2 +- .../test/java/com/skyflow/SkyflowTests.java | 281 ++++++++++++++++++ .../controller/VaultControllerTests.java | 192 ++++++++++++ .../java/com/skyflow/vault/data/GetTests.java | 27 ++ .../com/skyflow/vault/data/InsertTests.java | 58 +++- .../com/skyflow/vault/data/QueryTests.java | 5 +- .../skyflow/vault/tokens/DetokenizeTests.java | 72 ----- .../skyflow/vault/tokens/TokenizeTests.java | 14 + 10 files changed, 568 insertions(+), 87 deletions(-) create mode 100644 v2/src/test/java/com/skyflow/SkyflowTests.java create mode 100644 v2/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java index 08204181..3a3bc03f 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -26,8 +26,6 @@ public final class VaultController extends VaultClient { private AuditController auditController; private BinLookupController binLookupController; - private String token; - public VaultController(VaultConfig vaultConfig, Credentials credentials) { super(vaultConfig, credentials); this.auditController = null; diff --git a/v2/src/main/java/com/skyflow/vault/data/GetResponse.java b/v2/src/main/java/com/skyflow/vault/data/GetResponse.java index 2d2a4b1d..bd882138 100644 --- a/v2/src/main/java/com/skyflow/vault/data/GetResponse.java +++ b/v2/src/main/java/com/skyflow/vault/data/GetResponse.java @@ -24,7 +24,7 @@ public ArrayList> getErrors() { public String toString() { StringBuilder response = new StringBuilder("{"); response.append("\n\t\"data\": ").append(formatRecords(data)); - response.append("\n\t\"errors\": ").append(formatRecords(errors)); + response.append(",\n\t\"errors\": ").append(formatRecords(errors)); response.append("\n}"); return response.toString(); } diff --git a/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java b/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java index e0eaf098..240c6940 100644 --- a/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java +++ b/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java @@ -24,7 +24,7 @@ public ArrayList> getErrorFields() { public String toString() { StringBuilder response = new StringBuilder("{"); response.append("\n\t\"insertedFields\": ").append(formatRecords(insertedFields)); - response.append("\n\t\"errors\": ").append(formatRecords(errorFields)); + response.append(",\n\t\"errors\": ").append(formatRecords(errorFields)); response.append("\n}"); return response.toString(); } diff --git a/v2/src/test/java/com/skyflow/SkyflowTests.java b/v2/src/test/java/com/skyflow/SkyflowTests.java new file mode 100644 index 00000000..cfdd7e5a --- /dev/null +++ b/v2/src/test/java/com/skyflow/SkyflowTests.java @@ -0,0 +1,281 @@ +package com.skyflow; + +import com.skyflow.config.ConnectionConfig; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class SkyflowTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static String newClusterID = null; + private static String connectionID = null; + private static String connectionURL = null; + private static String token = null; + + @BeforeClass + public static void setup() { + vaultID = "test_vault_id"; + clusterID = "test_cluster_id"; + newClusterID = "new_test_cluster_id"; + connectionID = "test_connection_id"; + connectionURL = "https://test.connection.url"; + token = "test_token"; + } + + @Test + public void testAddingInvalidVaultConfigInSkyflowBuilder() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(""); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow.builder().addVaultConfig(config).build(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyVaultId.getMessage(), e.getMessage()); + } + } + + @Test + public void testAddingInvalidVaultConfigInSkyflowClient() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(""); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.addVaultConfig(config); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyVaultId.getMessage(), e.getMessage()); + } + } + + @Test + public void testAddingValidVaultConfigInSkyflowClient() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.addVaultConfig(config); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testAddingExistingVaultConfigInSkyflowClient() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.addVaultConfig(config).addVaultConfig(config); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.VaultIdAlreadyInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testUpdatingNonExistentVaultConfigInSkyflowBuilder() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow.builder().updateVaultConfig(config).build(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testUpdatingNonExistentVaultConfigInSkyflowClient() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.updateVaultConfig(config); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } catch (Exception e) { + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testUpdatingValidVaultConfigInSkyflowClient() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().addVaultConfig(config).build(); + + Credentials credentials = new Credentials(); + credentials.setToken(token); + + skyflowClient.updateVaultConfig(config); + + config.setClusterId(newClusterID); + config.setEnv(Env.PROD); + config.setCredentials(credentials); + + skyflowClient.updateVaultConfig(config); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testRemovingNonExistentVaultConfigInSkyflowBuilder() { + try { + Skyflow.builder().removeVaultConfig(vaultID).build(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testRemovingNonExistentVaultConfigInSkyflowClient() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().addVaultConfig(config).build(); + skyflowClient.removeVaultConfig(vaultID); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testRemovingValidVaultConfigInSkyflowClient() { + try { + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.removeVaultConfig(vaultID); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testGettingNonExistentVaultConfigInSkyflowClient() { + try { + Skyflow skyflowClient = Skyflow.builder().build(); + VaultConfig config = skyflowClient.getVaultConfig(vaultID); + Assert.assertNull(config); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + + @Test + public void testAddingInvalidConnectionConfigInSkyflowBuilder() { + try { + ConnectionConfig config = new ConnectionConfig(); + config.setConnectionId(""); + config.setConnectionUrl(connectionURL); + Skyflow.builder().addConnectionConfig(config).build(); +// Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { +// Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyVaultId.getMessage(), e.getMessage()); + } + } + + @Test + public void testAddingInvalidConnectionConfigInSkyflowClient() { + try { + ConnectionConfig config = new ConnectionConfig(); + config.setConnectionId(""); + config.setConnectionUrl(connectionURL); + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.addConnectionConfig(config); +// Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { +// Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyVaultId.getMessage(), e.getMessage()); + } + } + + @Test + public void testAddingInvalidSkyflowCredentialsInSkyflowBuilder() { + try { + Credentials credentials = new Credentials(); + Skyflow.builder().addSkyflowCredentials(credentials).build(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.NoTokenGenerationMeansPassed.getMessage(), e.getMessage()); + } + } + + @Test + public void testUpdatingValidSkyflowCredentialsInSkyflowClient() { + try { + Credentials credentials = new Credentials(); + credentials.setToken(token); + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.updateSkyflowCredentials(credentials); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testDefaultLogLevel() { + try { + Skyflow skyflowClient = Skyflow.builder().setLogLevel(null).build(); + Assert.assertEquals(LogLevel.ERROR, skyflowClient.getLogLevel()); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testUpdateLogLevel() { + try { + Skyflow skyflowClient = Skyflow.builder().setLogLevel(LogLevel.INFO).build(); + Assert.assertEquals(LogLevel.INFO, skyflowClient.getLogLevel()); + skyflowClient.updateLogLevel(LogLevel.WARN); + Assert.assertEquals(LogLevel.WARN, skyflowClient.getLogLevel()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + +} diff --git a/v2/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java b/v2/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java new file mode 100644 index 00000000..ecfca480 --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java @@ -0,0 +1,192 @@ +package com.skyflow.vault.controller; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.api.TokensApi; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.vault.data.*; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.TokenizeRequest; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class VaultControllerTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static VaultConfig vaultConfig = null; + private static Skyflow skyflowClient = null; + private ApiClient mockApiClient; + private TokensApi mockTokensApi; + + @BeforeClass + public static void setup() throws SkyflowException, NoSuchMethodException { + vaultID = "vault123"; + clusterID = "cluster123"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.DEV); + vaultConfig.setCredentials(credentials); + } + + @Test + public void testInvalidRequestInInsertMethod() { + try { + InsertRequest request = InsertRequest.builder().build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.vault().insert(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testInvalidRequestInDetokenizeMethod() { + try { + DetokenizeRequest request = DetokenizeRequest.builder().build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.vault().detokenize(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.InvalidDataTokens.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testInvalidRequestInGetMethod() { + try { + GetRequest request = GetRequest.builder().build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.vault().get(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testInvalidRequestInUpdateMethod() { + try { + UpdateRequest request = UpdateRequest.builder().build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.vault().update(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testInvalidRequestInDeleteMethod() { + try { + DeleteRequest request = DeleteRequest.builder().build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.vault().delete(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testInvalidRequestInQueryMethod() { + try { + QueryRequest request = QueryRequest.builder().build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.vault().query(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.QueryKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testInvalidRequestInTokenizeMethod() { + try { + TokenizeRequest request = TokenizeRequest.builder().build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.vault().tokenize(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.ColumnValuesKeyErrorTokenize.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testLookUpBin() { + try { + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.vault().lookUpBin(); + skyflowClient.vault().lookUpBin(); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testAudit() { + try { + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.vault().audit(); + skyflowClient.vault().audit(); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testDetect() { + try { + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.vault().detect(); + skyflowClient.vault().detect(); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + +} diff --git a/v2/src/test/java/com/skyflow/vault/data/GetTests.java b/v2/src/test/java/com/skyflow/vault/data/GetTests.java index ac6625fe..140990a7 100644 --- a/v2/src/test/java/com/skyflow/vault/data/GetTests.java +++ b/v2/src/test/java/com/skyflow/vault/data/GetTests.java @@ -22,6 +22,7 @@ import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; +import java.util.HashMap; @RunWith(PowerMockRunner.class) @PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") @@ -470,4 +471,30 @@ public void testEmptyValueInColumnValuesInGetRequestValidations() { ); } } + + @Test + public void testGetResponse() { + try { + ArrayList> data = new ArrayList<>(); + HashMap record = new HashMap<>(); + record.put("test_column_1", "test_value_1"); + record.put("test_column_2", "test_value_2"); + data.add(record); + data.add(record); + ArrayList> errors = new ArrayList<>(); + GetResponse response = new GetResponse(data, errors); + String responseString = "{\n\t\"data\": [" + + "{\n\t\t\"test_column_1\": \"test_value_1\"," + + "\n\t\t\"test_column_2\": \"test_value_2\",\n\t}, " + + "{\n\t\t\"test_column_1\": \"test_value_1\"," + + "\n\t\t\"test_column_2\": \"test_value_2\",\n\t}]" + + ",\n\t\"errors\": " + errors + "\n}"; + Assert.assertEquals(2, response.getData().size()); + Assert.assertTrue(response.getErrors().isEmpty()); + Assert.assertEquals(responseString, response.toString()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + + } } diff --git a/v2/src/test/java/com/skyflow/vault/data/InsertTests.java b/v2/src/test/java/com/skyflow/vault/data/InsertTests.java index f49f9c20..50b1e5fc 100644 --- a/v2/src/test/java/com/skyflow/vault/data/InsertTests.java +++ b/v2/src/test/java/com/skyflow/vault/data/InsertTests.java @@ -13,6 +13,7 @@ import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @@ -62,11 +63,19 @@ public static void setup() throws SkyflowException { values = new ArrayList<>(); tokens = new ArrayList<>(); valueMap = new HashMap<>(); + tokenMap = new HashMap<>(); + upsert = "upsert_column"; + } + + @Before + public void setupTest() { + values.clear(); + tokens.clear(); + valueMap.clear(); valueMap.put("test_column_1", "test_value_1"); valueMap.put("test_column_2", "test_value_2"); - tokenMap = new HashMap<>(); + tokenMap.clear(); tokenMap.put("test_column_1", "test_token_1"); - upsert = "upsert_column"; } @Test @@ -148,7 +157,6 @@ public void testNoValuesInInsertRequestValidations() { @Test public void testEmptyValuesInInsertRequestValidations() { - values.clear(); InsertRequest request = InsertRequest.builder().table(table).values(values).build(); try { Validations.validateInsertRequest(request); @@ -181,8 +189,8 @@ public void testEmptyKeyInValuesInInsertRequestValidations() { @Test public void testEmptyValueInValuesInInsertRequestValidations() { - valueMap.remove(""); valueMap.put("test_column_3", ""); + values.add(valueMap); InsertRequest request = InsertRequest.builder().table(table).values(values).build(); try { Validations.validateInsertRequest(request); @@ -198,7 +206,7 @@ public void testEmptyValueInValuesInInsertRequestValidations() { @Test public void testEmptyUpsertInInsertRequestValidations() { - valueMap.remove("test_column_3"); + values.add(valueMap); InsertRequest request = InsertRequest.builder().table(table).values(values).upsert("").build(); try { Validations.validateInsertRequest(request); @@ -214,6 +222,7 @@ public void testEmptyUpsertInInsertRequestValidations() { @Test public void testUpsertWithHomogenousInInsertRequestValidations() { + values.add(valueMap); InsertRequest request = InsertRequest.builder() .table(table).values(values).upsert(upsert).homogeneous(true) .build(); @@ -231,6 +240,7 @@ public void testUpsertWithHomogenousInInsertRequestValidations() { @Test public void testTokensWithTokenStrictDisableInInsertRequestValidations() { + values.add(valueMap); InsertRequest request = InsertRequest.builder().table(table).values(values).tokens(tokens).build(); try { Validations.validateInsertRequest(request); @@ -246,6 +256,7 @@ public void testTokensWithTokenStrictDisableInInsertRequestValidations() { @Test public void testNoTokensWithTokenStrictEnableInInsertRequestValidations() { + values.add(valueMap); InsertRequest request = InsertRequest.builder() .table(table).values(values).tokenStrict(Byot.ENABLE) .build(); @@ -263,6 +274,7 @@ public void testNoTokensWithTokenStrictEnableInInsertRequestValidations() { @Test public void testNoTokensWithTokenStrictEnableStrictInInsertRequestValidations() { + values.add(valueMap); InsertRequest request = InsertRequest.builder() .table(table).values(values).tokenStrict(Byot.ENABLE_STRICT) .build(); @@ -280,7 +292,7 @@ public void testNoTokensWithTokenStrictEnableStrictInInsertRequestValidations() @Test public void testEmptyTokensWithTokenStrictEnableInInsertRequestValidations() { - tokens.clear(); + values.add(valueMap); InsertRequest request = InsertRequest.builder() .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE) .build(); @@ -295,6 +307,7 @@ public void testEmptyTokensWithTokenStrictEnableInInsertRequestValidations() { @Test public void testInsufficientTokensWithTokenStrictEnableStrictInInsertRequestValidations1() { + values.add(valueMap); tokens.add(tokenMap); InsertRequest request = InsertRequest.builder() .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) @@ -311,6 +324,8 @@ public void testInsufficientTokensWithTokenStrictEnableStrictInInsertRequestVali @Test public void testInsufficientTokensWithTokenStrictEnableStrictInInsertRequestValidations2() { values.add(valueMap); + values.add(valueMap); + tokens.add(tokenMap); InsertRequest request = InsertRequest.builder() .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) .build(); @@ -325,8 +340,9 @@ public void testInsufficientTokensWithTokenStrictEnableStrictInInsertRequestVali @Test public void testTokenValueMismatchInInsertRequestValidations() { + values.add(valueMap); tokenMap.put("test_column_3", "test_token_3"); - values.remove(1); + tokens.add(tokenMap); InsertRequest request = InsertRequest.builder() .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) .build(); @@ -341,9 +357,9 @@ public void testTokenValueMismatchInInsertRequestValidations() { @Test public void testEmptyKeyInTokensInInsertRequestValidations() { - tokenMap.remove("test_column_2"); - tokenMap.remove("test_column_3"); tokenMap.put("", "test_token_2"); + values.add(valueMap); + tokens.add(tokenMap); InsertRequest request = InsertRequest.builder() .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) .build(); @@ -358,8 +374,9 @@ public void testEmptyKeyInTokensInInsertRequestValidations() { @Test public void testEmptyValueInTokensInInsertRequestValidations() { - tokenMap.remove(""); tokenMap.put("test_column_2", ""); + values.add(valueMap); + tokens.add(tokenMap); InsertRequest request = InsertRequest.builder() .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) .build(); @@ -372,4 +389,25 @@ public void testEmptyValueInTokensInInsertRequestValidations() { } } + @Test + public void testInsertResponse() { + try { + ArrayList> errorFields = new ArrayList<>(); + values.add(valueMap); + values.add(valueMap); + InsertResponse response = new InsertResponse(values, errorFields); + String responseString = "{\n\t\"insertedFields\": [" + + "{\n\t\t\"test_column_1\": \"test_value_1\"," + + "\n\t\t\"test_column_2\": \"test_value_2\",\n\t}, " + + "{\n\t\t\"test_column_1\": \"test_value_1\"," + + "\n\t\t\"test_column_2\": \"test_value_2\",\n\t}]" + + ",\n\t\"errors\": " + errorFields + "\n}"; + Assert.assertEquals(2, response.getInsertedFields().size()); + Assert.assertTrue(response.getErrorFields().isEmpty()); + Assert.assertEquals(responseString, response.toString()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + } diff --git a/v2/src/test/java/com/skyflow/vault/data/QueryTests.java b/v2/src/test/java/com/skyflow/vault/data/QueryTests.java index 3197a83c..a84c9113 100644 --- a/v2/src/test/java/com/skyflow/vault/data/QueryTests.java +++ b/v2/src/test/java/com/skyflow/vault/data/QueryTests.java @@ -105,11 +105,14 @@ public void testQueryResponse() { try { ArrayList> fields = new ArrayList<>(); fields.add(queryRecord); + fields.add(queryRecord); QueryResponse response = new QueryResponse(fields); String responseString = "{\n\t\"fields\": " + "[{\n\t\t\"card_number\": \"test_card_number\",\n\t\t\"name\": \"test_name\"," + + "\n\t\t\"tokenizedData\": " + null + "\n\t}, " + + "{\n\t\t\"card_number\": \"test_card_number\",\n\t\t\"name\": \"test_name\"," + "\n\t\t\"tokenizedData\": " + null + "\n\t}]\n}"; - Assert.assertEquals(1, response.getFields().size()); + Assert.assertEquals(2, response.getFields().size()); Assert.assertEquals(responseString, response.toString()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); diff --git a/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index d7a7d7fc..b4185260 100644 --- a/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -13,19 +13,12 @@ import com.skyflow.generated.rest.ApiException; import com.skyflow.generated.rest.api.TokensApi; import com.skyflow.generated.rest.models.V1DetokenizeResponse; -import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; import org.junit.Assert; -import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; @@ -166,69 +159,4 @@ public void testRedactionAndContinueOnErrorInDetokenizeRequestValidations() { Assert.fail(INVALID_EXCEPTION_THROWN); } } - - @Test - public void testNoTokensInDetokenizeMethod() { - DetokenizeRequest request = DetokenizeRequest.builder().build(); - try { - V1DetokenizeResponse mockResponse = new V1DetokenizeResponse(); - TokensApi mockApi = PowerMockito.mock(TokensApi.class); - PowerMockito - .when(mockApi.recordServiceDetokenize(ArgumentMatchers.anyString(), ArgumentMatchers.any())) - .thenReturn(mockResponse); - - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - DetokenizeResponse response = skyflowClient.vault().detokenize(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); - Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.InvalidDataTokens.getMessage(), Constants.SDK_PREFIX), - e.getMessage() - ); - Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); - Assert.assertTrue(request.getContinueOnError()); - } catch (ApiException e) { - Assert.fail(); - } - } - - @Test - public void testEmptyTokensInDetokenizeMethod() { - tokens.clear(); - DetokenizeRequest request = DetokenizeRequest.builder().tokens(tokens).build(); - try { - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - DetokenizeResponse response = skyflowClient.vault().detokenize(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); - Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.EmptyDataTokens.getMessage(), Constants.SDK_PREFIX), - e.getMessage() - ); - Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); - Assert.assertTrue(request.getContinueOnError()); - } - } - - @Test - public void testEmptyTokenInTokensInDetokenizeMethod() { - tokens.add(token); - tokens.add(""); - DetokenizeRequest request = DetokenizeRequest.builder().tokens(tokens).build(); - try { - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - DetokenizeResponse response = skyflowClient.vault().detokenize(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); - Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.EmptyTokenInDataTokens.getMessage(), Constants.SDK_PREFIX), - e.getMessage() - ); - Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); - Assert.assertTrue(request.getContinueOnError()); - } - } } diff --git a/v2/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java b/v2/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java index 4f801a44..1f4360b2 100644 --- a/v2/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java +++ b/v2/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java @@ -1,7 +1,9 @@ package com.skyflow.vault.tokens; import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; @@ -30,6 +32,18 @@ public class TokenizeTests { @BeforeClass public static void setup() { + vaultID = "vault123"; + clusterID = "cluster123"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.DEV); + vaultConfig.setCredentials(credentials); + columnValues = new ArrayList<>(); value = "test_value"; group = "test_group"; From f1484693d41823b73968c27e2a62394dbbb05357 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 8 Nov 2024 22:10:45 +0530 Subject: [PATCH 041/126] SK-1666 Fix conflicts and build issues after merge --- v2/src/main/java/com/skyflow/Skyflow.java | 23 +++++++------------ .../com/skyflow/config/ConnectionConfig.java | 8 ------- v2/src/main/java/com/skyflow/utils/Utils.java | 4 ++-- .../utils/validations/Validations.java | 12 +++------- 4 files changed, 13 insertions(+), 34 deletions(-) diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/v2/src/main/java/com/skyflow/Skyflow.java index b4223e32..eaf7a7a2 100644 --- a/v2/src/main/java/com/skyflow/Skyflow.java +++ b/v2/src/main/java/com/skyflow/Skyflow.java @@ -39,7 +39,7 @@ public VaultConfig getVaultConfig(String vaultId) { return this.builder.vaultConfigMap.get(vaultId); } - public Skyflow updateVaultConfig(VaultConfig vaultConfig) throws Exception { + public Skyflow updateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { this.builder.updateVaultConfig(vaultConfig); return this; } @@ -206,7 +206,7 @@ public SkyflowClientBuilder addSkyflowCredentials(Credentials credentials) throw public SkyflowClientBuilder setLogLevel(LogLevel logLevel) { this.logLevel = logLevel == null ? LogLevel.ERROR : logLevel; - LogUtil.setupLogger(logLevel); + LogUtil.setupLogger(this.logLevel); LogUtil.printInfoLog(Utils.parameterizedString( InfoLogs.CURRENT_LOG_LEVEL.getLog(), String.valueOf(logLevel) )); @@ -219,19 +219,12 @@ public Skyflow build() { private VaultConfig findAndUpdateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { VaultConfig previousConfig = this.vaultConfigMap.get(vaultConfig.getVaultId()); - if (previousConfig == null) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog(), vaultConfig.getVaultId() - )); - throw new SkyflowException(); - } else { - Env env = vaultConfig.getEnv() != null ? vaultConfig.getEnv() : previousConfig.getEnv(); - String clusterId = vaultConfig.getClusterId() != null ? vaultConfig.getClusterId() : previousConfig.getClusterId(); - Credentials credentials = vaultConfig.getCredentials() != null ? vaultConfig.getCredentials() : previousConfig.getCredentials(); - previousConfig.setEnv(env); - previousConfig.setClusterId(clusterId); - previousConfig.setCredentials(credentials); - } + Env env = vaultConfig.getEnv() != null ? vaultConfig.getEnv() : previousConfig.getEnv(); + String clusterId = vaultConfig.getClusterId() != null ? vaultConfig.getClusterId() : previousConfig.getClusterId(); + Credentials credentials = vaultConfig.getCredentials() != null ? vaultConfig.getCredentials() : previousConfig.getCredentials(); + previousConfig.setEnv(env); + previousConfig.setClusterId(clusterId); + previousConfig.setCredentials(credentials); return previousConfig; } } diff --git a/v2/src/main/java/com/skyflow/config/ConnectionConfig.java b/v2/src/main/java/com/skyflow/config/ConnectionConfig.java index acab67ad..c017b181 100644 --- a/v2/src/main/java/com/skyflow/config/ConnectionConfig.java +++ b/v2/src/main/java/com/skyflow/config/ConnectionConfig.java @@ -35,12 +35,4 @@ public void setCredentials(Credentials credentials) { this.credentials = credentials; } - public String getConnectionUrl() { - return connectionUrl; - } - - public Credentials getCredentials() { - return credentials; - } - } diff --git a/v2/src/main/java/com/skyflow/utils/Utils.java b/v2/src/main/java/com/skyflow/utils/Utils.java index 86eb17b8..66e50b5a 100644 --- a/v2/src/main/java/com/skyflow/utils/Utils.java +++ b/v2/src/main/java/com/skyflow/utils/Utils.java @@ -8,8 +8,8 @@ import com.skyflow.errors.SkyflowException; import com.skyflow.logs.ErrorLogs; import com.skyflow.serviceaccount.util.BearerToken; -import com.skyflow.vault.connection.InvokeConnectionRequest; import com.skyflow.utils.logger.LogUtil; +import com.skyflow.vault.connection.InvokeConnectionRequest; import org.apache.commons.codec.binary.Base64; import java.io.File; @@ -127,7 +127,7 @@ public static String constructConnectionURL(ConnectionConfig config, InvokeConne } } - if(invokeConnectionRequest.getQueryParams() != null && !invokeConnectionRequest.getQueryParams().isEmpty()) { + if (invokeConnectionRequest.getQueryParams() != null && !invokeConnectionRequest.getQueryParams().isEmpty()) { filledURL.append("?"); for (Map.Entry entry : invokeConnectionRequest.getQueryParams().entrySet()) { String key = entry.getKey(); diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index 42ef80ee..61c7ff80 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -3,14 +3,10 @@ import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; - -import com.skyflow.enums.RequestMethod; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.connection.InvokeConnectionRequest; import com.skyflow.enums.Byot; import com.skyflow.enums.InterfaceName; import com.skyflow.enums.RedactionType; +import com.skyflow.enums.RequestMethod; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; @@ -18,14 +14,12 @@ import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.utils.logger.LogUtil; +import com.skyflow.vault.connection.InvokeConnectionRequest; import com.skyflow.vault.data.*; import com.skyflow.vault.tokens.ColumnValue; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; -import java.net.URL; - -// Add config and request validations import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; @@ -92,7 +86,7 @@ public static void validateInvokeConnectionRequest(InvokeConnectionRequest invok throw new SkyflowException(); } - if (invokeConnectionRequest.getMethodName()!=null) { + if (invokeConnectionRequest.getMethodName() != null) { try { RequestMethod requestMethod = RequestMethod.valueOf(invokeConnectionRequest.getMethodName()); } catch (Exception e) { From f529a234de0ef10f557ad53aafe6e883e1c76fa9 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 15 Nov 2024 16:57:24 +0530 Subject: [PATCH 042/126] SK-1684 Add unit tests for invoke connection SK-1766 Add validations for invoke connection interface SK-1766 Refactor code for invoke connection, removed unnecessary components for code optimisation --- .../java/com/skyflow/ConnectionClient.java | 53 ++- v2/src/main/java/com/skyflow/Skyflow.java | 57 ++- v2/src/main/java/com/skyflow/VaultClient.java | 8 - .../java/com/skyflow/errors/ErrorMessage.java | 8 +- .../com/skyflow/errors/SkyflowException.java | 3 - .../main/java/com/skyflow/logs/ErrorLogs.java | 15 +- .../utils/validations/Validations.java | 96 +++-- .../connection/InvokeConnectionRequest.java | 25 +- .../controller/ConnectionController.java | 68 +-- .../test/java/com/skyflow/SkyflowTests.java | 154 ++++++- .../com/skyflow/config/CredentialsTests.java | 8 +- .../com/skyflow/utils/HttpUtilityTests.java | 123 ++++++ .../java/com/skyflow/utils/UtilsTests.java | 48 +++ .../connection/InvokeConnectionTests.java | 394 ++++++++++++++++++ .../controller/ConnectionControllerTests.java | 49 +++ .../skyflow/vault/tokens/DetokenizeTests.java | 59 +-- 16 files changed, 967 insertions(+), 201 deletions(-) create mode 100644 v2/src/test/java/com/skyflow/utils/HttpUtilityTests.java create mode 100644 v2/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java create mode 100644 v2/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java diff --git a/v2/src/main/java/com/skyflow/ConnectionClient.java b/v2/src/main/java/com/skyflow/ConnectionClient.java index a42d3aa6..40fd741a 100644 --- a/v2/src/main/java/com/skyflow/ConnectionClient.java +++ b/v2/src/main/java/com/skyflow/ConnectionClient.java @@ -2,32 +2,31 @@ import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; -import com.skyflow.config.VaultConfig; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.api.RecordsApi; -import com.skyflow.generated.rest.api.TokensApi; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.logs.InfoLogs; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.logger.LogUtil; +import com.skyflow.utils.validations.Validations; import io.github.cdimascio.dotenv.Dotenv; public class ConnectionClient { - private final ConnectionConfig connectionConfig; + protected String token; + protected String apiKey; private Credentials commonCredentials; private Credentials finalCredentials; - private final ApiClient apiClient; - protected ConnectionClient(ConnectionConfig connectionConfig, Credentials credentials) { super(); this.connectionConfig = connectionConfig; this.commonCredentials = credentials; - this.apiClient = new ApiClient(); prioritiseCredentials(); } - protected Credentials getFinalCredentials() { - return finalCredentials; - } - protected ConnectionConfig getConnectionConfig() { return connectionConfig; } @@ -37,8 +36,29 @@ protected void setCommonCredentials(Credentials commonCredentials) { prioritiseCredentials(); } - protected ApiClient getApiClient() { - return apiClient; + protected void updateConnectionConfig(ConnectionConfig connectionConfig) { + prioritiseCredentials(); + } + + protected void setBearerToken() throws SkyflowException { + Validations.validateCredentials(this.finalCredentials); + if (this.finalCredentials.getApiKey() != null) { + setApiKey(); + return; + } else if (token == null || Token.isExpired(token)) { + LogUtil.printInfoLog(InfoLogs.BEARER_TOKEN_EXPIRED.getLog()); + token = Utils.generateBearerToken(this.finalCredentials); + } else { + LogUtil.printInfoLog(InfoLogs.REUSE_BEARER_TOKEN.getLog()); + } + } + + private void setApiKey() { + if (apiKey == null) { + apiKey = this.finalCredentials.getApiKey(); + } else { + LogUtil.printInfoLog(InfoLogs.REUSE_API_KEY.getLog()); + } } private void prioritiseCredentials() { @@ -49,9 +69,10 @@ private void prioritiseCredentials() { this.finalCredentials = this.commonCredentials; } else { Dotenv dotenv = Dotenv.load(); - String sysCredentials = dotenv.get("SKYFLOW_CREDENTIALS"); + String sysCredentials = dotenv.get(Constants.ENV_CREDENTIALS_KEY_NAME); if (sysCredentials == null) { - // throw error for not passing any credentials + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.EmptyCredentials.getMessage()); } else { this.finalCredentials = new Credentials(); this.finalCredentials.setCredentialsString(sysCredentials); diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/v2/src/main/java/com/skyflow/Skyflow.java index eaf7a7a2..2a2e42cc 100644 --- a/v2/src/main/java/com/skyflow/Skyflow.java +++ b/v2/src/main/java/com/skyflow/Skyflow.java @@ -49,21 +49,21 @@ public Skyflow removeVaultConfig(String vaultId) throws SkyflowException { return this; } - public Skyflow addConnectionConfig(ConnectionConfig connectionConfig) { + public Skyflow addConnectionConfig(ConnectionConfig connectionConfig) throws SkyflowException { this.builder.addConnectionConfig(connectionConfig); return this; } public ConnectionConfig getConnectionConfig(String connectionId) { - return this.builder.connectionsMap.get(connectionId).getConnectionConfig(); + return this.builder.connectionConfigMap.get(connectionId); } - public Skyflow updateConnectionConfig(ConnectionConfig connectionConfig) { + public Skyflow updateConnectionConfig(ConnectionConfig connectionConfig) throws SkyflowException { this.builder.updateConnectionConfig(connectionConfig); return this; } - public Skyflow removeConnectionConfig(String connectionId) { + public Skyflow removeConnectionConfig(String connectionId) throws SkyflowException { this.builder.removeConnectionConfig(connectionId); return this; } @@ -91,7 +91,6 @@ public VaultController vault(String vaultId) { return this.builder.vaultClientsMap.get(vaultId); } - // In case no id is passed, return first connection controller public ConnectionController connection() { String connectionId = (String) this.builder.connectionsMap.keySet().toArray()[0]; return this.connection(connectionId); @@ -137,6 +136,8 @@ public SkyflowClientBuilder addVaultConfig(VaultConfig vaultConfig) throws Skyfl } public SkyflowClientBuilder updateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.VALIDATING_VAULT_CONFIG.getLog()); + Validations.validateVaultConfig(vaultConfig); if (this.vaultClientsMap.containsKey(vaultConfig.getVaultId())) { VaultConfig updatedConfig = findAndUpdateVaultConfig(vaultConfig); this.vaultClientsMap.get(updatedConfig.getVaultId()).updateVaultConfig(); @@ -160,34 +161,51 @@ public SkyflowClientBuilder removeVaultConfig(String vaultId) throws SkyflowExce return this; } - public SkyflowClientBuilder addConnectionConfig(ConnectionConfig connectionConfig) { - // check if connectionConfig already exists + public SkyflowClientBuilder addConnectionConfig(ConnectionConfig connectionConfig) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.VALIDATING_CONNECTION_CONFIG.getLog()); + Validations.validateConnectionConfig(connectionConfig); if (this.connectionsMap.containsKey(connectionConfig.getConnectionId())) { - // display error log, throw error, or both + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.CONNECTION_CONFIG_EXISTS.getLog(), connectionConfig.getConnectionId() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.ConnectionIdAlreadyInConfigList.getMessage()); } else { this.connectionConfigMap.put(connectionConfig.getConnectionId(), connectionConfig); ConnectionController controller = new ConnectionController(connectionConfig, this.skyflowCredentials); this.connectionsMap.put(connectionConfig.getConnectionId(), controller); + LogUtil.printInfoLog(Utils.parameterizedString( + InfoLogs.CONNECTION_CONTROLLER_INITIALIZED.getLog(), connectionConfig.getConnectionId())); } return this; } - public SkyflowClientBuilder updateConnectionConfig(ConnectionConfig connectionConfig) { + public SkyflowClientBuilder updateConnectionConfig(ConnectionConfig connectionConfig) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.VALIDATING_CONNECTION_CONFIG.getLog()); + Validations.validateConnectionConfig(connectionConfig); if (this.connectionsMap.containsKey(connectionConfig.getConnectionId())) { - ConnectionController controller = this.connectionsMap.get(connectionConfig.getConnectionId()); - controller.setConnectionConfig(connectionConfig); + ConnectionConfig updatedConfig = findAndUpdateConnectionConfig(connectionConfig); + this.connectionsMap.get(updatedConfig.getConnectionId()).updateConnectionConfig(connectionConfig); } else { - // display error log, throw error, or both + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.CONNECTION_CONFIG_DOES_NOT_EXIST.getLog(), connectionConfig.getConnectionId() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.ConnectionIdNotInConfigList.getMessage()); } return this; } - public SkyflowClientBuilder removeConnectionConfig(String connectionId) { + public SkyflowClientBuilder removeConnectionConfig(String connectionId) throws SkyflowException { if (this.connectionsMap.containsKey(connectionId)) { this.connectionsMap.remove(connectionId); this.connectionConfigMap.remove(connectionId); } else { - // display error log, throw error, or both + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.CONNECTION_CONFIG_DOES_NOT_EXIST.getLog(), connectionId + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.ConnectionIdNotInConfigList.getMessage()); } return this; } @@ -217,7 +235,7 @@ public Skyflow build() { return new Skyflow(this); } - private VaultConfig findAndUpdateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { + private VaultConfig findAndUpdateVaultConfig(VaultConfig vaultConfig) { VaultConfig previousConfig = this.vaultConfigMap.get(vaultConfig.getVaultId()); Env env = vaultConfig.getEnv() != null ? vaultConfig.getEnv() : previousConfig.getEnv(); String clusterId = vaultConfig.getClusterId() != null ? vaultConfig.getClusterId() : previousConfig.getClusterId(); @@ -227,5 +245,14 @@ private VaultConfig findAndUpdateVaultConfig(VaultConfig vaultConfig) throws Sky previousConfig.setCredentials(credentials); return previousConfig; } + + private ConnectionConfig findAndUpdateConnectionConfig(ConnectionConfig connectionConfig) { + ConnectionConfig previousConfig = this.connectionConfigMap.get(connectionConfig.getConnectionId()); + String connectionURL = connectionConfig.getConnectionUrl() != null ? connectionConfig.getConnectionUrl() : previousConfig.getConnectionUrl(); + Credentials credentials = connectionConfig.getCredentials() != null ? connectionConfig.getCredentials() : previousConfig.getCredentials(); + previousConfig.setConnectionUrl(connectionURL); + previousConfig.setCredentials(credentials); + return previousConfig; + } } } diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/v2/src/main/java/com/skyflow/VaultClient.java index 1c2e81ea..b1acbdad 100644 --- a/v2/src/main/java/com/skyflow/VaultClient.java +++ b/v2/src/main/java/com/skyflow/VaultClient.java @@ -51,10 +51,6 @@ protected VaultClient(VaultConfig vaultConfig, Credentials credentials) { prioritiseCredentials(); } - protected Credentials getFinalCredentials() { - return finalCredentials; - } - protected RecordsApi getRecordsApi() { return recordsApi; } @@ -75,10 +71,6 @@ protected VaultConfig getVaultConfig() { return vaultConfig; } - protected String getToken() { - return token; - } - protected void setCommonCredentials(Credentials commonCredentials) { this.commonCredentials = commonCredentials; prioritiseCredentials(); diff --git a/v2/src/main/java/com/skyflow/errors/ErrorMessage.java b/v2/src/main/java/com/skyflow/errors/ErrorMessage.java index 5d9905a3..f44427fb 100644 --- a/v2/src/main/java/com/skyflow/errors/ErrorMessage.java +++ b/v2/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -20,8 +20,8 @@ public enum ErrorMessage { // connection config InvalidConnectionId("%s1 Initialization failed. Invalid connection ID. Specify a valid connection ID."), EmptyConnectionId("%s1 Initialization failed. Invalid connection ID. Connection ID must not be empty."), - EmptyConnectionUrl("%s1 Initialization failed. Invalid connection URL. Connection URL must not be empty."), InvalidConnectionUrl("%s1 Initialization failed. Invalid connection URL. Specify a valid connection URL."), + EmptyConnectionUrl("%s1 Initialization failed. Invalid connection URL. Connection URL must not be empty."), InvalidConnectionUrlFormat("%s1 Initialization failed. Connection URL is not a valid URL. Specify a valid connection URL."), // credentials @@ -112,9 +112,13 @@ public enum ErrorMessage { ColumnValuesKeyErrorTokenize("%s1 Validation error. 'columnValues' key is missing from the payload. Specify a 'columnValues' key."), EmptyColumnGroupInColumnValue("%s1 Validation error. Invalid column group in column value. Specify a valid column group."), - //connection + // connection + InvalidRequestHeaders("%s1 Validation error. Request headers aren't valid. Specify valid request headers."), + EmptyRequestHeaders("%s1 Validation error. Request headers are empty. Specify valid ."), InvalidPathParams("%s1 Validation error. Path parameters aren't valid. Specify valid path parameters."), EmptyPathParams("%s1 Validation error. Path parameters are empty. Specify valid path parameters."), + InvalidQueryParams("%s1 Validation error. Query parameters aren't valid. Specify valid query parameters."), + EmptyQueryParams("%s1 Validation error. Query parameters are empty. Specify valid query parameters."), InvalidRequestBody("%s1 Validation error. Invalid request body. Specify the request body as an object."), EmptyRequestBody("%s1 Validation error. Request body can't be empty. Specify a valid request body."), diff --git a/v2/src/main/java/com/skyflow/errors/SkyflowException.java b/v2/src/main/java/com/skyflow/errors/SkyflowException.java index 1d0c81ff..625b0d2e 100644 --- a/v2/src/main/java/com/skyflow/errors/SkyflowException.java +++ b/v2/src/main/java/com/skyflow/errors/SkyflowException.java @@ -16,9 +16,6 @@ public class SkyflowException extends Exception { private JsonArray details; private JsonObject responseBody; - public SkyflowException() { - } - public SkyflowException(String message) { super(message); this.message = message; diff --git a/v2/src/main/java/com/skyflow/logs/ErrorLogs.java b/v2/src/main/java/com/skyflow/logs/ErrorLogs.java index fa1f945d..98bc3064 100644 --- a/v2/src/main/java/com/skyflow/logs/ErrorLogs.java +++ b/v2/src/main/java/com/skyflow/logs/ErrorLogs.java @@ -91,7 +91,20 @@ public enum ErrorLogs { COLUMN_VALUES_IS_REQUIRED_TOKENIZE("Invalid %s1 request. ColumnValues are required."), EMPTY_OR_NULL_COLUMN_GROUP_IN_COLUMN_VALUES("Invalid %s1 request. Column group can not be null or empty in column values at index %s2."), TOKENIZE_REQUEST_REJECTED("Tokenize request resulted in failure."), - DELETE_REQUEST_REJECTED("Delete request resulted in failure."); + DELETE_REQUEST_REJECTED("Delete request resulted in failure."), + + // invoke connection interface + INVOKE_CONNECTION_INVALID_CONNECTION_URL("Invalid %s1 request. Connection URL is not a valid URL."), + EMPTY_REQUEST_HEADERS("Invalid %s1 request. Request headers can not be empty."), + INVALID_REQUEST_HEADERS("Invalid %s1 request. Request header can not be null or empty in request headers."), + EMPTY_PATH_PARAMS("Invalid %s1 request. Path params can not be empty."), + INVALID_PATH_PARAM("Invalid %s1 request. Path parameter can not be null or empty in path params."), + EMPTY_QUERY_PARAMS("Invalid %s1 request. Query params can not be empty."), + INVALID_QUERY_PARAM("Invalid %s1 request. Query parameter can not be null or empty in query params."), + EMPTY_REQUEST_BODY("Invalid %s1 request. Request body can not be empty."), + INVALID_REQUEST_BODY("Invalid %s1 request. Request body can not be empty."), + INVOKE_CONNECTION_REQUEST_REJECTED("Invoke connection request resulted in failure."), + ; private final String log; diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/v2/src/main/java/com/skyflow/utils/validations/Validations.java index 61c7ff80..5e88ec1b 100644 --- a/v2/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/v2/src/main/java/com/skyflow/utils/validations/Validations.java @@ -6,7 +6,6 @@ import com.skyflow.enums.Byot; import com.skyflow.enums.InterfaceName; import com.skyflow.enums.RedactionType; -import com.skyflow.enums.RequestMethod; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; @@ -20,11 +19,11 @@ import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; -import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -67,44 +66,77 @@ public static void validateConnectionConfig(ConnectionConfig connectionConfig) t } else if (connectionUrl.trim().isEmpty()) { LogUtil.printErrorLog(ErrorLogs.EMPTY_CONNECTION_URL.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyConnectionUrl.getMessage()); - } - try { - URL url = new URL(connectionUrl); - } catch (MalformedURLException e) { + } else if (isInvalidURL(connectionUrl)) { LogUtil.printErrorLog(ErrorLogs.INVALID_CONNECTION_URL.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidConnectionUrlFormat.getMessage()); } } public static void validateInvokeConnectionRequest(InvokeConnectionRequest invokeConnectionRequest) throws SkyflowException { - if (invokeConnectionRequest.getRequestHeaders().containsKey("connectionURL")) { - String connectionURL = invokeConnectionRequest.getRequestHeaders().get("connectionURL"); - if (isInvalidURL(connectionURL)) { - throw new SkyflowException(); + Map requestHeaders = invokeConnectionRequest.getRequestHeaders(); + Map pathParams = invokeConnectionRequest.getPathParams(); + Map queryParams = invokeConnectionRequest.getQueryParams(); + Object requestBody = invokeConnectionRequest.getRequestBody(); + + if (requestHeaders != null) { + if (requestHeaders.isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_REQUEST_HEADERS.getLog(), InterfaceName.INVOKE_CONNECTION.getName())); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestHeaders.getMessage()); + } else { + for (String header : requestHeaders.keySet()) { + String headerValue = requestHeaders.get(header); + if (header == null || header.trim().isEmpty() || headerValue == null || headerValue.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_REQUEST_HEADERS.getLog(), InterfaceName.INVOKE_CONNECTION.getName())); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestHeaders.getMessage()); + } + } } - } else { - throw new SkyflowException(); } - if (invokeConnectionRequest.getMethodName() != null) { - try { - RequestMethod requestMethod = RequestMethod.valueOf(invokeConnectionRequest.getMethodName()); - } catch (Exception e) { - throw new SkyflowException(); + if (pathParams != null) { + if (pathParams.isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_PATH_PARAMS.getLog(), InterfaceName.INVOKE_CONNECTION.getName())); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyPathParams.getMessage()); + } else { + for (String param : pathParams.keySet()) { + String paramValue = pathParams.get(param); + if (param == null || param.trim().isEmpty() || paramValue == null || paramValue.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_PATH_PARAM.getLog(), InterfaceName.INVOKE_CONNECTION.getName())); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidPathParams.getMessage()); + } + } } - } else { - throw new SkyflowException(); } - } - private static boolean isInvalidURL(String configURL) { - try { - URL url = new URL(configURL); - if (!url.getProtocol().equals("https")) throw new Exception(); - } catch (Exception e) { - return true; + if (queryParams != null) { + if (queryParams.isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_QUERY_PARAMS.getLog(), InterfaceName.INVOKE_CONNECTION.getName())); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyQueryParams.getMessage()); + } else { + for (String param : queryParams.keySet()) { + String paramValue = queryParams.get(param); + if (param == null || param.trim().isEmpty() || paramValue == null || paramValue.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_QUERY_PARAM.getLog(), InterfaceName.INVOKE_CONNECTION.getName())); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidQueryParams.getMessage()); + } + } + } + } + + if (requestBody != null) { + Map requestBodyMap = (Map) requestBody; + if (requestBodyMap.isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_REQUEST_BODY.getLog(), InterfaceName.INVOKE_CONNECTION.getName())); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestBody.getMessage()); + } } - return false; } public static void validateCredentials(Credentials credentials) throws SkyflowException { @@ -643,6 +675,16 @@ public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) thro } } + private static boolean isInvalidURL(String configURL) { + try { + URL url = new URL(configURL); + if (!url.getProtocol().equals("https")) throw new Exception(); + } catch (Exception e) { + return true; + } + return false; + } + private static void validateTokensForInsertRequest( ArrayList> tokens, ArrayList> values, diff --git a/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java b/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java index a74b9adb..5edf4f4f 100644 --- a/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java +++ b/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java @@ -1,11 +1,7 @@ package com.skyflow.vault.connection; -import com.google.gson.JsonObject; -import com.skyflow.enums.RedactionType; -import com.skyflow.vault.tokens.DetokenizeRequest; -import com.skyflow.vault.tokens.TokenizeRequest; +import com.skyflow.enums.RequestMethod; -import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @@ -21,11 +17,7 @@ public static InvokeConnectionRequestBuilder builder() { return new InvokeConnectionRequestBuilder(); } - public InvokeConnectionRequest getConnectionRequest() { - return new InvokeConnectionRequest(builder); - } - - public String getMethodName() { + public RequestMethod getMethodName() { return builder.methodName; } @@ -45,24 +37,23 @@ public Object getRequestBody() { return builder.requestBody; } - public static final class InvokeConnectionRequestBuilder{ - - private String methodName; + public static final class InvokeConnectionRequestBuilder { + private RequestMethod methodName; private Map pathParams; private Map queryParams; private Map requestHeaders; private Object requestBody; - public InvokeConnectionRequestBuilder() { - this.methodName = ""; + private InvokeConnectionRequestBuilder() { + this.methodName = RequestMethod.POST; this.pathParams = new HashMap<>(); this.queryParams = new HashMap<>(); this.requestHeaders = new HashMap<>(); this.requestBody = new Object(); } - public InvokeConnectionRequestBuilder methodName(String methodName) { - this.methodName = methodName; + public InvokeConnectionRequestBuilder methodName(RequestMethod methodName) { + this.methodName = methodName == null ? RequestMethod.POST : methodName; return this; } diff --git a/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java b/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java index d2e08977..7ae03a2a 100644 --- a/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java +++ b/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -1,97 +1,75 @@ package com.skyflow.vault.controller; import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.skyflow.ConnectionClient; import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; +import com.skyflow.enums.RequestMethod; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.generated.rest.auth.HttpBearerAuth; -import com.skyflow.serviceaccount.util.Token; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.logs.InfoLogs; import com.skyflow.utils.HttpUtility; import com.skyflow.utils.Utils; +import com.skyflow.utils.logger.LogUtil; import com.skyflow.utils.validations.Validations; import com.skyflow.vault.connection.InvokeConnectionRequest; import com.skyflow.vault.connection.InvokeConnectionResponse; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import java.net.URL; import java.io.IOException; -import java.text.ParseException; +import java.net.URL; import java.util.HashMap; import java.util.Map; public class ConnectionController extends ConnectionClient { - private ConnectionConfig connectionConfig; - private Credentials commonCredentials; - - private String token; - public ConnectionController(ConnectionConfig connectionConfig, Credentials credentials) { super(connectionConfig, credentials); - this.connectionConfig = connectionConfig; - this.commonCredentials = credentials; } - public void setCommonCredentials(Credentials commonCredentials) { - this.commonCredentials = commonCredentials; - } - - public ConnectionConfig getConnectionConfig() { - return connectionConfig; - } - - public void setConnectionConfig(ConnectionConfig connectionConfig) { - this.connectionConfig = connectionConfig; - } - - public InvokeConnectionResponse invoke(InvokeConnectionRequest invokeConnectionRequest) throws SkyflowException, IOException { - + public InvokeConnectionResponse invoke(InvokeConnectionRequest invokeConnectionRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.INVOKE_CONNECTION_TRIGGERED.getLog()); InvokeConnectionResponse connectionResponse; try { + LogUtil.printInfoLog(InfoLogs.VALIDATING_INVOKE_CONNECTION_REQUEST.getLog()); Validations.validateInvokeConnectionRequest(invokeConnectionRequest); setBearerToken(); - String filledURL = Utils.constructConnectionURL(connectionConfig, invokeConnectionRequest); + String filledURL = Utils.constructConnectionURL(super.getConnectionConfig(), invokeConnectionRequest); Map headers = new HashMap<>(); if (invokeConnectionRequest.getRequestHeaders().containsKey("requestHeader")) { headers = Utils.constructConnectionHeadersMap(invokeConnectionRequest.getRequestHeaders()); } if (!headers.containsKey("x-skyflow-authorization")) { - headers.put("x-skyflow-authorization", token); + headers.put("x-skyflow-authorization", token == null ? apiKey : token); } - String requestMethod = invokeConnectionRequest.getMethodName(); + RequestMethod requestMethod = invokeConnectionRequest.getMethodName(); JsonObject requestBody = null; Object requestBodyObject = invokeConnectionRequest.getRequestBody(); - if(requestBodyObject!=null) { + if (requestBodyObject != null) { try { requestBody = convertObjectToJson(requestBodyObject); } catch (Exception e) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.INVALID_REQUEST_HEADERS.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); } } - String response = HttpUtility.sendRequest(requestMethod, new URL(filledURL), requestBody, headers); - connectionResponse = new InvokeConnectionResponse((JsonObject) new JsonParser().parse(response)); + String response = HttpUtility.sendRequest(requestMethod.name(), new URL(filledURL), requestBody, headers); + connectionResponse = new InvokeConnectionResponse((JsonObject) JsonParser.parseString(response)); + LogUtil.printInfoLog(InfoLogs.INVOKE_CONNECTION_REQUEST_RESOLVED.getLog()); } catch (IOException e) { - throw new SkyflowException(); + LogUtil.printErrorLog(ErrorLogs.INVOKE_CONNECTION_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.getMessage(), e); } return connectionResponse; } - private void setBearerToken() throws SkyflowException { - Validations.validateCredentials(super.getFinalCredentials()); - if (token == null || Token.isExpired(token)) { - token = Utils.generateBearerToken(super.getFinalCredentials()); - } - HttpBearerAuth Bearer = (HttpBearerAuth) super.getApiClient().getAuthentication("Bearer"); - Bearer.setBearerToken(token); - } - private JsonObject convertObjectToJson(Object object) { Gson gson = new Gson(); JsonElement jsonElement = gson.toJsonTree(object); diff --git a/v2/src/test/java/com/skyflow/SkyflowTests.java b/v2/src/test/java/com/skyflow/SkyflowTests.java index cfdd7e5a..efdc54dc 100644 --- a/v2/src/test/java/com/skyflow/SkyflowTests.java +++ b/v2/src/test/java/com/skyflow/SkyflowTests.java @@ -20,6 +20,7 @@ public class SkyflowTests { private static String newClusterID = null; private static String connectionID = null; private static String connectionURL = null; + private static String newConnectionURL = null; private static String token = null; @BeforeClass @@ -29,6 +30,7 @@ public static void setup() { newClusterID = "new_test_cluster_id"; connectionID = "test_connection_id"; connectionURL = "https://test.connection.url"; + newConnectionURL = "https://new.test.connection.url"; token = "test_token"; } @@ -147,8 +149,6 @@ public void testUpdatingValidVaultConfigInSkyflowClient() { skyflowClient.updateVaultConfig(config); } catch (SkyflowException e) { Assert.fail(INVALID_EXCEPTION_THROWN); - } catch (Exception e) { - Assert.fail(INVALID_EXCEPTION_THROWN); } } @@ -208,10 +208,10 @@ public void testAddingInvalidConnectionConfigInSkyflowBuilder() { config.setConnectionId(""); config.setConnectionUrl(connectionURL); Skyflow.builder().addConnectionConfig(config).build(); -// Assert.fail(EXCEPTION_NOT_THROWN); - } catch (Exception e) { -// Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); - Assert.assertEquals(ErrorMessage.EmptyVaultId.getMessage(), e.getMessage()); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyConnectionId.getMessage(), e.getMessage()); } } @@ -223,10 +223,134 @@ public void testAddingInvalidConnectionConfigInSkyflowClient() { config.setConnectionUrl(connectionURL); Skyflow skyflowClient = Skyflow.builder().build(); skyflowClient.addConnectionConfig(config); -// Assert.fail(EXCEPTION_NOT_THROWN); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyConnectionId.getMessage(), e.getMessage()); + } + } + + @Test + public void testAddingValidConnectionConfigInSkyflowClient() { + try { + ConnectionConfig config = new ConnectionConfig(); + config.setConnectionId(connectionID); + config.setConnectionUrl(connectionURL); + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.addConnectionConfig(config); } catch (Exception e) { -// Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); - Assert.assertEquals(ErrorMessage.EmptyVaultId.getMessage(), e.getMessage()); + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testAddingExistingConnectionConfigInSkyflowClient() { + try { + ConnectionConfig config = new ConnectionConfig(); + config.setConnectionId(connectionID); + config.setConnectionUrl(connectionURL); + Skyflow skyflowClient = Skyflow.builder().addConnectionConfig(config).build(); + skyflowClient.addConnectionConfig(config); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.ConnectionIdAlreadyInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testUpdatingNonExistentConnectionConfigInSkyflowBuilder() { + try { + ConnectionConfig config = new ConnectionConfig(); + config.setConnectionId(connectionID); + config.setConnectionUrl(connectionURL); + Skyflow.builder().updateConnectionConfig(config).build(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.ConnectionIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testUpdatingNonExistentConnectionConfigInSkyflowClient() { + try { + ConnectionConfig config = new ConnectionConfig(); + config.setConnectionId(connectionID); + config.setConnectionUrl(connectionURL); + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.updateConnectionConfig(config); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.ConnectionIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testUpdatingValidConnectionConfigInSkyflowClient() { + try { + ConnectionConfig config = new ConnectionConfig(); + config.setConnectionId(connectionID); + config.setConnectionUrl(connectionURL); + Skyflow skyflowClient = Skyflow.builder().addConnectionConfig(config).build(); + + Credentials credentials = new Credentials(); + credentials.setToken(token); + + config.setConnectionUrl(newConnectionURL); + config.setCredentials(credentials); + + skyflowClient.updateConnectionConfig(config); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testRemovingNonExistentConnectionConfigInSkyflowBuilder() { + try { + Skyflow.builder().removeConnectionConfig(connectionID).build(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.ConnectionIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testRemovingNonExistentConnectionConfigInSkyflowClient() { + try { + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.removeConnectionConfig(connectionID); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.ConnectionIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testRemovingValidConnectionConfigInSkyflowClient() { + try { + ConnectionConfig config = new ConnectionConfig(); + config.setConnectionId(connectionID); + config.setConnectionUrl(connectionURL); + Skyflow skyflowClient = Skyflow.builder().addConnectionConfig(config).build(); + skyflowClient.removeConnectionConfig(connectionID); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGettingNonExistentConnectionConfigInSkyflowClient() { + try { + Skyflow skyflowClient = Skyflow.builder().build(); + ConnectionConfig config = skyflowClient.getConnectionConfig(connectionID); + Assert.assertNull(config); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); } } @@ -245,9 +369,17 @@ public void testAddingInvalidSkyflowCredentialsInSkyflowBuilder() { @Test public void testUpdatingValidSkyflowCredentialsInSkyflowClient() { try { + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + + ConnectionConfig connectionConfig = new ConnectionConfig(); + connectionConfig.setConnectionId(connectionID); + connectionConfig.setConnectionUrl(connectionURL); + Credentials credentials = new Credentials(); credentials.setToken(token); - Skyflow skyflowClient = Skyflow.builder().build(); + Skyflow skyflowClient = Skyflow.builder().addVaultConfig(vaultConfig).addConnectionConfig(connectionConfig).build(); skyflowClient.updateSkyflowCredentials(credentials); } catch (SkyflowException e) { Assert.fail(INVALID_EXCEPTION_THROWN); @@ -260,7 +392,6 @@ public void testDefaultLogLevel() { Skyflow skyflowClient = Skyflow.builder().setLogLevel(null).build(); Assert.assertEquals(LogLevel.ERROR, skyflowClient.getLogLevel()); } catch (Exception e) { - e.printStackTrace(); Assert.fail(INVALID_EXCEPTION_THROWN); } } @@ -277,5 +408,4 @@ public void testUpdateLogLevel() { } } - } diff --git a/v2/src/test/java/com/skyflow/config/CredentialsTests.java b/v2/src/test/java/com/skyflow/config/CredentialsTests.java index 64f34c94..1b7f6e64 100644 --- a/v2/src/test/java/com/skyflow/config/CredentialsTests.java +++ b/v2/src/test/java/com/skyflow/config/CredentialsTests.java @@ -1,6 +1,5 @@ package com.skyflow.config; -import com.skyflow.config.Credentials; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; @@ -8,6 +7,7 @@ import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.validations.Validations; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @@ -48,6 +48,11 @@ public static void setup() throws SkyflowException, NoSuchMethodException { context = "test_context_value"; } + @Before + public void setupTest() { + roles.clear(); + } + @Test public void testValidCredentialsWithPath() { try { @@ -217,7 +222,6 @@ public void testNothingPassedInCredentials() { @Test public void testEmptyRolesInCredentials() { try { - roles.clear(); Credentials credentials = new Credentials(); credentials.setPath(path); credentials.setRoles(roles); diff --git a/v2/src/test/java/com/skyflow/utils/HttpUtilityTests.java b/v2/src/test/java/com/skyflow/utils/HttpUtilityTests.java new file mode 100644 index 00000000..816f1504 --- /dev/null +++ b/v2/src/test/java/com/skyflow/utils/HttpUtilityTests.java @@ -0,0 +1,123 @@ +package com.skyflow.utils; + +import com.google.gson.JsonObject; +import com.skyflow.errors.SkyflowException; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.BDDMockito.given; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({URL.class, HttpURLConnection.class}) +public class HttpUtilityTests { + + private static String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + @InjectMocks + HttpUtility httpUtility; + @Mock + OutputStream outputStream; + private String expected; + private String expectedError; + private URL url; + private HttpURLConnection mockConnection; + + @Before + public void setup() throws IOException { + expected = "{\"status\":\"success\"}"; + expectedError = "{\"status\":\"something went wrong\"}"; + mockConnection = Mockito.mock(HttpURLConnection.class); + given(mockConnection.getInputStream()).willReturn(new ByteArrayInputStream(expected.getBytes())); + given(mockConnection.getErrorStream()).willReturn(new ByteArrayInputStream(expectedError.getBytes())); + given(mockConnection.getOutputStream()).willReturn(outputStream); + given(mockConnection.getResponseCode()).willReturn(200); + given(mockConnection.getHeaderField(anyString())).willReturn("id"); + final URLStreamHandler handler = new URLStreamHandler() { + @Override + protected URLConnection openConnection(final URL arg0) throws IOException { + return mockConnection; + } + }; + url = new URL("https://google.com", "google.com", 80, "", handler); + } + + @Test + @PrepareForTest({URL.class, HttpURLConnection.class}) + public void testSendRequest() { + try { + given(mockConnection.getRequestProperty("content-type")).willReturn("application/json"); + Map headers = new HashMap<>(); + headers.put("content-type", "application/json"); + JsonObject params = new JsonObject(); + params.addProperty("key", "value"); + String response = httpUtility.sendRequest("GET", url, params, headers); + Assert.assertEquals(expected, response); + } catch (Exception e) { + fail(INVALID_EXCEPTION_THROWN); + } + } + + + @Test + @PrepareForTest({URL.class, HttpURLConnection.class}) + public void testSendRequestFormData() { + try { + given(mockConnection.getRequestProperty("content-type")).willReturn("multipart/form-data"); + Map headers = new HashMap<>(); + headers.put("content-type", "multipart/form-data"); + JsonObject params = new JsonObject(); + params.addProperty("key", "value"); + String response = httpUtility.sendRequest("GET", url, params, headers); + Assert.assertEquals(expected, response); + } catch (Exception e) { + fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + @PrepareForTest({URL.class, HttpURLConnection.class}) + public void testSendRequestFormURLEncoded() { + try { + given(mockConnection.getRequestProperty("content-type")).willReturn("application/x-www-form-urlencoded"); + Map headers = new HashMap<>(); + headers.put("content-type", "application/x-www-form-urlencoded"); + JsonObject params = new JsonObject(); + params.addProperty("key", "value"); + String response = httpUtility.sendRequest("GET", url, params, headers); + Assert.assertEquals(expected, response); + } catch (Exception e) { + fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + @PrepareForTest({URL.class, HttpURLConnection.class}) + public void testSendRequestError() { + try { + given(mockConnection.getResponseCode()).willReturn(500); + String response = httpUtility.sendRequest("GET", url, null, null); + } catch (SkyflowException e) { + Assert.assertEquals(expectedError, e.getMessage()); + } catch (Exception e) { + fail(INVALID_EXCEPTION_THROWN); + } + } +} diff --git a/v2/src/test/java/com/skyflow/utils/UtilsTests.java b/v2/src/test/java/com/skyflow/utils/UtilsTests.java index 33a83f59..5a1b9de7 100644 --- a/v2/src/test/java/com/skyflow/utils/UtilsTests.java +++ b/v2/src/test/java/com/skyflow/utils/UtilsTests.java @@ -1,15 +1,20 @@ package com.skyflow.utils; +import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; import com.skyflow.enums.Env; +import com.skyflow.enums.RequestMethod; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.connection.InvokeConnectionRequest; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; public class UtilsTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; @@ -21,6 +26,11 @@ public class UtilsTests { private static String token = null; private static String context = null; private static ArrayList roles = null; + private static String connectionId = null; + private static String connectionUrl = null; + private static Map queryParams; + private static Map pathParams; + private static Map requestHeaders; @BeforeClass public static void setup() { @@ -33,6 +43,11 @@ public static void setup() { roles = new ArrayList<>(); String role = "test_role"; roles.add(role); + connectionId = "test_connection_id"; + connectionUrl = "https://test.connection.url"; + pathParams = new HashMap<>(); + queryParams = new HashMap<>(); + requestHeaders = new HashMap<>(); } @Test @@ -133,4 +148,37 @@ public void testGenerateBearerTokenWithToken() { Assert.fail(INVALID_EXCEPTION_THROWN); } } + + @Test + public void testConstructConnectionURL() { + try { + queryParams.put("query_param", "value"); + pathParams.put("path_param", "value"); + + ConnectionConfig connectionConfig = new ConnectionConfig(); + connectionConfig.setConnectionId(connectionId); + connectionConfig.setConnectionUrl(connectionUrl); + + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST).pathParams(pathParams).queryParams(queryParams).build(); + String filledUrl = Utils.constructConnectionURL(connectionConfig, request); + Assert.assertEquals(connectionUrl + "?" + "query_param=value", filledUrl); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testConstructConnectionHeaderMap() { + try { + requestHeaders.put("HEADER", "value"); + Map headers = Utils.constructConnectionHeadersMap(requestHeaders); + Assert.assertEquals(1, headers.size()); + Assert.assertTrue(headers.containsKey("header")); + Assert.assertFalse(headers.containsKey("HEADER")); + Assert.assertEquals("value", headers.get("header")); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } } diff --git a/v2/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java b/v2/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java new file mode 100644 index 00000000..2294bdaa --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java @@ -0,0 +1,394 @@ +package com.skyflow.vault.connection; + +import com.skyflow.enums.RequestMethod; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +public class InvokeConnectionTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static Map queryParams; + private static Map pathParams; + private static Map requestHeaders; + private static Map requestBody; + + @BeforeClass + public static void setup() { + queryParams = new HashMap<>(); + pathParams = new HashMap<>(); + requestHeaders = new HashMap<>(); + requestBody = new HashMap<>(); + } + + @Before + public void setupTest() { + queryParams.clear(); + pathParams.clear(); + requestHeaders.clear(); + requestBody.clear(); + } + + @Test + public void testValidInputInInvokeConnectionRequestValidations() { + queryParams.put("query_param", "value"); + pathParams.put("path_param", "value"); + requestHeaders.put("header", "value"); + requestBody.put("key", "value"); + try { + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.assertEquals(1, request.getQueryParams().size()); + Assert.assertEquals(1, request.getPathParams().size()); + Assert.assertEquals(1, request.getRequestHeaders().size()); + Assert.assertEquals(RequestMethod.POST, request.getMethodName()); + Assert.assertNotNull(request.getRequestBody()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testEmptyRequestHeadersInInvokeConnectionRequestValidations() { + try { + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyRequestHeaders.getMessage(), e.getMessage()); + } + } + + @Test + public void testNullRequestHeaderKeyInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value1"); + requestHeaders.put(null, "value2"); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidRequestHeaders.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyRequestHeaderKeyInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value"); + requestHeaders.put("", "value"); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidRequestHeaders.getMessage(), e.getMessage()); + } + } + + @Test + public void testNullRequestHeaderValueInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value"); + requestHeaders.put("header2", null); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidRequestHeaders.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyRequestHeaderValueInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value"); + requestHeaders.put("header2", ""); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidRequestHeaders.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyPathParamsInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value"); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyPathParams.getMessage(), e.getMessage()); + } + } + + @Test + public void testNullPathParamKeyInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value"); + pathParams.put("path_param", "value"); + pathParams.put(null, "value"); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidPathParams.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyPathParamKeyInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value"); + pathParams.put("path_param", "value"); + pathParams.put("", "value"); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidPathParams.getMessage(), e.getMessage()); + } + } + + @Test + public void testNullPathParamValueInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value"); + pathParams.put("path_param1", "value"); + pathParams.put("path_param2", null); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidPathParams.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyPathParamValueInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value"); + pathParams.put("path_param1", "value"); + pathParams.put("path_param2", ""); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidPathParams.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyQueryParamsInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value"); + pathParams.put("path_param", "value"); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyQueryParams.getMessage(), e.getMessage()); + } + } + + @Test + public void testNullQueryParamKeyInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value"); + pathParams.put("path_param", "value"); + queryParams.put("query_param", "value"); + queryParams.put(null, "value"); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidQueryParams.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyQueryParamKeyInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value"); + pathParams.put("path_param", "value"); + queryParams.put("query_param", "value"); + queryParams.put("", "value"); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidQueryParams.getMessage(), e.getMessage()); + } + } + + @Test + public void testNullQueryParamValueInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value"); + pathParams.put("path_param", "value"); + queryParams.put("query_param1", "value"); + queryParams.put("query_param2", null); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidQueryParams.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyQueryParamValueInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header1", "value"); + pathParams.put("path_param", "value"); + queryParams.put("query_param1", "value"); + queryParams.put("query_param2", ""); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.InvalidQueryParams.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyRequestBodyInInvokeConnectionRequestValidations() { + try { + requestHeaders.put("header", "value"); + pathParams.put("path_param", "value"); + queryParams.put("query_param", "value"); + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(requestBody) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyRequestBody.getMessage(), e.getMessage()); + } + } +} diff --git a/v2/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java b/v2/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java new file mode 100644 index 00000000..0b933b4a --- /dev/null +++ b/v2/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java @@ -0,0 +1,49 @@ +package com.skyflow.vault.controller; + +import com.skyflow.Skyflow; +import com.skyflow.config.ConnectionConfig; +import com.skyflow.config.Credentials; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.connection.InvokeConnectionRequest; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ConnectionControllerTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String connectionID = null; + private static String connectionURL = null; + private static ConnectionConfig connectionConfig = null; + private static Skyflow skyflowClient = null; + + @BeforeClass + public static void setup() { + connectionID = "vault123"; + connectionURL = "https://test.connection.url"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + connectionConfig = new ConnectionConfig(); + connectionConfig.setConnectionId(connectionID); + connectionConfig.setConnectionUrl(connectionURL); + connectionConfig.setCredentials(credentials); + } + + @Test + public void testInvalidRequestInInvokeConnectionMethod() { + try { + InvokeConnectionRequest connectionRequest = InvokeConnectionRequest.builder().build(); + Skyflow skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addConnectionConfig(connectionConfig).build(); + skyflowClient.connection().invoke(connectionRequest); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorMessage.EmptyRequestHeaders.getMessage(), e.getMessage()); + } + } +} diff --git a/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index b4185260..d569cbc9 100644 --- a/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -1,80 +1,35 @@ package com.skyflow.vault.tokens; -import com.skyflow.Skyflow; -import com.skyflow.config.Credentials; -import com.skyflow.config.VaultConfig; -import com.skyflow.enums.Env; -import com.skyflow.enums.LogLevel; import com.skyflow.enums.RedactionType; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.ApiException; -import com.skyflow.generated.rest.api.TokensApi; -import com.skyflow.generated.rest.models.V1DetokenizeResponse; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.util.ArrayList; -//@RunWith(PowerMockRunner.class) -//@PrepareForTest(fullyQualifiedNames = { -// "com.skyflow.serviceaccount.util.Token", -// "com.skyflow.generated.rest.ApiClient", -// "com.skyflow.generated.rest.api.TokensApi", -//}) public class DetokenizeTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; - private static String vaultID = null; - private static String clusterID = null; - private static VaultConfig vaultConfig = null; private static String token = null; private static ArrayList tokens = null; - private static Skyflow skyflowClient = null; - private ApiClient mockApiClient; - private TokensApi mockTokensApi; @BeforeClass public static void setup() throws SkyflowException, NoSuchMethodException { -// PowerMockito.mockStatic(Token.class); -// PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); -// PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); - - vaultID = "vault123"; - clusterID = "cluster123"; - - Credentials credentials = new Credentials(); - credentials.setToken("valid-token"); - - vaultConfig = new VaultConfig(); - vaultConfig.setVaultId(vaultID); - vaultConfig.setClusterId(clusterID); - vaultConfig.setEnv(Env.DEV); - vaultConfig.setCredentials(credentials); - - token = "test_token_1"; tokens = new ArrayList<>(); - -// System.setProperty("ssl.TrustManagerFactory.algorithm", "PKIX"); + token = "test_token_1"; } -// @Before -// public void setupMock() throws ApiException { -// mockApiClient = PowerMockito.mock(ApiClient.class); -// mockTokensApi = PowerMockito.mock(TokensApi.class); -// -// V1DetokenizeResponse mockResponse = new V1DetokenizeResponse(); -// PowerMockito -// .when(mockTokensApi.recordServiceDetokenize(ArgumentMatchers.anyString(), ArgumentMatchers.any())) -// .thenReturn(mockResponse); -// -// } + @Before + public void setupTest() { + tokens.clear(); + } @Test public void testValidInputInDetokenizeRequestValidations() { @@ -110,7 +65,6 @@ public void testNoTokensInDetokenizeRequestValidations() { @Test public void testEmptyTokensInDetokenizeRequestValidations() { - tokens.clear(); DetokenizeRequest request = DetokenizeRequest.builder().tokens(tokens).build(); try { Validations.validateDetokenizeRequest(request); @@ -147,7 +101,6 @@ public void testEmptyTokenInTokensInDetokenizeRequestValidations() { @Test public void testRedactionAndContinueOnErrorInDetokenizeRequestValidations() { - tokens.clear(); tokens.add(token); DetokenizeRequest request = DetokenizeRequest.builder(). tokens(tokens).redactionType(null).continueOnError(null).build(); From 8efdf12e903c037ec62ee81f230b15084efad53e Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 15 Nov 2024 17:38:16 +0530 Subject: [PATCH 043/126] SK-1623 Java SDK v2 Removed v1,v2 modules and moved all v2 code directly to parent module Removed unnecessary dependencies --- pom.xml | 76 +- .../java/com/skyflow/ConnectionClient.java | 0 .../main/java/com/skyflow/Skyflow.java | 0 .../main/java/com/skyflow/VaultClient.java | 0 .../com/skyflow/config/ConnectionConfig.java | 0 .../java/com/skyflow/config/Credentials.java | 0 .../com/skyflow/config/ManagementConfig.java | 0 .../java/com/skyflow/config/VaultConfig.java | 0 .../main/java/com/skyflow/enums/Byot.java | 0 .../main/java/com/skyflow/enums/Env.java | 0 .../java/com/skyflow/enums/InterfaceName.java | 0 .../main/java/com/skyflow/enums/LogLevel.java | 0 .../java/com/skyflow/enums/RedactionType.java | 0 .../java/com/skyflow/enums/RequestMethod.java | 0 .../java/com/skyflow/errors/ErrorCode.java | 0 .../java/com/skyflow/errors/ErrorMessage.java | 0 .../com/skyflow/errors/SkyflowException.java | 0 .../skyflow/generated/rest/ApiCallback.java | 0 .../com/skyflow/generated/rest/ApiClient.java | 0 .../skyflow/generated/rest/ApiException.java | 0 .../skyflow/generated/rest/ApiResponse.java | 0 .../skyflow/generated/rest/Configuration.java | 0 .../rest/GzipRequestInterceptor.java | 0 .../java/com/skyflow/generated/rest/JSON.java | 0 .../java/com/skyflow/generated/rest/Pair.java | 0 .../generated/rest/ProgressRequestBody.java | 0 .../generated/rest/ProgressResponseBody.java | 0 .../generated/rest/ServerConfiguration.java | 0 .../generated/rest/ServerVariable.java | 0 .../skyflow/generated/rest/StringUtil.java | 0 .../skyflow/generated/rest/api/AuditApi.java | 0 .../generated/rest/api/AuthenticationApi.java | 0 .../generated/rest/api/BinLookupApi.java | 0 .../skyflow/generated/rest/api/QueryApi.java | 0 .../generated/rest/api/RecordsApi.java | 0 .../skyflow/generated/rest/api/TokensApi.java | 0 .../generated/rest/auth/ApiKeyAuth.java | 0 .../generated/rest/auth/Authentication.java | 0 .../generated/rest/auth/HttpBasicAuth.java | 0 .../generated/rest/auth/HttpBearerAuth.java | 0 .../rest/models/AbstractOpenApiSchema.java | 0 .../models/AuditEventAuditResourceType.java | 0 .../rest/models/AuditEventContext.java | 0 .../generated/rest/models/AuditEventData.java | 0 .../rest/models/AuditEventHTTPInfo.java | 0 .../rest/models/BatchRecordMethod.java | 0 .../rest/models/ContextAccessType.java | 0 .../rest/models/ContextAuthMode.java | 0 .../DetokenizeRecordResponseValueType.java | 0 .../rest/models/GooglerpcStatus.java | 0 .../generated/rest/models/ProtobufAny.java | 0 .../models/QueryServiceExecuteQueryBody.java | 0 .../RecordServiceBatchOperationBody.java | 0 .../RecordServiceBulkDeleteRecordBody.java | 0 .../models/RecordServiceInsertRecordBody.java | 0 .../models/RecordServiceUpdateRecordBody.java | 0 .../rest/models/RedactionEnumREDACTION.java | 0 .../rest/models/RequestActionType.java | 0 .../rest/models/V1AuditAfterOptions.java | 0 .../rest/models/V1AuditEventResponse.java | 0 .../rest/models/V1AuditResponse.java | 0 .../rest/models/V1AuditResponseEvent.java | 0 .../models/V1AuditResponseEventRequest.java | 0 .../rest/models/V1BINListRequest.java | 0 .../rest/models/V1BINListResponse.java | 0 .../skyflow/generated/rest/models/V1BYOT.java | 0 .../rest/models/V1BatchOperationResponse.java | 0 .../generated/rest/models/V1BatchRecord.java | 0 .../models/V1BulkDeleteRecordResponse.java | 0 .../rest/models/V1BulkGetRecordResponse.java | 0 .../skyflow/generated/rest/models/V1Card.java | 0 .../rest/models/V1DeleteFileResponse.java | 0 .../rest/models/V1DeleteRecordResponse.java | 0 .../rest/models/V1DetokenizePayload.java | 0 .../models/V1DetokenizeRecordRequest.java | 0 .../models/V1DetokenizeRecordResponse.java | 0 .../rest/models/V1DetokenizeResponse.java | 0 .../generated/rest/models/V1FieldRecords.java | 0 .../rest/models/V1FileAVScanStatus.java | 0 .../rest/models/V1GetAuthTokenRequest.java | 0 .../rest/models/V1GetAuthTokenResponse.java | 0 .../models/V1GetFileScanStatusResponse.java | 0 .../rest/models/V1GetQueryResponse.java | 0 .../rest/models/V1InsertRecordResponse.java | 0 .../generated/rest/models/V1MemberType.java | 0 .../rest/models/V1RecordMetaProperties.java | 0 .../rest/models/V1TokenizePayload.java | 0 .../rest/models/V1TokenizeRecordRequest.java | 0 .../rest/models/V1TokenizeRecordResponse.java | 0 .../rest/models/V1TokenizeResponse.java | 0 .../rest/models/V1UpdateRecordResponse.java | 0 .../rest/models/V1VaultFieldMapping.java | 0 .../rest/models/V1VaultSchemaConfig.java | 0 .../main/java/com/skyflow/logs/ErrorLogs.java | 0 .../main/java/com/skyflow/logs/InfoLogs.java | 0 .../serviceaccount/util/BearerToken.java | 0 .../util/SignedDataTokenResponse.java | 0 .../serviceaccount/util/SignedDataTokens.java | 0 .../skyflow/serviceaccount/util/Token.java | 0 .../java/com/skyflow/utils/Constants.java | 0 .../java/com/skyflow/utils/HttpUtility.java | 0 .../main/java/com/skyflow/utils/Utils.java | 0 .../com/skyflow/utils/logger/LogUtil.java | 0 .../utils/validations/Validations.java | 0 .../skyflow/vault/audit/ListEventRequest.java | 0 .../vault/audit/ListEventResponse.java | 0 .../com/skyflow/vault/bin/GetBinRequest.java | 0 .../com/skyflow/vault/bin/GetBinResponse.java | 0 .../connection/InvokeConnectionRequest.java | 0 .../connection/InvokeConnectionResponse.java | 0 .../vault/controller/AuditController.java | 0 .../vault/controller/BinLookupController.java | 0 .../controller/ConnectionController.java | 0 .../vault/controller/DetectController.java | 0 .../vault/controller/VaultController.java | 0 .../com/skyflow/vault/data/DeleteRequest.java | 0 .../skyflow/vault/data/DeleteResponse.java | 0 .../com/skyflow/vault/data/GetRequest.java | 0 .../com/skyflow/vault/data/GetResponse.java | 0 .../com/skyflow/vault/data/InsertRequest.java | 0 .../skyflow/vault/data/InsertResponse.java | 0 .../com/skyflow/vault/data/QueryRequest.java | 0 .../com/skyflow/vault/data/QueryResponse.java | 0 .../com/skyflow/vault/data/UpdateRequest.java | 0 .../skyflow/vault/data/UpdateResponse.java | 0 .../vault/detect/DeIdentifyRequest.java | 0 .../vault/detect/DeIdentifyResponse.java | 0 .../com/skyflow/vault/tokens/ColumnValue.java | 0 .../tokens/DetokenizeRecordResponse.java | 0 .../vault/tokens/DetokenizeRequest.java | 0 .../vault/tokens/DetokenizeResponse.java | 0 .../skyflow/vault/tokens/TokenizeRequest.java | 0 .../vault/tokens/TokenizeResponse.java | 0 .../test/java/com/skyflow/SkyflowTests.java | 0 .../skyflow/config/ConnectionConfigTests.java | 0 .../com/skyflow/config/CredentialsTests.java | 0 .../com/skyflow/config/VaultConfigTests.java | 0 .../serviceaccount/util/BearerTokenTests.java | 0 .../util/SignedDataTokensTests.java | 0 .../serviceaccount/util/TokenTests.java | 12 +- .../com/skyflow/utils/HttpUtilityTests.java | 0 .../java/com/skyflow/utils/UtilsTests.java | 0 .../connection/InvokeConnectionTests.java | 15 + .../controller/ConnectionControllerTests.java | 0 .../controller/VaultControllerTests.java | 0 .../com/skyflow/vault/data/DeleteTests.java | 13 +- .../java/com/skyflow/vault/data/GetTests.java | 0 .../com/skyflow/vault/data/InsertTests.java | 0 .../com/skyflow/vault/data/QueryTests.java | 0 .../com/skyflow/vault/data/UpdateTests.java | 70 +- .../skyflow/vault/tokens/DetokenizeTests.java | 0 .../skyflow/vault/tokens/TokenizeTests.java | 0 .../invalidPrivateKeyCredentials.json | 0 .../resources/invalidTokenURICredentials.json | 0 .../test/resources/noClientIDCredentials.json | 0 .../test/resources/noKeyIDCredentials.json | 0 .../resources/noPrivateKeyCredentials.json | 0 .../test/resources/noTokenURICredentials.json | 0 {v2/src => src}/test/resources/notJson.txt | 0 v1/pom.xml | 20 - v1/src/main/java/DetokenizeExample.java | 71 - v1/src/main/java/InsertExample.java | 84 - .../main/java/com/skyflow/Configuration.java | 16 - .../com/skyflow/common/utils/Constants.java | 8 - .../com/skyflow/common/utils/Helpers.java | 440 --- .../com/skyflow/common/utils/HttpUtility.java | 107 - .../com/skyflow/common/utils/LogUtil.java | 102 - .../com/skyflow/common/utils/TokenUtils.java | 74 - .../com/skyflow/common/utils/Validators.java | 176 -- .../com/skyflow/entities/DeleteInput.java | 13 - .../com/skyflow/entities/DeleteOptions.java | 5 - .../skyflow/entities/DeleteRecordInput.java | 22 - .../com/skyflow/entities/DetokenizeInput.java | 16 - .../skyflow/entities/DetokenizeRecord.java | 25 - .../com/skyflow/entities/GetByIdInput.java | 16 - .../skyflow/entities/GetByIdRecordInput.java | 34 - .../java/com/skyflow/entities/GetInput.java | 16 - .../java/com/skyflow/entities/GetOptions.java | 16 - .../com/skyflow/entities/GetRecordInput.java | 52 - .../skyflow/entities/InsertBulkOptions.java | 35 - .../com/skyflow/entities/InsertInput.java | 17 - .../com/skyflow/entities/InsertOptions.java | 60 - .../skyflow/entities/InsertRecordInput.java | 27 - .../java/com/skyflow/entities/LogLevel.java | 12 - .../java/com/skyflow/entities/QueryInput.java | 13 - .../com/skyflow/entities/QueryOptions.java | 8 - .../skyflow/entities/QueryRecordInput.java | 11 - .../com/skyflow/entities/RedactionType.java | 24 - .../com/skyflow/entities/RequestMethod.java | 25 - .../com/skyflow/entities/ResponseToken.java | 25 - .../entities/SkyflowConfiguration.java | 46 - .../com/skyflow/entities/TokenProvider.java | 10 - .../com/skyflow/entities/UpdateInput.java | 13 - .../com/skyflow/entities/UpdateOptions.java | 18 - .../skyflow/entities/UpdateRecordInput.java | 35 - .../com/skyflow/entities/UpsertOption.java | 22 - .../java/com/skyflow/errors/ErrorCode.java | 79 - .../com/skyflow/errors/SkyflowException.java | 54 - .../main/java/com/skyflow/logs/DebugLogs.java | 19 - .../main/java/com/skyflow/logs/ErrorLogs.java | 70 - .../main/java/com/skyflow/logs/InfoLogs.java | 39 - .../main/java/com/skyflow/logs/WarnLogs.java | 18 - .../serviceaccount/util/BearerToken.java | 229 -- .../util/SignedDataTokenResponse.java | 20 - .../serviceaccount/util/SignedDataTokens.java | 224 -- .../skyflow/serviceaccount/util/Token.java | 231 -- .../com/skyflow/vault/DeleteBySkyflowId.java | 94 - .../java/com/skyflow/vault/Detokenize.java | 102 - v1/src/main/java/com/skyflow/vault/Get.java | 138 - .../com/skyflow/vault/GetBySkyflowId.java | 110 - .../main/java/com/skyflow/vault/Insert.java | 120 - .../main/java/com/skyflow/vault/Skyflow.java | 565 ---- .../com/skyflow/vault/UpdateBySkyflowId.java | 106 - .../com/skyflow/common/utils/HelpersTest.java | 205 -- .../skyflow/common/utils/HttpUtilityTest.java | 154 - .../skyflow/common/utils/TokenUtilsTest.java | 87 - .../utils/TokenUtilsValidTokenTest.java | 88 - .../skyflow/common/utils/ValidatorsTest.java | 160 -- .../serviceaccount/util/BearerTokenTest.java | 275 -- .../util/SignedDataTokenResponseTest.java | 19 - .../util/SignedDataTokensTest.java | 197 -- .../serviceaccount/util/TokenTest.java | 229 -- .../com/skyflow/vault/DeleteMethodTest.java | 421 --- .../java/com/skyflow/vault/GetMethodTest.java | 870 ------ .../skyflow/vault/InvokeConnectionTest.java | 258 -- .../java/com/skyflow/vault/SkyflowTest.java | 2485 ----------------- v1/src/test/resources/invalidCredentials.json | 1 - v1/src/test/resources/notJson.txt | 0 v2/pom.xml | 70 - 229 files changed, 125 insertions(+), 9512 deletions(-) rename {v2/src => src}/main/java/com/skyflow/ConnectionClient.java (100%) rename {v2/src => src}/main/java/com/skyflow/Skyflow.java (100%) rename {v2/src => src}/main/java/com/skyflow/VaultClient.java (100%) rename {v2/src => src}/main/java/com/skyflow/config/ConnectionConfig.java (100%) rename {v2/src => src}/main/java/com/skyflow/config/Credentials.java (100%) rename {v2/src => src}/main/java/com/skyflow/config/ManagementConfig.java (100%) rename {v2/src => src}/main/java/com/skyflow/config/VaultConfig.java (100%) rename {v2/src => src}/main/java/com/skyflow/enums/Byot.java (100%) rename {v2/src => src}/main/java/com/skyflow/enums/Env.java (100%) rename {v2/src => src}/main/java/com/skyflow/enums/InterfaceName.java (100%) rename {v2/src => src}/main/java/com/skyflow/enums/LogLevel.java (100%) rename {v2/src => src}/main/java/com/skyflow/enums/RedactionType.java (100%) rename {v2/src => src}/main/java/com/skyflow/enums/RequestMethod.java (100%) rename {v2/src => src}/main/java/com/skyflow/errors/ErrorCode.java (100%) rename {v2/src => src}/main/java/com/skyflow/errors/ErrorMessage.java (100%) rename {v2/src => src}/main/java/com/skyflow/errors/SkyflowException.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/ApiCallback.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/ApiClient.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/ApiException.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/ApiResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/Configuration.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/JSON.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/Pair.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/ProgressRequestBody.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/ProgressResponseBody.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/ServerConfiguration.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/ServerVariable.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/StringUtil.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/api/AuditApi.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/api/BinLookupApi.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/api/QueryApi.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/api/RecordsApi.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/api/TokensApi.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/auth/Authentication.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/AuditEventContext.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/AuditEventData.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/ContextAccessType.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/ProtobufAny.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/RequestActionType.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1BYOT.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1Card.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1MemberType.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java (100%) rename {v2/src => src}/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java (100%) rename {v2/src => src}/main/java/com/skyflow/logs/ErrorLogs.java (100%) rename {v2/src => src}/main/java/com/skyflow/logs/InfoLogs.java (100%) rename {v2/src => src}/main/java/com/skyflow/serviceaccount/util/BearerToken.java (100%) rename {v2/src => src}/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java (100%) rename {v2/src => src}/main/java/com/skyflow/serviceaccount/util/Token.java (100%) rename {v2/src => src}/main/java/com/skyflow/utils/Constants.java (100%) rename {v2/src => src}/main/java/com/skyflow/utils/HttpUtility.java (100%) rename {v2/src => src}/main/java/com/skyflow/utils/Utils.java (100%) rename {v2/src => src}/main/java/com/skyflow/utils/logger/LogUtil.java (100%) rename {v2/src => src}/main/java/com/skyflow/utils/validations/Validations.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/audit/ListEventRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/audit/ListEventResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/bin/GetBinRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/bin/GetBinResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/controller/AuditController.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/controller/BinLookupController.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/controller/ConnectionController.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/controller/DetectController.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/controller/VaultController.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/data/DeleteRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/data/DeleteResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/data/GetRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/data/GetResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/data/InsertRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/data/InsertResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/data/QueryRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/data/QueryResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/data/UpdateRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/data/UpdateResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/tokens/ColumnValue.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/tokens/TokenizeRequest.java (100%) rename {v2/src => src}/main/java/com/skyflow/vault/tokens/TokenizeResponse.java (100%) rename {v2/src => src}/test/java/com/skyflow/SkyflowTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/config/ConnectionConfigTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/config/CredentialsTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/config/VaultConfigTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/serviceaccount/util/TokenTests.java (75%) rename {v2/src => src}/test/java/com/skyflow/utils/HttpUtilityTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/utils/UtilsTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java (96%) rename {v2/src => src}/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/vault/controller/VaultControllerTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/vault/data/DeleteTests.java (97%) rename {v2/src => src}/test/java/com/skyflow/vault/data/GetTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/vault/data/InsertTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/vault/data/QueryTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/vault/data/UpdateTests.java (88%) rename {v2/src => src}/test/java/com/skyflow/vault/tokens/DetokenizeTests.java (100%) rename {v2/src => src}/test/java/com/skyflow/vault/tokens/TokenizeTests.java (100%) rename {v2/src => src}/test/resources/invalidPrivateKeyCredentials.json (100%) rename {v2/src => src}/test/resources/invalidTokenURICredentials.json (100%) rename {v2/src => src}/test/resources/noClientIDCredentials.json (100%) rename {v2/src => src}/test/resources/noKeyIDCredentials.json (100%) rename {v2/src => src}/test/resources/noPrivateKeyCredentials.json (100%) rename {v2/src => src}/test/resources/noTokenURICredentials.json (100%) rename {v2/src => src}/test/resources/notJson.txt (100%) delete mode 100644 v1/pom.xml delete mode 100644 v1/src/main/java/DetokenizeExample.java delete mode 100644 v1/src/main/java/InsertExample.java delete mode 100644 v1/src/main/java/com/skyflow/Configuration.java delete mode 100644 v1/src/main/java/com/skyflow/common/utils/Constants.java delete mode 100644 v1/src/main/java/com/skyflow/common/utils/Helpers.java delete mode 100644 v1/src/main/java/com/skyflow/common/utils/HttpUtility.java delete mode 100644 v1/src/main/java/com/skyflow/common/utils/LogUtil.java delete mode 100644 v1/src/main/java/com/skyflow/common/utils/TokenUtils.java delete mode 100644 v1/src/main/java/com/skyflow/common/utils/Validators.java delete mode 100644 v1/src/main/java/com/skyflow/entities/DeleteInput.java delete mode 100644 v1/src/main/java/com/skyflow/entities/DeleteOptions.java delete mode 100644 v1/src/main/java/com/skyflow/entities/DeleteRecordInput.java delete mode 100644 v1/src/main/java/com/skyflow/entities/DetokenizeInput.java delete mode 100644 v1/src/main/java/com/skyflow/entities/DetokenizeRecord.java delete mode 100644 v1/src/main/java/com/skyflow/entities/GetByIdInput.java delete mode 100644 v1/src/main/java/com/skyflow/entities/GetByIdRecordInput.java delete mode 100644 v1/src/main/java/com/skyflow/entities/GetInput.java delete mode 100644 v1/src/main/java/com/skyflow/entities/GetOptions.java delete mode 100644 v1/src/main/java/com/skyflow/entities/GetRecordInput.java delete mode 100644 v1/src/main/java/com/skyflow/entities/InsertBulkOptions.java delete mode 100644 v1/src/main/java/com/skyflow/entities/InsertInput.java delete mode 100644 v1/src/main/java/com/skyflow/entities/InsertOptions.java delete mode 100644 v1/src/main/java/com/skyflow/entities/InsertRecordInput.java delete mode 100644 v1/src/main/java/com/skyflow/entities/LogLevel.java delete mode 100644 v1/src/main/java/com/skyflow/entities/QueryInput.java delete mode 100644 v1/src/main/java/com/skyflow/entities/QueryOptions.java delete mode 100644 v1/src/main/java/com/skyflow/entities/QueryRecordInput.java delete mode 100644 v1/src/main/java/com/skyflow/entities/RedactionType.java delete mode 100644 v1/src/main/java/com/skyflow/entities/RequestMethod.java delete mode 100644 v1/src/main/java/com/skyflow/entities/ResponseToken.java delete mode 100644 v1/src/main/java/com/skyflow/entities/SkyflowConfiguration.java delete mode 100644 v1/src/main/java/com/skyflow/entities/TokenProvider.java delete mode 100644 v1/src/main/java/com/skyflow/entities/UpdateInput.java delete mode 100644 v1/src/main/java/com/skyflow/entities/UpdateOptions.java delete mode 100644 v1/src/main/java/com/skyflow/entities/UpdateRecordInput.java delete mode 100644 v1/src/main/java/com/skyflow/entities/UpsertOption.java delete mode 100644 v1/src/main/java/com/skyflow/errors/ErrorCode.java delete mode 100644 v1/src/main/java/com/skyflow/errors/SkyflowException.java delete mode 100644 v1/src/main/java/com/skyflow/logs/DebugLogs.java delete mode 100644 v1/src/main/java/com/skyflow/logs/ErrorLogs.java delete mode 100644 v1/src/main/java/com/skyflow/logs/InfoLogs.java delete mode 100644 v1/src/main/java/com/skyflow/logs/WarnLogs.java delete mode 100644 v1/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java delete mode 100644 v1/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java delete mode 100644 v1/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java delete mode 100644 v1/src/main/java/com/skyflow/serviceaccount/util/Token.java delete mode 100644 v1/src/main/java/com/skyflow/vault/DeleteBySkyflowId.java delete mode 100644 v1/src/main/java/com/skyflow/vault/Detokenize.java delete mode 100644 v1/src/main/java/com/skyflow/vault/Get.java delete mode 100644 v1/src/main/java/com/skyflow/vault/GetBySkyflowId.java delete mode 100644 v1/src/main/java/com/skyflow/vault/Insert.java delete mode 100644 v1/src/main/java/com/skyflow/vault/Skyflow.java delete mode 100644 v1/src/main/java/com/skyflow/vault/UpdateBySkyflowId.java delete mode 100644 v1/src/test/java/com/skyflow/common/utils/HelpersTest.java delete mode 100644 v1/src/test/java/com/skyflow/common/utils/HttpUtilityTest.java delete mode 100644 v1/src/test/java/com/skyflow/common/utils/TokenUtilsTest.java delete mode 100644 v1/src/test/java/com/skyflow/common/utils/TokenUtilsValidTokenTest.java delete mode 100644 v1/src/test/java/com/skyflow/common/utils/ValidatorsTest.java delete mode 100644 v1/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTest.java delete mode 100644 v1/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokenResponseTest.java delete mode 100644 v1/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTest.java delete mode 100644 v1/src/test/java/com/skyflow/serviceaccount/util/TokenTest.java delete mode 100644 v1/src/test/java/com/skyflow/vault/DeleteMethodTest.java delete mode 100644 v1/src/test/java/com/skyflow/vault/GetMethodTest.java delete mode 100644 v1/src/test/java/com/skyflow/vault/InvokeConnectionTest.java delete mode 100644 v1/src/test/java/com/skyflow/vault/SkyflowTest.java delete mode 100644 v1/src/test/resources/invalidCredentials.json delete mode 100644 v1/src/test/resources/notJson.txt delete mode 100644 v2/pom.xml diff --git a/pom.xml b/pom.xml index 85befa48..12533834 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ com.skyflow skyflow-java 1.15.0 - pom + jar ${project.groupId}:${project.artifactId} Skyflow SDK for the Java programming language @@ -25,10 +25,6 @@ skyflow - - v1 - v2 - scm:git:git://github.com:skyflowapi/skyflow-java.git scm:git:ssh://github.com:skyflowapi/skyflow-java.git @@ -41,6 +37,11 @@ 4.12.0 2.10.1 1.9.0 + UTF-8 + 4.12.0 + 5.10.3 + 1.10.0 + 1.3.5 @@ -55,49 +56,68 @@ + - com.fasterxml.jackson.core - jackson-core - 2.13.0 + io.github.cdimascio + dotenv-java + 3.0.0 - com.googlecode.json-simple - json-simple - 1.1.1 + com.google.code.findbugs + jsr305 + 3.0.2 - io.jsonwebtoken - jjwt - 0.9.1 + io.gsonfire + gson-fire + ${gson-fire-version} + + + com.google.code.gson + gson + ${gson-version} + + + com.squareup.okhttp3 + okhttp + ${okhttp-version} + + com.squareup.okhttp3 + logging-interceptor + ${okhttp-version} + + commons-codec commons-codec 1.15 - javax.xml.bind - jaxb-api - 2.3.1 + io.jsonwebtoken + jjwt + 0.9.1 - io.jsonwebtoken - jjwt-impl - 0.11.2 - runtime + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation-version} + provided + - io.jsonwebtoken - jjwt-jackson - 0.11.2 - runtime + org.junit.jupiter + junit-jupiter-engine + ${junit-version} + test - junit - junit - 4.13.2 + org.junit.platform + junit-platform-runner + ${junit-platform-runner.version} test + org.powermock powermock-module-junit4 diff --git a/v2/src/main/java/com/skyflow/ConnectionClient.java b/src/main/java/com/skyflow/ConnectionClient.java similarity index 100% rename from v2/src/main/java/com/skyflow/ConnectionClient.java rename to src/main/java/com/skyflow/ConnectionClient.java diff --git a/v2/src/main/java/com/skyflow/Skyflow.java b/src/main/java/com/skyflow/Skyflow.java similarity index 100% rename from v2/src/main/java/com/skyflow/Skyflow.java rename to src/main/java/com/skyflow/Skyflow.java diff --git a/v2/src/main/java/com/skyflow/VaultClient.java b/src/main/java/com/skyflow/VaultClient.java similarity index 100% rename from v2/src/main/java/com/skyflow/VaultClient.java rename to src/main/java/com/skyflow/VaultClient.java diff --git a/v2/src/main/java/com/skyflow/config/ConnectionConfig.java b/src/main/java/com/skyflow/config/ConnectionConfig.java similarity index 100% rename from v2/src/main/java/com/skyflow/config/ConnectionConfig.java rename to src/main/java/com/skyflow/config/ConnectionConfig.java diff --git a/v2/src/main/java/com/skyflow/config/Credentials.java b/src/main/java/com/skyflow/config/Credentials.java similarity index 100% rename from v2/src/main/java/com/skyflow/config/Credentials.java rename to src/main/java/com/skyflow/config/Credentials.java diff --git a/v2/src/main/java/com/skyflow/config/ManagementConfig.java b/src/main/java/com/skyflow/config/ManagementConfig.java similarity index 100% rename from v2/src/main/java/com/skyflow/config/ManagementConfig.java rename to src/main/java/com/skyflow/config/ManagementConfig.java diff --git a/v2/src/main/java/com/skyflow/config/VaultConfig.java b/src/main/java/com/skyflow/config/VaultConfig.java similarity index 100% rename from v2/src/main/java/com/skyflow/config/VaultConfig.java rename to src/main/java/com/skyflow/config/VaultConfig.java diff --git a/v2/src/main/java/com/skyflow/enums/Byot.java b/src/main/java/com/skyflow/enums/Byot.java similarity index 100% rename from v2/src/main/java/com/skyflow/enums/Byot.java rename to src/main/java/com/skyflow/enums/Byot.java diff --git a/v2/src/main/java/com/skyflow/enums/Env.java b/src/main/java/com/skyflow/enums/Env.java similarity index 100% rename from v2/src/main/java/com/skyflow/enums/Env.java rename to src/main/java/com/skyflow/enums/Env.java diff --git a/v2/src/main/java/com/skyflow/enums/InterfaceName.java b/src/main/java/com/skyflow/enums/InterfaceName.java similarity index 100% rename from v2/src/main/java/com/skyflow/enums/InterfaceName.java rename to src/main/java/com/skyflow/enums/InterfaceName.java diff --git a/v2/src/main/java/com/skyflow/enums/LogLevel.java b/src/main/java/com/skyflow/enums/LogLevel.java similarity index 100% rename from v2/src/main/java/com/skyflow/enums/LogLevel.java rename to src/main/java/com/skyflow/enums/LogLevel.java diff --git a/v2/src/main/java/com/skyflow/enums/RedactionType.java b/src/main/java/com/skyflow/enums/RedactionType.java similarity index 100% rename from v2/src/main/java/com/skyflow/enums/RedactionType.java rename to src/main/java/com/skyflow/enums/RedactionType.java diff --git a/v2/src/main/java/com/skyflow/enums/RequestMethod.java b/src/main/java/com/skyflow/enums/RequestMethod.java similarity index 100% rename from v2/src/main/java/com/skyflow/enums/RequestMethod.java rename to src/main/java/com/skyflow/enums/RequestMethod.java diff --git a/v2/src/main/java/com/skyflow/errors/ErrorCode.java b/src/main/java/com/skyflow/errors/ErrorCode.java similarity index 100% rename from v2/src/main/java/com/skyflow/errors/ErrorCode.java rename to src/main/java/com/skyflow/errors/ErrorCode.java diff --git a/v2/src/main/java/com/skyflow/errors/ErrorMessage.java b/src/main/java/com/skyflow/errors/ErrorMessage.java similarity index 100% rename from v2/src/main/java/com/skyflow/errors/ErrorMessage.java rename to src/main/java/com/skyflow/errors/ErrorMessage.java diff --git a/v2/src/main/java/com/skyflow/errors/SkyflowException.java b/src/main/java/com/skyflow/errors/SkyflowException.java similarity index 100% rename from v2/src/main/java/com/skyflow/errors/SkyflowException.java rename to src/main/java/com/skyflow/errors/SkyflowException.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/ApiCallback.java b/src/main/java/com/skyflow/generated/rest/ApiCallback.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/ApiCallback.java rename to src/main/java/com/skyflow/generated/rest/ApiCallback.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/ApiClient.java b/src/main/java/com/skyflow/generated/rest/ApiClient.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/ApiClient.java rename to src/main/java/com/skyflow/generated/rest/ApiClient.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/ApiException.java b/src/main/java/com/skyflow/generated/rest/ApiException.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/ApiException.java rename to src/main/java/com/skyflow/generated/rest/ApiException.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/ApiResponse.java b/src/main/java/com/skyflow/generated/rest/ApiResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/ApiResponse.java rename to src/main/java/com/skyflow/generated/rest/ApiResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/Configuration.java b/src/main/java/com/skyflow/generated/rest/Configuration.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/Configuration.java rename to src/main/java/com/skyflow/generated/rest/Configuration.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java b/src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java rename to src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/JSON.java b/src/main/java/com/skyflow/generated/rest/JSON.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/JSON.java rename to src/main/java/com/skyflow/generated/rest/JSON.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/Pair.java b/src/main/java/com/skyflow/generated/rest/Pair.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/Pair.java rename to src/main/java/com/skyflow/generated/rest/Pair.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java b/src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java rename to src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java b/src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java rename to src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/ServerConfiguration.java b/src/main/java/com/skyflow/generated/rest/ServerConfiguration.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/ServerConfiguration.java rename to src/main/java/com/skyflow/generated/rest/ServerConfiguration.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/ServerVariable.java b/src/main/java/com/skyflow/generated/rest/ServerVariable.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/ServerVariable.java rename to src/main/java/com/skyflow/generated/rest/ServerVariable.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/StringUtil.java b/src/main/java/com/skyflow/generated/rest/StringUtil.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/StringUtil.java rename to src/main/java/com/skyflow/generated/rest/StringUtil.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/api/AuditApi.java b/src/main/java/com/skyflow/generated/rest/api/AuditApi.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/api/AuditApi.java rename to src/main/java/com/skyflow/generated/rest/api/AuditApi.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java b/src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java rename to src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java b/src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java rename to src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/api/QueryApi.java b/src/main/java/com/skyflow/generated/rest/api/QueryApi.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/api/QueryApi.java rename to src/main/java/com/skyflow/generated/rest/api/QueryApi.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/api/RecordsApi.java b/src/main/java/com/skyflow/generated/rest/api/RecordsApi.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/api/RecordsApi.java rename to src/main/java/com/skyflow/generated/rest/api/RecordsApi.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/api/TokensApi.java b/src/main/java/com/skyflow/generated/rest/api/TokensApi.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/api/TokensApi.java rename to src/main/java/com/skyflow/generated/rest/api/TokensApi.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java b/src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java rename to src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/auth/Authentication.java b/src/main/java/com/skyflow/generated/rest/auth/Authentication.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/auth/Authentication.java rename to src/main/java/com/skyflow/generated/rest/auth/Authentication.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java b/src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java rename to src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java b/src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java rename to src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java b/src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java rename to src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java b/src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java rename to src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java b/src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java rename to src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventData.java b/src/main/java/com/skyflow/generated/rest/models/AuditEventData.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/AuditEventData.java rename to src/main/java/com/skyflow/generated/rest/models/AuditEventData.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java b/src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java rename to src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java b/src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java rename to src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java b/src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java rename to src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java b/src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java rename to src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java b/src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java rename to src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java b/src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java rename to src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java b/src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java rename to src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java b/src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java rename to src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java b/src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java rename to src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java b/src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java rename to src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java b/src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java rename to src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java b/src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java rename to src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java b/src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java rename to src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/RequestActionType.java b/src/main/java/com/skyflow/generated/rest/models/RequestActionType.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/RequestActionType.java rename to src/main/java/com/skyflow/generated/rest/models/RequestActionType.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java rename to src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java rename to src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java rename to src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java rename to src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BYOT.java b/src/main/java/com/skyflow/generated/rest/models/V1BYOT.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1BYOT.java rename to src/main/java/com/skyflow/generated/rest/models/V1BYOT.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java b/src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java rename to src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1Card.java b/src/main/java/com/skyflow/generated/rest/models/V1Card.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1Card.java rename to src/main/java/com/skyflow/generated/rest/models/V1Card.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java b/src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java rename to src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java rename to src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java b/src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java rename to src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java b/src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java rename to src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java rename to src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1MemberType.java b/src/main/java/com/skyflow/generated/rest/models/V1MemberType.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1MemberType.java rename to src/main/java/com/skyflow/generated/rest/models/V1MemberType.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java b/src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java rename to src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java b/src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java rename to src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java rename to src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java rename to src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java b/src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java rename to src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java diff --git a/v2/src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java b/src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java similarity index 100% rename from v2/src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java rename to src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java diff --git a/v2/src/main/java/com/skyflow/logs/ErrorLogs.java b/src/main/java/com/skyflow/logs/ErrorLogs.java similarity index 100% rename from v2/src/main/java/com/skyflow/logs/ErrorLogs.java rename to src/main/java/com/skyflow/logs/ErrorLogs.java diff --git a/v2/src/main/java/com/skyflow/logs/InfoLogs.java b/src/main/java/com/skyflow/logs/InfoLogs.java similarity index 100% rename from v2/src/main/java/com/skyflow/logs/InfoLogs.java rename to src/main/java/com/skyflow/logs/InfoLogs.java diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java b/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java similarity index 100% rename from v2/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java rename to src/main/java/com/skyflow/serviceaccount/util/BearerToken.java diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java rename to src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java similarity index 100% rename from v2/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java rename to src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java diff --git a/v2/src/main/java/com/skyflow/serviceaccount/util/Token.java b/src/main/java/com/skyflow/serviceaccount/util/Token.java similarity index 100% rename from v2/src/main/java/com/skyflow/serviceaccount/util/Token.java rename to src/main/java/com/skyflow/serviceaccount/util/Token.java diff --git a/v2/src/main/java/com/skyflow/utils/Constants.java b/src/main/java/com/skyflow/utils/Constants.java similarity index 100% rename from v2/src/main/java/com/skyflow/utils/Constants.java rename to src/main/java/com/skyflow/utils/Constants.java diff --git a/v2/src/main/java/com/skyflow/utils/HttpUtility.java b/src/main/java/com/skyflow/utils/HttpUtility.java similarity index 100% rename from v2/src/main/java/com/skyflow/utils/HttpUtility.java rename to src/main/java/com/skyflow/utils/HttpUtility.java diff --git a/v2/src/main/java/com/skyflow/utils/Utils.java b/src/main/java/com/skyflow/utils/Utils.java similarity index 100% rename from v2/src/main/java/com/skyflow/utils/Utils.java rename to src/main/java/com/skyflow/utils/Utils.java diff --git a/v2/src/main/java/com/skyflow/utils/logger/LogUtil.java b/src/main/java/com/skyflow/utils/logger/LogUtil.java similarity index 100% rename from v2/src/main/java/com/skyflow/utils/logger/LogUtil.java rename to src/main/java/com/skyflow/utils/logger/LogUtil.java diff --git a/v2/src/main/java/com/skyflow/utils/validations/Validations.java b/src/main/java/com/skyflow/utils/validations/Validations.java similarity index 100% rename from v2/src/main/java/com/skyflow/utils/validations/Validations.java rename to src/main/java/com/skyflow/utils/validations/Validations.java diff --git a/v2/src/main/java/com/skyflow/vault/audit/ListEventRequest.java b/src/main/java/com/skyflow/vault/audit/ListEventRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/audit/ListEventRequest.java rename to src/main/java/com/skyflow/vault/audit/ListEventRequest.java diff --git a/v2/src/main/java/com/skyflow/vault/audit/ListEventResponse.java b/src/main/java/com/skyflow/vault/audit/ListEventResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/audit/ListEventResponse.java rename to src/main/java/com/skyflow/vault/audit/ListEventResponse.java diff --git a/v2/src/main/java/com/skyflow/vault/bin/GetBinRequest.java b/src/main/java/com/skyflow/vault/bin/GetBinRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/bin/GetBinRequest.java rename to src/main/java/com/skyflow/vault/bin/GetBinRequest.java diff --git a/v2/src/main/java/com/skyflow/vault/bin/GetBinResponse.java b/src/main/java/com/skyflow/vault/bin/GetBinResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/bin/GetBinResponse.java rename to src/main/java/com/skyflow/vault/bin/GetBinResponse.java diff --git a/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java b/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java rename to src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java diff --git a/v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java b/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java rename to src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java diff --git a/v2/src/main/java/com/skyflow/vault/controller/AuditController.java b/src/main/java/com/skyflow/vault/controller/AuditController.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/controller/AuditController.java rename to src/main/java/com/skyflow/vault/controller/AuditController.java diff --git a/v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java b/src/main/java/com/skyflow/vault/controller/BinLookupController.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/controller/BinLookupController.java rename to src/main/java/com/skyflow/vault/controller/BinLookupController.java diff --git a/v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java b/src/main/java/com/skyflow/vault/controller/ConnectionController.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/controller/ConnectionController.java rename to src/main/java/com/skyflow/vault/controller/ConnectionController.java diff --git a/v2/src/main/java/com/skyflow/vault/controller/DetectController.java b/src/main/java/com/skyflow/vault/controller/DetectController.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/controller/DetectController.java rename to src/main/java/com/skyflow/vault/controller/DetectController.java diff --git a/v2/src/main/java/com/skyflow/vault/controller/VaultController.java b/src/main/java/com/skyflow/vault/controller/VaultController.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/controller/VaultController.java rename to src/main/java/com/skyflow/vault/controller/VaultController.java diff --git a/v2/src/main/java/com/skyflow/vault/data/DeleteRequest.java b/src/main/java/com/skyflow/vault/data/DeleteRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/data/DeleteRequest.java rename to src/main/java/com/skyflow/vault/data/DeleteRequest.java diff --git a/v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java b/src/main/java/com/skyflow/vault/data/DeleteResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/data/DeleteResponse.java rename to src/main/java/com/skyflow/vault/data/DeleteResponse.java diff --git a/v2/src/main/java/com/skyflow/vault/data/GetRequest.java b/src/main/java/com/skyflow/vault/data/GetRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/data/GetRequest.java rename to src/main/java/com/skyflow/vault/data/GetRequest.java diff --git a/v2/src/main/java/com/skyflow/vault/data/GetResponse.java b/src/main/java/com/skyflow/vault/data/GetResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/data/GetResponse.java rename to src/main/java/com/skyflow/vault/data/GetResponse.java diff --git a/v2/src/main/java/com/skyflow/vault/data/InsertRequest.java b/src/main/java/com/skyflow/vault/data/InsertRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/data/InsertRequest.java rename to src/main/java/com/skyflow/vault/data/InsertRequest.java diff --git a/v2/src/main/java/com/skyflow/vault/data/InsertResponse.java b/src/main/java/com/skyflow/vault/data/InsertResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/data/InsertResponse.java rename to src/main/java/com/skyflow/vault/data/InsertResponse.java diff --git a/v2/src/main/java/com/skyflow/vault/data/QueryRequest.java b/src/main/java/com/skyflow/vault/data/QueryRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/data/QueryRequest.java rename to src/main/java/com/skyflow/vault/data/QueryRequest.java diff --git a/v2/src/main/java/com/skyflow/vault/data/QueryResponse.java b/src/main/java/com/skyflow/vault/data/QueryResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/data/QueryResponse.java rename to src/main/java/com/skyflow/vault/data/QueryResponse.java diff --git a/v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java b/src/main/java/com/skyflow/vault/data/UpdateRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/data/UpdateRequest.java rename to src/main/java/com/skyflow/vault/data/UpdateRequest.java diff --git a/v2/src/main/java/com/skyflow/vault/data/UpdateResponse.java b/src/main/java/com/skyflow/vault/data/UpdateResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/data/UpdateResponse.java rename to src/main/java/com/skyflow/vault/data/UpdateResponse.java diff --git a/v2/src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java b/src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java rename to src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java diff --git a/v2/src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java b/src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java rename to src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java diff --git a/v2/src/main/java/com/skyflow/vault/tokens/ColumnValue.java b/src/main/java/com/skyflow/vault/tokens/ColumnValue.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/tokens/ColumnValue.java rename to src/main/java/com/skyflow/vault/tokens/ColumnValue.java diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java rename to src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java rename to src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java diff --git a/v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java rename to src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java diff --git a/v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java b/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java rename to src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java diff --git a/v2/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java b/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java similarity index 100% rename from v2/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java rename to src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java diff --git a/v2/src/test/java/com/skyflow/SkyflowTests.java b/src/test/java/com/skyflow/SkyflowTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/SkyflowTests.java rename to src/test/java/com/skyflow/SkyflowTests.java diff --git a/v2/src/test/java/com/skyflow/config/ConnectionConfigTests.java b/src/test/java/com/skyflow/config/ConnectionConfigTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/config/ConnectionConfigTests.java rename to src/test/java/com/skyflow/config/ConnectionConfigTests.java diff --git a/v2/src/test/java/com/skyflow/config/CredentialsTests.java b/src/test/java/com/skyflow/config/CredentialsTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/config/CredentialsTests.java rename to src/test/java/com/skyflow/config/CredentialsTests.java diff --git a/v2/src/test/java/com/skyflow/config/VaultConfigTests.java b/src/test/java/com/skyflow/config/VaultConfigTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/config/VaultConfigTests.java rename to src/test/java/com/skyflow/config/VaultConfigTests.java diff --git a/v2/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java b/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java rename to src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java diff --git a/v2/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java rename to src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java diff --git a/v2/src/test/java/com/skyflow/serviceaccount/util/TokenTests.java b/src/test/java/com/skyflow/serviceaccount/util/TokenTests.java similarity index 75% rename from v2/src/test/java/com/skyflow/serviceaccount/util/TokenTests.java rename to src/test/java/com/skyflow/serviceaccount/util/TokenTests.java index d1ac044b..ed5c72b2 100644 --- a/v2/src/test/java/com/skyflow/serviceaccount/util/TokenTests.java +++ b/src/test/java/com/skyflow/serviceaccount/util/TokenTests.java @@ -1,11 +1,20 @@ package com.skyflow.serviceaccount.util; +import com.skyflow.Skyflow; +import com.skyflow.enums.LogLevel; +import io.github.cdimascio.dotenv.Dotenv; import org.junit.Assert; +import org.junit.BeforeClass; import org.junit.Test; public class TokenTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + @BeforeClass + public static void setup() { + Skyflow skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).build(); + } + @Test public void testNoTokenForIsExpiredToken() { try { @@ -36,7 +45,8 @@ public void testInvalidTokenForIsExpiredToken() { @Test public void testExpiredTokenForIsExpiredToken() { try { - String token = System.getProperty("TEST_EXPIRED_TOKEN"); + Dotenv dotenv = Dotenv.load(); + String token = dotenv.get("TEST_EXPIRED_TOKEN"); Assert.assertTrue(Token.isExpired(token)); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); diff --git a/v2/src/test/java/com/skyflow/utils/HttpUtilityTests.java b/src/test/java/com/skyflow/utils/HttpUtilityTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/utils/HttpUtilityTests.java rename to src/test/java/com/skyflow/utils/HttpUtilityTests.java diff --git a/v2/src/test/java/com/skyflow/utils/UtilsTests.java b/src/test/java/com/skyflow/utils/UtilsTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/utils/UtilsTests.java rename to src/test/java/com/skyflow/utils/UtilsTests.java diff --git a/v2/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java similarity index 96% rename from v2/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java rename to src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java index 2294bdaa..db23e010 100644 --- a/v2/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java +++ b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java @@ -1,5 +1,6 @@ package com.skyflow.vault.connection; +import com.google.gson.JsonObject; import com.skyflow.enums.RequestMethod; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; @@ -391,4 +392,18 @@ public void testEmptyRequestBodyInInvokeConnectionRequestValidations() { Assert.assertEquals(ErrorMessage.EmptyRequestBody.getMessage(), e.getMessage()); } } + + @Test + public void testInvokeConnectionResponse() { + try { + JsonObject responseObject = new JsonObject(); + responseObject.addProperty("test_key_1", "test_value_1"); + responseObject.addProperty("test_key_2", "test_value_2"); + InvokeConnectionResponse connectionResponse = new InvokeConnectionResponse(responseObject); + String responseString = "InvokeConnectionResponse{" + "response=" + responseObject + "}"; + Assert.assertEquals(responseString, connectionResponse.toString()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } } diff --git a/v2/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java b/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java rename to src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java diff --git a/v2/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java rename to src/test/java/com/skyflow/vault/controller/VaultControllerTests.java diff --git a/v2/src/test/java/com/skyflow/vault/data/DeleteTests.java b/src/test/java/com/skyflow/vault/data/DeleteTests.java similarity index 97% rename from v2/src/test/java/com/skyflow/vault/data/DeleteTests.java rename to src/test/java/com/skyflow/vault/data/DeleteTests.java index 9ab78af6..5f2eefc7 100644 --- a/v2/src/test/java/com/skyflow/vault/data/DeleteTests.java +++ b/src/test/java/com/skyflow/vault/data/DeleteTests.java @@ -12,6 +12,7 @@ import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @@ -58,6 +59,11 @@ public static void setup() throws SkyflowException { table = "test_table"; } + @Before + public void setupTest() { + ids.clear(); + } + @Test public void testValidInputInDeleteRequestValidations() { try { @@ -88,7 +94,7 @@ public void testNoIdsInDeleteRequestValidations() { @Test public void testEmptyIdsInDeleteRequestValidations() { - ids.clear(); +// ids.clear(); DeleteRequest request = DeleteRequest.builder().ids(ids).table(table).build(); try { Validations.validateDeleteRequest(request); @@ -121,7 +127,7 @@ public void testEmptyIdInIdsInDeleteRequestValidations() { @Test public void testNoTableInDeleteRequestValidations() { - ids.clear(); +// ids.clear(); ids.add(skyflowID); DeleteRequest request = DeleteRequest.builder().ids(ids).build(); try { @@ -138,7 +144,7 @@ public void testNoTableInDeleteRequestValidations() { @Test public void testEmptyTableInDeleteRequestValidations() { - ids.clear(); +// ids.clear(); ids.add(skyflowID); DeleteRequest request = DeleteRequest.builder().ids(ids).table("").build(); try { @@ -156,6 +162,7 @@ public void testEmptyTableInDeleteRequestValidations() { @Test public void testDeleteResponse() { try { + ids.add(skyflowID); DeleteResponse response = new DeleteResponse(ids); String responseString = "{\n\t\"deletedIds\": [\n\t\t\"" + skyflowID + "\"]\n}"; Assert.assertEquals(1, response.getDeletedIds().size()); diff --git a/v2/src/test/java/com/skyflow/vault/data/GetTests.java b/src/test/java/com/skyflow/vault/data/GetTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/vault/data/GetTests.java rename to src/test/java/com/skyflow/vault/data/GetTests.java diff --git a/v2/src/test/java/com/skyflow/vault/data/InsertTests.java b/src/test/java/com/skyflow/vault/data/InsertTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/vault/data/InsertTests.java rename to src/test/java/com/skyflow/vault/data/InsertTests.java diff --git a/v2/src/test/java/com/skyflow/vault/data/QueryTests.java b/src/test/java/com/skyflow/vault/data/QueryTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/vault/data/QueryTests.java rename to src/test/java/com/skyflow/vault/data/QueryTests.java diff --git a/v2/src/test/java/com/skyflow/vault/data/UpdateTests.java b/src/test/java/com/skyflow/vault/data/UpdateTests.java similarity index 88% rename from v2/src/test/java/com/skyflow/vault/data/UpdateTests.java rename to src/test/java/com/skyflow/vault/data/UpdateTests.java index 3780a417..22417257 100644 --- a/v2/src/test/java/com/skyflow/vault/data/UpdateTests.java +++ b/src/test/java/com/skyflow/vault/data/UpdateTests.java @@ -13,6 +13,7 @@ import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @@ -53,20 +54,24 @@ public static void setup() throws SkyflowException { vaultConfig.setEnv(Env.DEV); vaultConfig.setCredentials(credentials); -// skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - skyflowID = "test_update_id_1"; table = "test_table"; valueMap = new HashMap<>(); - valueMap.put("test_column_1", "test_value_1"); - valueMap.put("test_column_2", "test_value_2"); tokenMap = new HashMap<>(); - tokenMap.put("test_column_1", "test_token_1"); + } + + @Before + public void setupTest() { + valueMap.clear(); + tokenMap.clear(); } @Test public void testValidInputInUpdateRequestValidations() { try { + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.put("test_column_1", "test_token_1"); UpdateRequest request = UpdateRequest.builder() .id(skyflowID) .table(table) @@ -163,8 +168,7 @@ public void testNoValuesInUpdateRequestValidations() { @Test public void testEmptyValuesInUpdateRequestValidations() { - HashMap emptyValueMap = new HashMap<>(); - UpdateRequest request = UpdateRequest.builder().id(skyflowID).table(table).values(emptyValueMap).build(); + UpdateRequest request = UpdateRequest.builder().id(skyflowID).table(table).values(valueMap).build(); try { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); @@ -179,6 +183,8 @@ public void testEmptyValuesInUpdateRequestValidations() { @Test public void testEmptyKeyInValuesInUpdateRequestValidations() { + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); valueMap.put("", "test_value_3"); UpdateRequest request = UpdateRequest.builder().id(skyflowID).table(table).values(valueMap).build(); try { @@ -195,7 +201,8 @@ public void testEmptyKeyInValuesInUpdateRequestValidations() { @Test public void testEmptyValueInValuesInUpdateRequestValidations() { - valueMap.remove(""); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); valueMap.put("test_column_3", ""); UpdateRequest request = UpdateRequest.builder().id(skyflowID).table(table).values(valueMap).build(); try { @@ -212,7 +219,9 @@ public void testEmptyValueInValuesInUpdateRequestValidations() { @Test public void testTokensWithTokenStrictDisableInUpdateRequestValidations() { - valueMap.remove("test_column_3"); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.put("test_column_1", "test_token_1"); UpdateRequest request = UpdateRequest.builder() .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.DISABLE) .build(); @@ -230,6 +239,8 @@ public void testTokensWithTokenStrictDisableInUpdateRequestValidations() { @Test public void testNoTokensWithTokenStrictEnableInUpdateRequestValidations() { + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); UpdateRequest request = UpdateRequest.builder() .id(skyflowID).table(table).values(valueMap).tokenStrict(Byot.ENABLE) .build(); @@ -247,6 +258,8 @@ public void testNoTokensWithTokenStrictEnableInUpdateRequestValidations() { @Test public void testNoTokensWithTokenStrictEnableStrictInUpdateRequestValidations() { + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); UpdateRequest request = UpdateRequest.builder() .id(skyflowID).table(table).values(valueMap).tokenStrict(Byot.ENABLE_STRICT) .build(); @@ -264,9 +277,10 @@ public void testNoTokensWithTokenStrictEnableStrictInUpdateRequestValidations() @Test public void testEmptyTokensWithTokenStrictEnableInUpdateRequestValidations() { - HashMap emptyTokenMap = new HashMap<>(); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); UpdateRequest request = UpdateRequest.builder() - .id(skyflowID).table(table).values(valueMap).tokens(emptyTokenMap).tokenStrict(Byot.ENABLE) + .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE) .build(); try { Validations.validateUpdateRequest(request); @@ -278,21 +292,10 @@ public void testEmptyTokensWithTokenStrictEnableInUpdateRequestValidations() { } @Test - public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestValidations1() { - UpdateRequest request = UpdateRequest.builder() - .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) - .build(); - try { - Validations.validateUpdateRequest(request); - Assert.fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); - Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage(), e.getMessage()); - } - } - - @Test - public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestValidations2() { + public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestValidations() { + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.put("test_column_1", "test_token_1"); UpdateRequest request = UpdateRequest.builder() .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) .build(); @@ -307,6 +310,9 @@ public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestVali @Test public void testTokenValueMismatchInUpdateRequestValidations() { + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("test_column_3", "test_token_3"); UpdateRequest request = UpdateRequest.builder() .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) @@ -322,8 +328,9 @@ public void testTokenValueMismatchInUpdateRequestValidations() { @Test public void testEmptyKeyInTokensInUpdateRequestValidations() { - tokenMap.remove("test_column_2"); - tokenMap.remove("test_column_3"); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("", "test_token_2"); UpdateRequest request = UpdateRequest.builder() .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) @@ -339,7 +346,9 @@ public void testEmptyKeyInTokensInUpdateRequestValidations() { @Test public void testEmptyValueInTokensInUpdateRequestValidations() { - tokenMap.remove(""); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("test_column_2", ""); UpdateRequest request = UpdateRequest.builder() .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) @@ -356,6 +365,9 @@ public void testEmptyValueInTokensInUpdateRequestValidations() { @Test public void testUpdateResponse() { try { + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("test_column_2", "test_token_2"); UpdateResponse response = new UpdateResponse(skyflowID, tokenMap); String responseString = "{\n\t\"skyflowId\": " + skyflowID + "\n\t\"tokens\": " diff --git a/v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java rename to src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java diff --git a/v2/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java similarity index 100% rename from v2/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java rename to src/test/java/com/skyflow/vault/tokens/TokenizeTests.java diff --git a/v2/src/test/resources/invalidPrivateKeyCredentials.json b/src/test/resources/invalidPrivateKeyCredentials.json similarity index 100% rename from v2/src/test/resources/invalidPrivateKeyCredentials.json rename to src/test/resources/invalidPrivateKeyCredentials.json diff --git a/v2/src/test/resources/invalidTokenURICredentials.json b/src/test/resources/invalidTokenURICredentials.json similarity index 100% rename from v2/src/test/resources/invalidTokenURICredentials.json rename to src/test/resources/invalidTokenURICredentials.json diff --git a/v2/src/test/resources/noClientIDCredentials.json b/src/test/resources/noClientIDCredentials.json similarity index 100% rename from v2/src/test/resources/noClientIDCredentials.json rename to src/test/resources/noClientIDCredentials.json diff --git a/v2/src/test/resources/noKeyIDCredentials.json b/src/test/resources/noKeyIDCredentials.json similarity index 100% rename from v2/src/test/resources/noKeyIDCredentials.json rename to src/test/resources/noKeyIDCredentials.json diff --git a/v2/src/test/resources/noPrivateKeyCredentials.json b/src/test/resources/noPrivateKeyCredentials.json similarity index 100% rename from v2/src/test/resources/noPrivateKeyCredentials.json rename to src/test/resources/noPrivateKeyCredentials.json diff --git a/v2/src/test/resources/noTokenURICredentials.json b/src/test/resources/noTokenURICredentials.json similarity index 100% rename from v2/src/test/resources/noTokenURICredentials.json rename to src/test/resources/noTokenURICredentials.json diff --git a/v2/src/test/resources/notJson.txt b/src/test/resources/notJson.txt similarity index 100% rename from v2/src/test/resources/notJson.txt rename to src/test/resources/notJson.txt diff --git a/v1/pom.xml b/v1/pom.xml deleted file mode 100644 index ff3fc13a..00000000 --- a/v1/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - 4.0.0 - - com.skyflow - skyflow-java - 1.15.0 - - - v1 - - - 8 - 8 - UTF-8 - - - \ No newline at end of file diff --git a/v1/src/main/java/DetokenizeExample.java b/v1/src/main/java/DetokenizeExample.java deleted file mode 100644 index 8b2a657f..00000000 --- a/v1/src/main/java/DetokenizeExample.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ - -import com.skyflow.Configuration; -import com.skyflow.entities.*; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - - -public class DetokenizeExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration( - "l906001b0b4e4843a69b091f278f7017", - "https://sb.area51.vault.skyflowapis.dev", - new DemoTokenProvider() - ); - - Configuration.setLogLevel(LogLevel.DEBUG); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("token", "4304-0207-2378-9259"); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - JSONObject record1 = new JSONObject(); - record1.put("token", "3809-9467-7122-3994"); - record1.put("redaction", RedactionType.PLAIN_TEXT.toString()); - recordsArray.add(record); - recordsArray.add(record1); - records.put("records", recordsArray); - - JSONObject response = skyflowClient.detokenize(records); - System.out.println(response); - - } catch (SkyflowException e) { - e.printStackTrace(); - System.out.println(e.getData()); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwczovL21hbmFnZS5za3lmbG93YXBpcy5kZXYiLCJjbGkiOiJ2OGY0NTE1OWYxNjA0NzViYTk4MjAxOGJkMmFiMmVlZSIsImV4cCI6MTcxMTA5NDYwMSwiaWF0IjoxNzExMDkxMDAyLCJpc3MiOiJzYS1hdXRoQG1hbmFnZS5za3lmbG93YXBpcy5kZXYiLCJqdGkiOiJuMzk0OGI1ODIxOGQ0NWQ2OWQyYTExZjMwYjk2YmRiMiIsImtleSI6Imc0NDRmZTQxMmEzZTQ5ZTA5YjJlN2E4ZGE2ZDhkZWNlIiwic2NwIjpudWxsLCJzdWIiOiJzZGstZTJlLWJsaXR6LW5ldyJ9.D1bkgk8U5yC7Ped-eC8W4zc7CSImRdMbH2jvx9o_ADGYLmRsUJg3Jm004RtmCz6Vqy1hfgBobje4SgccavlYQTO3JUdtwx9SLJVwMGSEYnM_LvTAKqTVInJkvkKgJThHfh6na4iKWZlzUjNjhIFVjLcEhJuikRO68dpw8YFo84mc8iAjzW4BiKIyfAPzEUqIYq6VNUtz80ZsIhkfMz99_93NFf_KKzIR_a-MVYa7LzJfCrO6EQ-1fXLrTeJkusuco4MFSOf3-x55TimJygcQJjJC34lEtDK0OhFJWbM65gJRpRv6ftaknXRcp8caVE6xkqXI320O6GcBZK933aHw8w"; - - @Override - public String getBearerToken() throws Exception { -// ResponseToken response = null; -// try { -// String filePath = "/home/vivekj/SKYFLOW/SDKs/skyflow-java/samples/credentials.json"; -// if (Token.isExpired(bearerToken)) { -// response = Token.generateBearerToken(filePath); -// bearerToken = response.getAccessToken(); -// } -// } catch (SkyflowException e) { -// e.printStackTrace(); -// } - - return bearerToken; - } - } -} diff --git a/v1/src/main/java/InsertExample.java b/v1/src/main/java/InsertExample.java deleted file mode 100644 index 1cdd0900..00000000 --- a/v1/src/main/java/InsertExample.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ - -import com.skyflow.Configuration; -import com.skyflow.entities.*; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -public class InsertExample { - - public static void main(String[] args) { - // blitz -// String vaultID = ""; -// String vaultURL = ""; - - // stage - String vaultID = "aef438f3be974c8f897795ab02248f78"; - String vaultURL = "https://cf5643204594.vault.skyflowapis.tech"; - - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Configuration.setLogLevel(LogLevel.DEBUG); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", "customers"); - JSONObject fields = new JSONObject(); - fields.put("name", "chandragupta maurya"); - fields.put("card_number", "4111111111111111"); - fields.put("email", "chandragupta.maurya@test.com"); - record.put("fields", fields); - - JSONObject record2 = new JSONObject(); - record2.put("table", "pii_fields_upsert"); - JSONObject fields2 = new JSONObject(); - fields2.put("name", "java coe"); - fields2.put("card_number", "4111111111111111"); - fields2.put("expiration_year", "2025"); - fields2.put("expiration_month", "11"); - fields2.put("expiration_date", "11/25"); - fields2.put("cvv", "123"); - record2.put("fields", fields2); - - recordsArray.add(record); -// recordsArray.add(record2); - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(false); - JSONObject res = skyflowClient.insert(records, insertOptions); - - System.out.println("final response " + res); - } catch (SkyflowException e) { - System.out.println(e); - e.printStackTrace(); - } - } - - static class DemoTokenProvider implements TokenProvider { - private String bearerToken; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - String env = "stage"; - try { - String filePath = "/home/vivekj/Documents/credentials/sdk-integration-tests/" + env + "-credentials.json"; - if (Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - return bearerToken; - } - } -} diff --git a/v1/src/main/java/com/skyflow/Configuration.java b/v1/src/main/java/com/skyflow/Configuration.java deleted file mode 100644 index fac93b8b..00000000 --- a/v1/src/main/java/com/skyflow/Configuration.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow; - -import com.skyflow.common.utils.Helpers; -import com.skyflow.common.utils.LogUtil; -import com.skyflow.entities.LogLevel; -import com.skyflow.logs.InfoLogs; - -public final class Configuration { - public static void setLogLevel(LogLevel level) { - LogUtil.setupLogger(level); - LogUtil.printInfoLog(Helpers.parameterizedString(InfoLogs.CurrentLogLevel.getLog(), String.valueOf(level))); - } -} diff --git a/v1/src/main/java/com/skyflow/common/utils/Constants.java b/v1/src/main/java/com/skyflow/common/utils/Constants.java deleted file mode 100644 index 05e22578..00000000 --- a/v1/src/main/java/com/skyflow/common/utils/Constants.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.skyflow.common.utils; - -public class Constants { - - public static final String SDK_METRICS_HEADER_KEY = "sky-metadata"; - public static final String SDK_VERSION = "1.15.0"; - -} diff --git a/v1/src/main/java/com/skyflow/common/utils/Helpers.java b/v1/src/main/java/com/skyflow/common/utils/Helpers.java deleted file mode 100644 index e5c3bbfe..00000000 --- a/v1/src/main/java/com/skyflow/common/utils/Helpers.java +++ /dev/null @@ -1,440 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.common.utils; - -import com.skyflow.entities.*; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.logs.DebugLogs; -import com.skyflow.logs.ErrorLogs; -import org.apache.commons.codec.binary.Base64; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.util.*; - -public final class Helpers { - - private static final String LINE_FEED = "\r\n"; - - public static String getUpsertColumn(String tableName, UpsertOption[] upsertOptions) { - String upsertColumn = ""; - - for (UpsertOption upsertOption : upsertOptions) { - if (Objects.equals(tableName, upsertOption.getTable())) { - upsertColumn = upsertOption.getColumn(); - } - } - return upsertColumn; - } - - public static JSONObject constructInsertRequest(InsertInput recordsInput, InsertOptions options) - throws SkyflowException { - JSONObject finalRequest = new JSONObject(); - List requestBodyContent = new ArrayList(); - boolean isTokens = options.isTokens(); - boolean continueOnError = options.isContinueOnError(); - InsertRecordInput[] records = recordsInput.getRecords(); - - if (records == null || records.length == 0) { - throw new SkyflowException(ErrorCode.EmptyRecords); - } - - for (int i = 0; i < records.length; i++) { - InsertRecordInput record = records[i]; - - if (record.getTable() == null || record.getTable().isEmpty()) { - throw new SkyflowException(ErrorCode.InvalidTable); - } - if (record.getFields() == null) { - throw new SkyflowException(ErrorCode.InvalidFields); - } - - JSONObject postRequestInput = new JSONObject(); - postRequestInput.put("method", "POST"); - postRequestInput.put("quorum", true); - postRequestInput.put("tableName", record.getTable()); - postRequestInput.put("fields", record.getFields()); - if (options.getUpsertOptions() != null) - postRequestInput.put("upsert", getUpsertColumn(record.getTable(), options.getUpsertOptions())); - if (isTokens){ - postRequestInput.put("tokenization", true); - } - requestBodyContent.add(postRequestInput); - - } - finalRequest.put("records", requestBodyContent); - finalRequest.put("continueOnError", continueOnError); - - return finalRequest; - } - - public static JSONObject constructUpdateRequest(UpdateRecordInput record, UpdateOptions options) throws SkyflowException { - if (record == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidUpdateInput.getLog()); - throw new SkyflowException(ErrorCode.EmptyRecords); - } - if (record.getId() == null || record.getId().isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.InvalidSkyflowId.getLog()); - throw new SkyflowException(ErrorCode.InvalidSkyflowId); - } - if (record.getTable() == null || record.getTable().isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.InvalidTable.getLog()); - throw new SkyflowException(ErrorCode.InvalidTable); - } - if (record.getFields() == null || record.getFields().isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.InvalidField.getLog()); - throw new SkyflowException(ErrorCode.InvalidFields); - } - - JSONObject postRequestInput = new JSONObject(); - postRequestInput.put("fields", record.getFields()); - return postRequestInput; - - } - public static JSONObject constructQueryRequest(QueryRecordInput queryInput, QueryOptions options) - throws SkyflowException { - if (queryInput == null) { - throw new SkyflowException(ErrorCode.EmptyRecords); - } - JSONObject postRequestInput = new JSONObject(); - if (queryInput.getQuery() == null||queryInput.getQuery().trim().isEmpty()) { - throw new SkyflowException(ErrorCode.InvalidQuery); - } - postRequestInput.put("query", queryInput.getQuery()); - return postRequestInput; - } - - public static JSONObject constructQueryErrorObject(SkyflowException skyflowException) { - JSONObject finalResponseError = new JSONObject(); - try { - JSONObject errorObject = (JSONObject) ((JSONObject) new JSONParser().parse(skyflowException.getMessage())).get("error"); - if (errorObject != null) { - JSONObject responseError = new JSONObject(); - responseError.put("code", errorObject.get("http_code")); - responseError.put("description", errorObject.get("message")); - finalResponseError.put("error", responseError); - } - } catch (ParseException e) { - JSONObject responseError = new JSONObject(); - responseError.put("code", skyflowException.getCode()); - responseError.put("description", skyflowException.getMessage()); - finalResponseError.put("error", responseError); - - } - return finalResponseError; - } - - public static StringBuilder constructGetByIdRequestURLParams(GetByIdRecordInput record) { - StringBuilder paramsList = new StringBuilder(); - - for (String id : record.getIds()) { - paramsList.append("skyflow_ids=").append(id).append("&"); - } - - paramsList.append("redaction=").append(record.getRedaction()); - return paramsList; - } - - public static StringBuilder constructGetRequestURLParams(GetRecordInput record, GetOptions getOptions) { - StringBuilder paramsList = new StringBuilder(); - - if (record.getIds() != null) { - for (String id : record.getIds()) { - paramsList.append("skyflow_ids=").append(id).append("&"); - } - } - - if (record.getColumnName() != null && record.getColumnValues() != null) { - paramsList.append("column_name=").append(record.getColumnName()).append("&"); - for (String value : record.getColumnValues()) { - paramsList.append("column_values=").append(value).append("&"); - } - } - if(record.getRedaction() == null && getOptions.getOptionToken() == true){ - paramsList.append("tokenization=").append(getOptions.getOptionToken()); - } else { - paramsList.append("redaction=").append(record.getRedaction()); - } - return paramsList; - } - - public static JSONObject constructInsertResponse(JSONObject response, List requestRecords, InsertOptions options) { - JSONArray responses = (JSONArray) response.get("responses"); - JSONArray successResponses = new JSONArray(); - JSONArray failureResponses = new JSONArray(); - JSONObject insertResponse = new JSONObject(); - - boolean tokens = options.isTokens(); - boolean continueOnError = options.isContinueOnError(); - - if (continueOnError) { - for (int index = 0; index < responses.size(); index++) { - JSONObject body = (JSONObject) ((JSONObject) responses.get(index)).get("Body"); - Long status = (Long) ((JSONObject) responses.get(index)).get("Status"); - if (body.containsKey("records")) { - JSONObject record = ((JSONObject) ((JSONArray) body.get("records")).get(0)); - String skyflowID = (String) record.get("skyflow_id"); - JSONObject responseTokens = (JSONObject) record.get("tokens"); - String table = (String) ((JSONObject) requestRecords.get(index)).get("tableName"); - JSONObject successObj = new JSONObject(); - successObj.put("table", table); - successObj.put("request_index", index); - if (tokens) { - responseTokens.remove("*"); - responseTokens.put("skyflow_id", skyflowID); - successObj.put("fields", responseTokens); - } else { - successObj.put("skyflow_id", skyflowID); - } - successResponses.add(successObj); - } else { - JSONObject failureObj = new JSONObject(); - JSONObject errorObj = new JSONObject(); - errorObj.put("code", status); - errorObj.put("description", appendRequestId((String) body.get("error"), HttpUtility.getRequestID())); - errorObj.put("request_index", index); - failureObj.put("error", errorObj); - failureResponses.add(failureObj); - } - } - } else if (tokens) { - for (int index = 0; index < responses.size(); index++) { - String skyflowId = (String) ((JSONObject) ((JSONArray) ((JSONObject) responses.get(index)) - .get("records")).get(0)).get("skyflow_id"); - JSONObject newObj = new JSONObject(); - newObj.put("table", ((JSONObject) requestRecords.get(index)).get("tableName")); - JSONObject newFields = (JSONObject) ((JSONObject) ((JSONArray) ((JSONObject) responses.get(index)) - .get("records")).get(0)).get("tokens"); - newFields.remove("*"); - newFields.put("skyflow_id", skyflowId); - newObj.put("fields", newFields); - newObj.put("request_index", index); - successResponses.add(newObj); - } - } else { - for (int index = 0; index < responses.size(); index++) { - JSONObject newObj = new JSONObject(); - - newObj.put("table", ((JSONObject) requestRecords.get(index)).get("tableName")); - newObj.put("skyflow_id", - ((JSONObject) ((JSONArray) ((JSONObject) responses.get(index)).get("records")).get(0)) - .get("skyflow_id")); - newObj.put("request_index", index); - successResponses.add(newObj); - } - } - if (successResponses.size() > 0) { - insertResponse.put("records", successResponses); - } - if (failureResponses.size() > 0) { - insertResponse.put("errors", failureResponses); - } - return insertResponse; - } - - public static String parameterizedString(String base, String... args) { - for (int index = 0; index < args.length; index++) { - base = base.replace("%s" + (index + 1), args[index]); - } - return base; - } - - public static String constructConnectionURL(JSONObject config) { - StringBuilder filledURL = new StringBuilder((String) config.get("connectionURL")); - - if (config.containsKey("pathParams")) { - JSONObject pathParams = (JSONObject) config.get("pathParams"); - for (Object key : pathParams.keySet()) { - Object value = pathParams.get(key); - filledURL = new StringBuilder(filledURL.toString().replace(String.format("{%s}", key), (String) value)); - } - } - - if (config.containsKey("queryParams")) { - JSONObject queryParams = (JSONObject) config.get("queryParams"); - filledURL.append("?"); - for (Object key : queryParams.keySet()) { - Object value = queryParams.get(key); - filledURL.append(key).append("=").append(value).append("&"); - } - filledURL = new StringBuilder(filledURL.substring(0, filledURL.length() - 1)); - - } - return filledURL.toString(); - } - - public static Map constructConnectionHeadersMap(JSONObject configHeaders) { - Map headersMap = new HashMap<>(); - for (Object key : configHeaders.keySet()) { - Object value = configHeaders.get(key); - headersMap.put(((String) key).toLowerCase(), (String) value); - } - return headersMap; - } - - public static String appendRequestId(String message, String requestId) { - if (requestId != null && !requestId.isEmpty()) { - message = message + " - requestId: " + requestId; - } - return message; - } - - public static String appendRequestIdToErrorObj(int status, String error, String requestId) throws SkyflowException { - try { - if (requestId != null && !requestId.isEmpty()) { - JSONObject errorObject = (JSONObject) new JSONParser().parse(error); - JSONObject tempError = (JSONObject) errorObject.get("error"); - if (tempError != null) { - String message = (String) tempError.get("message"); - message = message + " - requestId: " + requestId; - - tempError.put("message", message); - errorObject.put("error", tempError); - } - error = errorObject.toString(); - } - } catch (ParseException e) { - throw new SkyflowException(status, error); - } - return error; - } - - public static String formatJsonToFormEncodedString(JSONObject requestBody) { - LogUtil.printDebugLog(DebugLogs.FormatRequestBodyFormUrlFormEncoded.getLog()); - StringBuilder formEncodeString = new StringBuilder(); - HashMap jsonMap = convertJsonToMap(requestBody, ""); - - for (Map.Entry currentEntry : jsonMap.entrySet()) - formEncodeString.append(makeFormEncodeKeyValuePair(currentEntry.getKey(), currentEntry.getValue())); - - return formEncodeString.substring(0, formEncodeString.length() - 1); - } - - public static String formatJsonToMultiPartFormDataString(JSONObject requestBody, String boundary) { - LogUtil.printDebugLog(DebugLogs.FormatRequestBodyFormData.getLog()); - StringBuilder formEncodeString = new StringBuilder(); - HashMap jsonMap = convertJsonToMap(requestBody, ""); - - for (Map.Entry currentEntry : jsonMap.entrySet()) - formEncodeString.append(makeFormDataKeyValuePair(currentEntry.getKey(), currentEntry.getValue(), boundary)); - - formEncodeString.append(LINE_FEED); - formEncodeString.append("--").append(boundary).append("--").append(LINE_FEED); - - return formEncodeString.toString(); - } - - private static HashMap convertJsonToMap(JSONObject json, String rootKey) { - HashMap currentMap = new HashMap<>(); - for (Object key : json.keySet()) { - Object currentValue = json.get(key); - String currentKey = rootKey.length() != 0 ? rootKey + '[' + key.toString() + ']' : rootKey + key.toString(); - if (currentValue instanceof JSONObject) { - currentMap.putAll(convertJsonToMap((JSONObject) currentValue, currentKey)); - } else { - currentMap.put(currentKey, currentValue.toString()); - } - } - return currentMap; - } - - private static String makeFormEncodeKeyValuePair(String key, String value) { - return key + "=" + value + "&"; - } - - private static String makeFormDataKeyValuePair(String key, String value, String boundary) { - StringBuilder formDataTextField = new StringBuilder(); - formDataTextField.append("--").append(boundary).append(LINE_FEED); - formDataTextField.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_FEED); - formDataTextField.append(LINE_FEED); - formDataTextField.append(value).append(LINE_FEED); - - return formDataTextField.toString(); - } - - public static PrivateKey getPrivateKeyFromPem(String pemKey) throws SkyflowException { - - String PKCS8PrivateHeader = "-----BEGIN PRIVATE KEY-----"; - String PKCS8PrivateFooter = "-----END PRIVATE KEY-----"; - - String privateKeyContent = pemKey; - PrivateKey privateKey = null; - - if (pemKey.contains(PKCS8PrivateHeader)) { - privateKeyContent = privateKeyContent.replace(PKCS8PrivateHeader, ""); - privateKeyContent = privateKeyContent.replace(PKCS8PrivateFooter, ""); - privateKeyContent = privateKeyContent.replace("\n", ""); - privateKeyContent = privateKeyContent.replace("\r\n", ""); - privateKey = parsePkcs8PrivateKey(Base64.decodeBase64(privateKeyContent)); - } else { - LogUtil.printErrorLog(ErrorLogs.UnableToRetrieveRSA.getLog()); - throw new SkyflowException(ErrorCode.UnableToRetrieveRSA); - } - return privateKey; - } - - /** - * Create a PrivateKey instance from raw PKCS#8 bytes. - */ - public static PrivateKey parsePkcs8PrivateKey(byte[] pkcs8Bytes) throws SkyflowException { - KeyFactory keyFactory; - PrivateKey privateKey = null; - try { - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8Bytes); - keyFactory = KeyFactory.getInstance("RSA"); - privateKey = keyFactory.generatePrivate(keySpec); - } catch (NoSuchAlgorithmException e) { - LogUtil.printErrorLog(ErrorLogs.NoSuchAlgorithm.getLog()); - throw new SkyflowException(ErrorCode.NoSuchAlgorithm, e); - } catch (InvalidKeySpecException e) { - LogUtil.printErrorLog(ErrorLogs.InvalidKeySpec.getLog()); - throw new SkyflowException(ErrorCode.InvalidKeySpec, e); - } - return privateKey; - } - public static JSONObject getMetrics(){ - JSONObject details = new JSONObject(); - - String sdkVersion = Constants.SDK_VERSION; - String deviceModel = ""; - String osDetails = ""; - String javaVersion = ""; - - details.put("sdk_name_version", "skyflow-java@" + sdkVersion); - - // Retrieve device model - try { - deviceModel = System.getProperty("os.name"); - } catch (Exception e) { - deviceModel = ""; - } - details.put("sdk_client_device_model", deviceModel); - - // Retrieve OS details - try { - osDetails = System.getProperty("os.version"); - } catch (Exception e) { - osDetails = ""; - } - details.put("sdk_client_os_details", osDetails); - - // Retrieve Java version details - try { - javaVersion = System.getProperty("java.version"); - } catch (Exception e) { - javaVersion = ""; - } - details.put("sdk_runtime_details", "Java@" + javaVersion); - - return details; - } -} diff --git a/v1/src/main/java/com/skyflow/common/utils/HttpUtility.java b/v1/src/main/java/com/skyflow/common/utils/HttpUtility.java deleted file mode 100644 index 60cf9aac..00000000 --- a/v1/src/main/java/com/skyflow/common/utils/HttpUtility.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.common.utils; - -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import org.json.simple.JSONObject; - -import java.io.*; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Map; - -import static com.skyflow.common.utils.Helpers.formatJsonToFormEncodedString; -import static com.skyflow.common.utils.Helpers.formatJsonToMultiPartFormDataString; - -public final class HttpUtility { - private static String requestID; - - public static String getRequestID() { - return requestID; - } - - public static String sendRequest(String method, URL url, JSONObject params, Map headers) throws IOException, SkyflowException { - HttpURLConnection connection = null; - BufferedReader in = null; - StringBuffer response = null; - String boundary = String.valueOf(System.currentTimeMillis()); - try { - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod(method); - connection.setRequestProperty("content-type", "application/json"); - connection.setRequestProperty("Accept", "*/*"); - - if (headers != null && headers.size() > 0) { - for (Map.Entry entry : headers.entrySet()) - connection.setRequestProperty(entry.getKey(), entry.getValue()); - - // append dynamic boundary if content-type is multipart/form-data - if (headers.containsKey("content-type")) { - if (headers.get("content-type") == "multipart/form-data") { - connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary); - } - } - } - if (params != null && params.size() > 0) { - connection.setDoOutput(true); - try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { - byte[] input = null; - String requestContentType = connection.getRequestProperty("content-type"); - - if (requestContentType.contains("application/x-www-form-urlencoded")) { - input = formatJsonToFormEncodedString(params).getBytes(StandardCharsets.UTF_8); - } else if (requestContentType.contains("multipart/form-data")) { - input = formatJsonToMultiPartFormDataString(params, boundary).getBytes(StandardCharsets.UTF_8); - }else { - input = params.toString().getBytes(StandardCharsets.UTF_8); - } - - wr.write(input, 0, input.length); - wr.flush(); - } - } - - int status = connection.getResponseCode(); - String requestID = connection.getHeaderField("x-request-id"); - HttpUtility.requestID = requestID; - - Reader streamReader; - if (status > 299) { - if (connection.getErrorStream() != null) - streamReader = new InputStreamReader(connection.getErrorStream()); - else { - String description = Helpers.appendRequestId(ErrorCode.Server.getDescription(), requestID); - LogUtil.printErrorLog(description); - throw new SkyflowException(status, description); - } - } else { - streamReader = new InputStreamReader(connection.getInputStream()); - } - - response = new StringBuffer(); - in = new BufferedReader(streamReader); - String inputLine; - while ((inputLine = in.readLine()) != null) { - response.append(inputLine); - } - - if (status > 299) { - LogUtil.printErrorLog(Helpers.appendRequestId(response.toString(), requestID)); - String errorMsg = Helpers.appendRequestIdToErrorObj(status, response.toString(), requestID); - throw new SkyflowException(status, errorMsg); - } - } finally { - if (in != null) { - in.close(); - } - if (connection != null) { - connection.disconnect(); - } - } - return response.toString(); - } - -} diff --git a/v1/src/main/java/com/skyflow/common/utils/LogUtil.java b/v1/src/main/java/com/skyflow/common/utils/LogUtil.java deleted file mode 100644 index fa48cdb3..00000000 --- a/v1/src/main/java/com/skyflow/common/utils/LogUtil.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.common.utils; - -import com.skyflow.entities.LogLevel; -import com.skyflow.logs.InfoLogs; - -import java.util.logging.*; - -public final class LogUtil { - private static final Logger LOGGER = Logger.getLogger(LogUtil.class.getName()); - private static final String SDK_OWNER = "[Skyflow] "; - private static boolean IS_LOGGER_SETUP_DONE = false; - - - synchronized public static void setupLogger(LogLevel logLevel) { - IS_LOGGER_SETUP_DONE = true; - LogManager.getLogManager().reset(); - LOGGER.setUseParentHandlers(false); - Formatter formatter = new SimpleFormatter() { - private static final String format = "%s: %s %n"; - - // Override format method - @Override - public synchronized String format(LogRecord logRecord) { - return String.format(format, loggerLevelToLogLevelMap(logRecord.getLevel()), - logRecord.getMessage()); - } - }; - ConsoleHandler consoleHandler = new ConsoleHandler(); - consoleHandler.setFormatter(formatter); - consoleHandler.setLevel(Level.CONFIG); - - LOGGER.addHandler(consoleHandler); - LOGGER.setLevel(logLevelToLoggerLevelMap(logLevel)); - printInfoLog(InfoLogs.LoggerSetup.getLog()); - } - - public static void printErrorLog(String message) { - if (IS_LOGGER_SETUP_DONE) - LOGGER.severe(SDK_OWNER + message); - else { - setupLogger(LogLevel.ERROR); - LOGGER.severe(SDK_OWNER + message); - } - } - - public static void printDebugLog(String message) { - if (IS_LOGGER_SETUP_DONE) - LOGGER.config(SDK_OWNER + message); - } - - public static void printWarningLog(String message) { - if (IS_LOGGER_SETUP_DONE) - LOGGER.warning(SDK_OWNER + message); - } - - public static void printInfoLog(String message) { - if (IS_LOGGER_SETUP_DONE) - LOGGER.info(SDK_OWNER + message); - } - - - private static Level logLevelToLoggerLevelMap(LogLevel logLevel) { - Level loggerLevel; - switch (logLevel) { - case ERROR: - loggerLevel = Level.SEVERE; - break; - case WARN: - loggerLevel = Level.WARNING; - break; - case INFO: - loggerLevel = Level.INFO; - break; - case DEBUG: - loggerLevel = Level.CONFIG; - break; - default: - loggerLevel = Level.OFF; - } - return loggerLevel; - } - - private static LogLevel loggerLevelToLogLevelMap(Level loggerLevel) { - LogLevel logLevel; - if (Level.SEVERE.equals(loggerLevel)) { - logLevel = LogLevel.ERROR; - } else if (Level.WARNING.equals(loggerLevel)) { - logLevel = LogLevel.WARN; - } else if (Level.INFO.equals(loggerLevel)) { - logLevel = LogLevel.INFO; - } else if (Level.CONFIG.equals(loggerLevel)){ - logLevel = LogLevel.DEBUG; - }else - logLevel = LogLevel.OFF; - return logLevel; - } - - -} diff --git a/v1/src/main/java/com/skyflow/common/utils/TokenUtils.java b/v1/src/main/java/com/skyflow/common/utils/TokenUtils.java deleted file mode 100644 index 288f2faa..00000000 --- a/v1/src/main/java/com/skyflow/common/utils/TokenUtils.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.common.utils; - -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.logs.ErrorLogs; -import com.skyflow.logs.InfoLogs; -import org.apache.commons.codec.binary.Base64; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.nio.charset.StandardCharsets; -import java.util.Date; - -public final class TokenUtils { - - private String token; - - public TokenUtils() { - LogUtil.printInfoLog(InfoLogs.TokenUtilsInstanceCreated.getLog()); - this.token = null; - } - - public static boolean isTokenValid(String token) throws SkyflowException { - try { - if (token != null) { - return !isExpired(token); - } - } catch (ParseException e) { - LogUtil.printErrorLog(ErrorLogs.InvalidBearerToken.getLog()); - throw new SkyflowException(ErrorCode.InvalidBearerToken, e); - } - - return false; - } - - private static boolean isExpired(String encodedToken) throws ParseException, SkyflowException { - long currentTime = new Date().getTime() / 1000; - long expiryTime = (long) decoded(encodedToken).get("exp"); - return currentTime > expiryTime; - } - - public static JSONObject decoded(String encodedToken) throws ParseException, SkyflowException { - String[] split = encodedToken.split("\\."); - if (split.length < 3) { - throw new SkyflowException(ErrorCode.InvalidBearerToken); - } - byte[] decodedBytes = Base64.decodeBase64(split[1]); - return (JSONObject) new JSONParser().parse(new String(decodedBytes, StandardCharsets.UTF_8)); - } - - public String getBearerToken(TokenProvider tokenProvider) throws SkyflowException { - if (token != null && isTokenValid(token)) - return token; - - try { - token = tokenProvider.getBearerToken(); - if(!isTokenValid(token)){ - LogUtil.printErrorLog(ErrorLogs.BearerTokenExpired.getLog()); - throw new SkyflowException(ErrorCode.BearerTokenExpired); - } - } catch (SkyflowException exception) { - throw exception; - } catch (Exception e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.BearerThrownException.getLog(), e.getMessage())); - throw new SkyflowException(ErrorCode.BearerThrownException.getCode(), e.getMessage(), e); - } - return token; - } -} diff --git a/v1/src/main/java/com/skyflow/common/utils/Validators.java b/v1/src/main/java/com/skyflow/common/utils/Validators.java deleted file mode 100644 index c1eda9e1..00000000 --- a/v1/src/main/java/com/skyflow/common/utils/Validators.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.common.utils; - -import com.skyflow.entities.*; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.logs.ErrorLogs; -import com.skyflow.logs.InfoLogs; -import org.json.simple.JSONObject; - -import java.net.URL; -import java.util.Objects; - -public final class Validators { - public static void validateConfiguration(SkyflowConfiguration config) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.ValidatingSkyflowConfiguration.getLog()); - if (config.getVaultID() == null || config.getVaultID().length() <= 0) { - LogUtil.printErrorLog(ErrorLogs.InvalidVaultId.getLog()); - throw new SkyflowException(ErrorCode.EmptyVaultID); - } - - if (config.getVaultURL() == null || isInvalidURL(config.getVaultURL())) { - LogUtil.printErrorLog(ErrorLogs.InvalidVaultURL.getLog()); - throw new SkyflowException(ErrorCode.InvalidVaultURL); - } - - if (config.getTokenProvider() == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidTokenProvider.getLog()); - throw new SkyflowException(ErrorCode.InvalidTokenProvider); - } - - } - - public static void validateConnectionConfiguration(JSONObject connectionConfig, SkyflowConfiguration skyflowConfiguration) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.ValidatingInvokeConnectionConfig.getLog()); - if (skyflowConfiguration.getTokenProvider() == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidTokenProvider.getLog()); - throw new SkyflowException(ErrorCode.InvalidTokenProvider); - } - - if (connectionConfig.containsKey("connectionURL")) { - String connectionURL = (String) connectionConfig.get("connectionURL"); - if (isInvalidURL(connectionURL)) { - LogUtil.printErrorLog(ErrorLogs.InvalidConnectionURL.getLog()); - throw new SkyflowException(ErrorCode.InvalidConnectionURL); - } - } else { - LogUtil.printErrorLog(ErrorLogs.ConnectionURLMissing.getLog()); - throw new SkyflowException(ErrorCode.ConnectionURLMissing); - } - - if (connectionConfig.containsKey("methodName")) { - try { - RequestMethod requestMethod = (RequestMethod) connectionConfig.get("methodName"); - } catch (Exception e) { - LogUtil.printErrorLog(ErrorLogs.InvalidMethodName.getLog()); - throw new SkyflowException(ErrorCode.InvalidMethodName); - } - } else { - LogUtil.printErrorLog(ErrorLogs.MethodNameMissing.getLog()); - throw new SkyflowException(ErrorCode.MethodNameMissing); - } - } - - public static void validateUpsertOptions(UpsertOption[] upsertOptions) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.ValidatingUpsertOptions.getLog()); - if (upsertOptions.length == 0) { - LogUtil.printErrorLog(ErrorLogs.InvalidUpsertOptionType.getLog()); - throw new SkyflowException(ErrorCode.InvalidUpsertOptionType); - } - - for (UpsertOption upsertOption : upsertOptions) { - if (upsertOption == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidUpsertObjectType.getLog()); - throw new SkyflowException(ErrorCode.InvalidUpsertObjectType); - } - - if (upsertOption.getTable() == null || Objects.equals(upsertOption.getTable(), "")) { - LogUtil.printErrorLog(ErrorLogs.InvalidTableInUpsertOption.getLog()); - throw new SkyflowException(ErrorCode.InvalidTableInUpsertOption); - } - if (upsertOption.getColumn() == null || Objects.equals(upsertOption.getColumn(), "")) { - LogUtil.printErrorLog(ErrorLogs.InvalidColumnInUpsertOption.getLog()); - throw new SkyflowException(ErrorCode.InvalidColumnInUpsertOption); - } - } - - } - - private static boolean isInvalidURL(String configURL) { - try { - URL url = new URL(configURL); - if (!url.getProtocol().equals("https")) throw new Exception(); - } catch (Exception e) { - return true; - } - return false; - } - - public static void validateGetByIdRequestRecord(GetByIdRecordInput record) throws SkyflowException { - String table = record.getTable(); - - if (table == null || table.trim().isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.InvalidTable.getLog()); - throw new SkyflowException(ErrorCode.InvalidTable); - } - } - - public static void validateGetRequestRecord(GetRecordInput record, GetOptions getOptions) throws SkyflowException { - String[] ids = record.getIds(); - String table = record.getTable(); - String columnName = record.getColumnName(); - String[] columnValues = record.getColumnValues(); - RedactionType redaction = record.getRedaction(); - - if (table == null || table.trim().isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.InvalidTable.getLog()); - throw new SkyflowException(ErrorCode.InvalidTable); - } - if (getOptions.getOptionToken() == false && redaction == null) { - LogUtil.printErrorLog((ErrorLogs.MissingRedaction.getLog())); - throw new SkyflowException(ErrorCode.MissingRedaction); - } - - if (ids == null && columnName == null && columnValues == null) { - LogUtil.printErrorLog(ErrorLogs.MissingIdAndColumnName.getLog()); - throw new SkyflowException(ErrorCode.MissingIdAndColumnName); - } - if( ids != null && columnName != null) { - LogUtil.printErrorLog(ErrorLogs.SkyflowIdAndColumnNameBothSpecified.getLog()); - throw new SkyflowException(ErrorCode.SkyflowIdAndColumnNameBothSpecified); - } - - if (columnName != null && columnValues == null) { - LogUtil.printErrorLog(ErrorLogs.MissingRecordColumnValue.getLog()); - throw new SkyflowException(ErrorCode.MissingRecordColumnValue); - } - if (columnName == null && columnValues != null) { - LogUtil.printErrorLog(ErrorLogs.MissingRecordColumnName.getLog()); - throw new SkyflowException(ErrorCode.MissingRecordColumnName); - } - if (getOptions.getOptionToken() == true) { - if (columnName != null || columnValues != null) { - LogUtil.printErrorLog(ErrorLogs.TokensGetColumnNotSupported.getLog()); - throw new SkyflowException(ErrorCode.TokensGetColumnNotSupported); - } - if (redaction != null) { - LogUtil.printErrorLog(ErrorLogs.RedactionWithTokenNotSupported.getLog()); - throw new SkyflowException(ErrorCode.RedactionWithTokenNotSupported); - } - } - } - public static void validateDeleteBySkyflowId(DeleteRecordInput deleteRecordInput) throws SkyflowException{ - String table = deleteRecordInput.getTable(); - String id = deleteRecordInput.getId(); - if (table == null || table.trim().isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.InvalidTable.getLog()); - throw new SkyflowException(ErrorCode.InvalidTable); - } - if (id == null || id.trim().isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.InvalidId.getLog()); - throw new SkyflowException(ErrorCode.InvalidId); - } - - } - public static void validateInsertRecord(InsertRecordInput record) throws SkyflowException { - if (record.getTable() == null || record.getTable().isEmpty()) { - throw new SkyflowException(ErrorCode.InvalidTable); - } - if (record.getFields() == null) { - throw new SkyflowException(ErrorCode.InvalidFields); - } - } -} diff --git a/v1/src/main/java/com/skyflow/entities/DeleteInput.java b/v1/src/main/java/com/skyflow/entities/DeleteInput.java deleted file mode 100644 index 422d929d..00000000 --- a/v1/src/main/java/com/skyflow/entities/DeleteInput.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.skyflow.entities; - -public class DeleteInput { - private DeleteRecordInput[] records; - - public DeleteRecordInput[] getRecords() { - return records; - } - - public void setRecords(DeleteRecordInput[] records) { - this.records = records; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/DeleteOptions.java b/v1/src/main/java/com/skyflow/entities/DeleteOptions.java deleted file mode 100644 index affa26c6..00000000 --- a/v1/src/main/java/com/skyflow/entities/DeleteOptions.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.skyflow.entities; - -public class DeleteOptions { - public DeleteOptions(){} -} diff --git a/v1/src/main/java/com/skyflow/entities/DeleteRecordInput.java b/v1/src/main/java/com/skyflow/entities/DeleteRecordInput.java deleted file mode 100644 index 6e11b2a4..00000000 --- a/v1/src/main/java/com/skyflow/entities/DeleteRecordInput.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.skyflow.entities; - -public class DeleteRecordInput { - private String id; - private String table; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getTable() { - return table; - } - - public void setTable(String table) { - this.table = table; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/DetokenizeInput.java b/v1/src/main/java/com/skyflow/entities/DetokenizeInput.java deleted file mode 100644 index b8d8f908..00000000 --- a/v1/src/main/java/com/skyflow/entities/DetokenizeInput.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public class DetokenizeInput { - private DetokenizeRecord[] records; - - public DetokenizeRecord[] getRecords() { - return records; - } - - public void setRecords(DetokenizeRecord[] records) { - this.records = records; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/DetokenizeRecord.java b/v1/src/main/java/com/skyflow/entities/DetokenizeRecord.java deleted file mode 100644 index 4bd9ee40..00000000 --- a/v1/src/main/java/com/skyflow/entities/DetokenizeRecord.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public class DetokenizeRecord { - private String token; - private RedactionType redaction = RedactionType.PLAIN_TEXT; - - public String getToken() { - return token; - } - - void setToken(String token) { - this.token = token; - } - - public RedactionType getRedaction() { - return redaction; - } - - public void setRedaction(RedactionType redaction) { - this.redaction = redaction; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/GetByIdInput.java b/v1/src/main/java/com/skyflow/entities/GetByIdInput.java deleted file mode 100644 index a31f4b49..00000000 --- a/v1/src/main/java/com/skyflow/entities/GetByIdInput.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public class GetByIdInput { - private GetByIdRecordInput[] records; - - public GetByIdRecordInput[] getRecords() { - return records; - } - - public void setRecords(GetByIdRecordInput[] records) { - this.records = records; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/GetByIdRecordInput.java b/v1/src/main/java/com/skyflow/entities/GetByIdRecordInput.java deleted file mode 100644 index e858bb24..00000000 --- a/v1/src/main/java/com/skyflow/entities/GetByIdRecordInput.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public class GetByIdRecordInput { - private String[] ids; - private String table; - private RedactionType redaction; - - public String[] getIds() { - return ids; - } - - public void setIds(String[] ids) { - this.ids = ids; - } - - public String getTable() { - return table; - } - - public void setTable(String table) { - this.table = table; - } - - public RedactionType getRedaction() { - return redaction; - } - - public void setRedaction(RedactionType redaction) { - this.redaction = redaction; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/GetInput.java b/v1/src/main/java/com/skyflow/entities/GetInput.java deleted file mode 100644 index 786be682..00000000 --- a/v1/src/main/java/com/skyflow/entities/GetInput.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public class GetInput { - private GetRecordInput[] records; - - public GetRecordInput[] getRecords() { - return records; - } - - public void setRecords(GetRecordInput[] records) { - this.records = records; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/GetOptions.java b/v1/src/main/java/com/skyflow/entities/GetOptions.java deleted file mode 100644 index 7620b761..00000000 --- a/v1/src/main/java/com/skyflow/entities/GetOptions.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.skyflow.entities; - -public class GetOptions { - private boolean tokens; - - public GetOptions(){ - this.tokens = false; - } - public GetOptions(boolean tokens){ - this.tokens = tokens; - } - - public boolean getOptionToken(){ - return tokens; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/GetRecordInput.java b/v1/src/main/java/com/skyflow/entities/GetRecordInput.java deleted file mode 100644 index 169c0c18..00000000 --- a/v1/src/main/java/com/skyflow/entities/GetRecordInput.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public class GetRecordInput { - private String[] ids; - private String table; - private String columnName; - private String[] columnValues; - private RedactionType redaction; - - public String[] getIds() { - return ids; - } - - public void setIds(String[] ids) { - this.ids = ids; - } - - public String getTable() { - return table; - } - - public void setTable(String table) { - this.table = table; - } - - public String getColumnName() { - return columnName; - } - - public void setColumnName(String columnName) { - this.columnName = columnName; - } - - public String[] getColumnValues() { - return columnValues; - } - - public void setColumnValues(String[] columnValues) { - this.columnValues = columnValues; - } - - public RedactionType getRedaction() { - return redaction; - } - - public void setRedaction(RedactionType redaction) { - this.redaction = redaction; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/InsertBulkOptions.java b/v1/src/main/java/com/skyflow/entities/InsertBulkOptions.java deleted file mode 100644 index b7c03963..00000000 --- a/v1/src/main/java/com/skyflow/entities/InsertBulkOptions.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.skyflow.entities; - -public class InsertBulkOptions { - - private boolean tokens; - private UpsertOption[] upsertOptions; - - public InsertBulkOptions() { - this.tokens = true; - this.upsertOptions = null; - } - - public InsertBulkOptions(boolean tokens) { - this.tokens = tokens; - this.upsertOptions = null; - } - - public InsertBulkOptions(UpsertOption[] upsertOptions) { - this.tokens = true; - this.upsertOptions = upsertOptions; - } - - public InsertBulkOptions(boolean tokens, UpsertOption[] upsertOptions) { - this.tokens = tokens; - this.upsertOptions = upsertOptions; - } - - public boolean isTokens() { - return tokens; - } - - public UpsertOption[] getUpsertOptions() { - return upsertOptions; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/InsertInput.java b/v1/src/main/java/com/skyflow/entities/InsertInput.java deleted file mode 100644 index 0163aace..00000000 --- a/v1/src/main/java/com/skyflow/entities/InsertInput.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public class InsertInput { - - private InsertRecordInput[] records; - - public InsertRecordInput[] getRecords() { - return records; - } - - public void setRecords(InsertRecordInput[] records) { - this.records = records; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/InsertOptions.java b/v1/src/main/java/com/skyflow/entities/InsertOptions.java deleted file mode 100644 index 16739892..00000000 --- a/v1/src/main/java/com/skyflow/entities/InsertOptions.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public class InsertOptions { - - private boolean tokens; - private UpsertOption[] upsertOptions; - private boolean continueOnError; - - public InsertOptions() { - this.tokens = true; - this.upsertOptions = null; - this.continueOnError = false; - } - - public InsertOptions(boolean tokens) { - this.tokens = tokens; - this.upsertOptions = null; - } - - public InsertOptions(UpsertOption[] upsertOptions) { - this.tokens = true; - this.upsertOptions = upsertOptions; - } - - public InsertOptions(boolean tokens, UpsertOption[] upsertOptions) { - this.tokens = tokens; - this.upsertOptions = upsertOptions; - } - - public InsertOptions(boolean tokens, boolean continueOnError) { - this.tokens = tokens; - this.continueOnError = continueOnError; - } - - public InsertOptions(UpsertOption[] upsertOptions, boolean continueOnError) { - this.upsertOptions = upsertOptions; - this.continueOnError = continueOnError; - } - - public InsertOptions(boolean tokens, UpsertOption[] upsertOptions, boolean continueOnError) { - this.tokens = tokens; - this.upsertOptions = upsertOptions; - this.continueOnError = continueOnError; - } - - public boolean isTokens() { - return tokens; - } - - public UpsertOption[] getUpsertOptions() { - return upsertOptions; - } - - public boolean isContinueOnError() { - return continueOnError; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/InsertRecordInput.java b/v1/src/main/java/com/skyflow/entities/InsertRecordInput.java deleted file mode 100644 index 6572b5c0..00000000 --- a/v1/src/main/java/com/skyflow/entities/InsertRecordInput.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -import org.json.simple.JSONObject; - -public class InsertRecordInput { - private String table; - private JSONObject fields; - - public String getTable() { - return table; - } - - public void setTable(String table) { - this.table = table; - } - - public JSONObject getFields() { - return fields; - } - - public void setFields(JSONObject fields) { - this.fields = fields; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/LogLevel.java b/v1/src/main/java/com/skyflow/entities/LogLevel.java deleted file mode 100644 index 3bed5284..00000000 --- a/v1/src/main/java/com/skyflow/entities/LogLevel.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public enum LogLevel { - DEBUG, - INFO, - WARN, - ERROR, - OFF -} diff --git a/v1/src/main/java/com/skyflow/entities/QueryInput.java b/v1/src/main/java/com/skyflow/entities/QueryInput.java deleted file mode 100644 index 7e578d41..00000000 --- a/v1/src/main/java/com/skyflow/entities/QueryInput.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.skyflow.entities; - -public class QueryInput { - private QueryRecordInput queryInput; - - public QueryRecordInput getQueryInput() { - return queryInput; - } - - public void setQueryInput(QueryRecordInput queryInput) { - this.queryInput = queryInput; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/QueryOptions.java b/v1/src/main/java/com/skyflow/entities/QueryOptions.java deleted file mode 100644 index 7cc1a3de..00000000 --- a/v1/src/main/java/com/skyflow/entities/QueryOptions.java +++ /dev/null @@ -1,8 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public class QueryOptions { - -} diff --git a/v1/src/main/java/com/skyflow/entities/QueryRecordInput.java b/v1/src/main/java/com/skyflow/entities/QueryRecordInput.java deleted file mode 100644 index 032c4fd0..00000000 --- a/v1/src/main/java/com/skyflow/entities/QueryRecordInput.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.skyflow.entities; - -public class QueryRecordInput { - private String query; - public String getQuery() { - return query; - } - public void setQuery(String query) { - this.query = query; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/RedactionType.java b/v1/src/main/java/com/skyflow/entities/RedactionType.java deleted file mode 100644 index 7bf240fc..00000000 --- a/v1/src/main/java/com/skyflow/entities/RedactionType.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public enum RedactionType { - DEFAULT("DEFAULT"), - PLAIN_TEXT("PLAIN_TEXT"), - MASKED("MASKED"), - REDACTED("REDACTED"), - ; - - private final String text; - - RedactionType(final String text) { - this.text = text; - } - - @Override - public String toString() { - return text; - } - -} diff --git a/v1/src/main/java/com/skyflow/entities/RequestMethod.java b/v1/src/main/java/com/skyflow/entities/RequestMethod.java deleted file mode 100644 index 7e2cea75..00000000 --- a/v1/src/main/java/com/skyflow/entities/RequestMethod.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public enum RequestMethod { - GET("GET"), - POST("POST"), - PUT("PUT"), - PATCH("PATCH"), - DELETE("DELETE"), - ; - - private final String requestMethod; - - - RequestMethod(String requestMethod) { - this.requestMethod = requestMethod; - } - - @Override - public String toString() { - return requestMethod; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/ResponseToken.java b/v1/src/main/java/com/skyflow/entities/ResponseToken.java deleted file mode 100644 index d1e4e978..00000000 --- a/v1/src/main/java/com/skyflow/entities/ResponseToken.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public class ResponseToken { - private String accessToken; - private String tokenType; - - public String getAccessToken() { - return accessToken; - } - - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - public String getTokenType() { - return tokenType; - } - - public void setTokenType(String tokenType) { - this.tokenType = tokenType; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/SkyflowConfiguration.java b/v1/src/main/java/com/skyflow/entities/SkyflowConfiguration.java deleted file mode 100644 index a240e8ca..00000000 --- a/v1/src/main/java/com/skyflow/entities/SkyflowConfiguration.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public final class SkyflowConfiguration { - private final String vaultID; - private final String vaultURL; - private final TokenProvider tokenProvider; - - /** - * - * @param vaultID is the Skyflow vaultID, which can be found in EditVault Details. - * @param vaultURL is the vaultURL, which can be found in EditVault Details. - * @param tokenProvider class which implements the TokenProvider interface. - */ - public SkyflowConfiguration(String vaultID, String vaultURL, TokenProvider tokenProvider) { - this.vaultID = vaultID; - this.vaultURL = formatVaultURL(vaultURL); - this.tokenProvider = tokenProvider; - } - public SkyflowConfiguration(TokenProvider tokenProvider){ - this.vaultID = ""; - this.vaultURL = ""; - this.tokenProvider = tokenProvider; - } - - - public String getVaultID() { - return vaultID; - } - - public String getVaultURL() { - return vaultURL; - } - - public TokenProvider getTokenProvider() { - return tokenProvider; - } - - private String formatVaultURL(String vaultURL){ - if(vaultURL != null && vaultURL.trim().length() > 0 && vaultURL.trim().charAt(vaultURL.trim().length() - 1) == '/') - return vaultURL.trim().substring(0,vaultURL.trim().length()-1); - return vaultURL; - } -} \ No newline at end of file diff --git a/v1/src/main/java/com/skyflow/entities/TokenProvider.java b/v1/src/main/java/com/skyflow/entities/TokenProvider.java deleted file mode 100644 index 95863a21..00000000 --- a/v1/src/main/java/com/skyflow/entities/TokenProvider.java +++ /dev/null @@ -1,10 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -import com.skyflow.errors.SkyflowException; - -public interface TokenProvider { - String getBearerToken() throws Exception; -} diff --git a/v1/src/main/java/com/skyflow/entities/UpdateInput.java b/v1/src/main/java/com/skyflow/entities/UpdateInput.java deleted file mode 100644 index 9c7319d2..00000000 --- a/v1/src/main/java/com/skyflow/entities/UpdateInput.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.skyflow.entities; - -public class UpdateInput { - private UpdateRecordInput[] records; - - public UpdateRecordInput[] getRecords() { - return records; - } - - public void setRecords(UpdateRecordInput[] records) { - this.records = records; - } -} diff --git a/v1/src/main/java/com/skyflow/entities/UpdateOptions.java b/v1/src/main/java/com/skyflow/entities/UpdateOptions.java deleted file mode 100644 index 0f3703ec..00000000 --- a/v1/src/main/java/com/skyflow/entities/UpdateOptions.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.skyflow.entities; - -public class UpdateOptions { - private boolean tokens; - - public UpdateOptions() { - this.tokens = true; - } - - public UpdateOptions(boolean tokens) { - this.tokens = tokens; - } - - public boolean isTokens() { - return tokens; - } - -} diff --git a/v1/src/main/java/com/skyflow/entities/UpdateRecordInput.java b/v1/src/main/java/com/skyflow/entities/UpdateRecordInput.java deleted file mode 100644 index b6283e80..00000000 --- a/v1/src/main/java/com/skyflow/entities/UpdateRecordInput.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.skyflow.entities; - -import org.json.simple.JSONObject; - -public class UpdateRecordInput { - private String id; - private String table; - private JSONObject fields; - - public String getTable() { - return table; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public void setTable(String table) { - this.table = table; - } - - public JSONObject getFields() { - return fields; - } - - public void setFields(JSONObject fields) { - this.fields = fields; - } - - -} diff --git a/v1/src/main/java/com/skyflow/entities/UpsertOption.java b/v1/src/main/java/com/skyflow/entities/UpsertOption.java deleted file mode 100644 index 7c50eb71..00000000 --- a/v1/src/main/java/com/skyflow/entities/UpsertOption.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; - -public class UpsertOption { - private String table; - private String column; - - public UpsertOption(String table, String column) { - this.table = table; - this.column = column; - } - - public String getTable() { - return table; - } - - public String getColumn() { - return column; - } -} diff --git a/v1/src/main/java/com/skyflow/errors/ErrorCode.java b/v1/src/main/java/com/skyflow/errors/ErrorCode.java deleted file mode 100644 index f996d828..00000000 --- a/v1/src/main/java/com/skyflow/errors/ErrorCode.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.errors; - -public enum ErrorCode { - InvalidVaultURL(400, "Invalid Vault URL"), - EmptyVaultID(400, "Empty Vault ID"), - InvalidTokenProvider(400, "Invalid TokenProvider"), - InvalidKeySpec(400, "Unable to parse RSA private key"), - NoSuchAlgorithm(400, "Invalid algorithm"), - UnableToRetrieveRSA(400, "Unable to retrieve RSA private key"), - UnableToReadResponse(400, "Unable to read response payload"), - InvalidTokenURI(400, "Unable to read tokenURI"), - InvalidKeyID(400, "Unable to read keyID"), - InvalidClientID(400, "Unable to read clientID"), - InvalidCredentialsPath(400, "Unable to open credentials - file %s1"), - InvalidJsonFormat(400, "Provided json file is in wrong format - file %s1"), - InvalidBearerToken(400, "Invalid token"), - BearerThrownException(400, "getBearer() thrown exception"), - EmptyRecords(400, "Records cannot be empty"), - InvalidTable(400, "Table name is missing"), - InvalidId(400, "Skyflow id is missing"), - InvalidFields(400, "Fields are missing"), - InvalidQueryInput(400, "Invalid query input"), - InvalidQuery(400, "Query is missing"), - InvalidSkyflowId(400, "Skyflow id are missing"), - InvalidToken(400, "Token is empty"), - InvalidDetokenizeInput(400, "Invalid Detokenize Input"), - InvalidInsertInput(400, "Invalid insert input"), - InvalidUpdateInput(400, "Invalid update input"), - InvalidDeleteInput(400, "Invalid delete input"), - InvalidGetByIdInput(400, "Invalid getById input"), - InvalidGetInput(400, "Invalid get input"), - MissingIdAndColumnName(400, "Provide either Ids or column name to get records."), - SkyflowIdAndColumnNameBothSpecified(400, "ids and columnName can not be specified together."), - MissingRecordColumnValue(400, "Column Values can not be empty when Column Name is specified."), - MissingRecordColumnName(400, "Column Name can not be empty when Column Values are specified."), - ResponseParsingError(500, "Unable to parse response"), - ThreadInterruptedException(500, "Thread was interrupted"), - ThreadExecutionException(500, "ThreadExecution exception"), - Server(500, "Internal server error"), - ServerReturnedErrors(500, "Server returned errors, check SkyflowException.getData() for more"), - ConnectionURLMissing(400, "connectionURL is required"), - InvalidConnectionURL(400, "Invalid connectionURL"), - MethodNameMissing(400, "methodName is required"), - InvalidMethodName(400, "methodName is invalid"), - InvalidConnectionInput(400, "Invalid connection Input"), - EmptyJSONString(400, "credentials string cannot be empty"), - InvalidJSONStringFormat(400, "credentials string is not a valid json string format"), - EmptyFilePath(400, "file path cannot be empty or null"), - EmptyContext(400, "ctx claim field is missing from the jwt assertion"), - IncorrectRole(400, "Requested scope cannot be granted"), - IncorrectCredentials(400, "Incorrect credentials provided"), - InvalidUpsertOptionType(400, "upsert options should be an non empty UpsertOption array."), - InvalidUpsertObjectType(400, "upsert option cannot be null, should be an UpsertOption object."), - InvalidTableInUpsertOption(400, "Invalid table in upsert object, non empty string is required."), - InvalidColumnInUpsertOption(400, "Invalid column in upsert object, non empty string is required."), - MissingRedaction(400, "Missing Redaction Property"), - TokensGetColumnNotSupported(400,"Interface: get method - column_name or column_values cannot be used with tokens in options."), - RedactionWithTokenNotSupported(400, "Interface: get method - redaction cannot be used when tokens are true in options."), - - BearerTokenExpired(400,"Bearer token is invalid or expired."); - private final int code; - private final String description; - - ErrorCode(int code, String description) { - this.code = code; - this.description = description; - } - - public int getCode() { - return code; - } - - public String getDescription() { - return description; - } -} diff --git a/v1/src/main/java/com/skyflow/errors/SkyflowException.java b/v1/src/main/java/com/skyflow/errors/SkyflowException.java deleted file mode 100644 index 129eb67d..00000000 --- a/v1/src/main/java/com/skyflow/errors/SkyflowException.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.errors; - -import org.json.simple.JSONObject; - -public final class SkyflowException extends Exception { - private int code; - private JSONObject data; - - public SkyflowException(ErrorCode errorCode) { - super(errorCode.getDescription()); - this.setCode(errorCode.getCode()); - } - - public SkyflowException(ErrorCode errorCode, Throwable cause) { - super(errorCode.getDescription(), cause); - this.setCode(errorCode.getCode()); - } - - public SkyflowException(int code, String description) { - super(description); - this.setCode(code); - } - - public SkyflowException(int code, String description, Throwable cause) { - super(description, cause); - this.setCode(code); - } - - public SkyflowException(int code, String description, JSONObject data) { - super(description); - this.setCode(code); - setData(data); - } - - public int getCode() { - return code; - } - - void setCode(int code) { - this.code = code; - } - - - public JSONObject getData() { - return data; - } - - void setData(JSONObject data) { - this.data = data; - } -} diff --git a/v1/src/main/java/com/skyflow/logs/DebugLogs.java b/v1/src/main/java/com/skyflow/logs/DebugLogs.java deleted file mode 100644 index 82e636d4..00000000 --- a/v1/src/main/java/com/skyflow/logs/DebugLogs.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.logs; - -public enum DebugLogs { - - FormatRequestBodyFormUrlFormEncoded("Formatting request body for form-urlencoded content-type"), - FormatRequestBodyFormData("Formatting request body for form-data content-type"); - private final String log; - - DebugLogs(String log) { - this.log = log; - } - - public String getLog() { - return log; - } -} \ No newline at end of file diff --git a/v1/src/main/java/com/skyflow/logs/ErrorLogs.java b/v1/src/main/java/com/skyflow/logs/ErrorLogs.java deleted file mode 100644 index 2f7c78ff..00000000 --- a/v1/src/main/java/com/skyflow/logs/ErrorLogs.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.logs; - -public enum ErrorLogs { - InvalidVaultId("empty or invalid vaultID"), - InvalidVaultURL("invalid vault url"), - InvalidTokenProvider("invalid TokenProvider. TokenProvider cannot be null"), - InvalidInsertInput("invalid insert input"), - InvalidUpdateInput("invalid update input"), - InvalidDeleteInput("invalid delete input"), - InvalidDetokenizeInput("invalid detokenize input"), - InvalidQueryInput("Invalid query input"), - ResponseParsingError("Unable to parse response in %s1 method"), - ThreadInterruptedException("Thread was interrupted in %s1 method"), - ThreadExecutionException("ThreadExecution exception in %s1 method"), - InvalidGetByIdInput("Invalid getById input"), - InvalidGetInput("Invalid get input"), - MissingIdAndColumnName("Provide either Ids or column name to get records."), - SkyflowIdAndColumnNameBothSpecified("ids and columnName can not be specified together."), - MissingRecordColumnValue("Column Values can not be empty when Column Name is specified."), - MissingRecordColumnName("Column Name can not be empty when Column Values are specified."), - InvalidInvokeConnectionInput("Invalid invokeConnection Input"), - ConnectionURLMissing("connectionURL is required"), - InvalidConnectionURL("Invalid connectionURL"), - MethodNameMissing("methodName is required"), - InvalidMethodName("methodName is invalid"), - InvalidKeySpec("Unable to parse RSA private key"), - NoSuchAlgorithm("Invalid algorithm"), - UnableToRetrieveRSA("Unable to retrieve RSA private key"), - UnableToReadResponse("Unable to read response payload"), - InvalidTokenURI("Unable to read tokenURI"), - InvalidKeyID("Unable to read keyID"), - InvalidClientID("Unable to read clientID"), - InvalidCredentialsPath("Unable to open credentials - file %s1"), - InvalidJsonFormat("Provided json file is in wrong format - file %s1"), - EmptyJSONString("credentials string cannot be empty or null"), - EmptyFilePath("file path cannot be empty or null"), - InvalidJSONStringFormat("credentials string is not a valid json string format"), - BearerThrownException("getBearer() thrown exception "), - InvalidBearerToken("Invalid Bearer token"), - InvalidTable("Table name is missing"), - InvalidId("Skyflow id is missing"), - InvalidQuery("Query is missing"), - - Server("Internal server error"), - ServerReturnedErrors("Server returned errors, check SkyflowException.getData() for more"), - InvalidUpsertOptionType("upsert options cannot be null, should be an non empty UpsertOption array."), - InvalidTableInUpsertOption("Invalid table in upsert object, non empty string is required."), - InvalidColumnInUpsertOption("Invalid column in upsert object, non empty string is required."), - InvalidUpsertObjectType("upsert option cannot be null, should be an UpsertOption object."), - InvalidSkyflowId("Skyflow Id is missing"), - InvalidField("Fields missing"), - MissingRedaction("Missing Redaction property."), - TokensGetColumnNotSupported("Interface: get method - column_name or column_values cannot be used with tokens in options."), - RedactionWithTokenNotSupported("Interface: get method - redaction cannot be used when tokens are true in options."), - InvalidToken("Invalid Token value"), - BearerTokenExpired("Bearer token is invalid or expired."); - - private final String log; - - ErrorLogs(String log) { - this.log = log; - } - - public final String getLog() { - return log; - } -} diff --git a/v1/src/main/java/com/skyflow/logs/InfoLogs.java b/v1/src/main/java/com/skyflow/logs/InfoLogs.java deleted file mode 100644 index 33728a3a..00000000 --- a/v1/src/main/java/com/skyflow/logs/InfoLogs.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.logs; - -public enum InfoLogs { - EmptyBearerToken("BearerToken is empty"), - InitializedClient("skyflow client initialized successfully"), - CurrentLogLevel("client LogLevel is %s1"), - LoggerSetup("logger has setup successfully"), - ValidatingSkyflowConfiguration("validating skyflow configuration"), - ValidatedSkyflowConfiguration("validated skyflow configuration in %s1 method"), - ValidatingInvokeConnectionConfig("validating invoke connection configuration"), - InsertMethodCalled("insert method has triggered"), - InsertBulkMethodCalled("insertBulk method has triggered"), - - UpdateMethodCalled("update method has triggered"), - deleteMethodCalled("delete method has triggered"), - ConstructInsertResponse("constructing insert response"), - ConstructUpdateResponse("constructing update response"), - DetokenizeMethodCalled("detokenize method has triggered"), - GetByIdMethodCalled("getById method has triggered"), - GetMethodCalled("get method has triggered"), - InvokeConnectionCalled("invokeConnection method has triggered"), - GenerateBearerTokenCalled("generateBearerToken method has triggered"), - QuerySupportCalled("query method has triggered"), - GenerateBearerTokenFromCredsCalled("generateBearerTokenFromCreds method has triggered"), - ValidatingUpsertOptions("validating upsert options."), - TokenUtilsInstanceCreated("token utils instance created"); - private final String log; - - InfoLogs(String log) { - this.log = log; - } - - public String getLog() { - return log; - } -} diff --git a/v1/src/main/java/com/skyflow/logs/WarnLogs.java b/v1/src/main/java/com/skyflow/logs/WarnLogs.java deleted file mode 100644 index 6a1a3d16..00000000 --- a/v1/src/main/java/com/skyflow/logs/WarnLogs.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.logs; - -public enum WarnLogs { - GetTokenDeprecated("GenerateToken method is deprecated, will be removed in future, use generateBearerToken()"), - IsValidDeprecated("isValid method is deprecated, will be removed in future, use isExpired()"); - private final String log; - - WarnLogs(String log) { - this.log = log; - } - - public String getLog() { - return log; - } -} diff --git a/v1/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java b/v1/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java deleted file mode 100644 index a40ec2c2..00000000 --- a/v1/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.serviceaccount.util; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.skyflow.common.utils.Constants; -import com.skyflow.common.utils.Helpers; -import com.skyflow.common.utils.HttpUtility; -import com.skyflow.common.utils.LogUtil; -import com.skyflow.entities.ResponseToken; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.logs.ErrorLogs; -import com.skyflow.logs.InfoLogs; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.net.URL; -import java.security.PrivateKey; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -public class BearerToken { - private final File credentialsFile; - private final String credentialsString; - private final String ctx; - - private final String[] roles; - - private final String credentialsType; - - private BearerToken(BearerTokenBuilder builder) { - this.credentialsFile = builder.credentialsFile; - this.credentialsString = builder.credentialsString; - this.ctx = builder.ctx; - this.roles = builder.roles; - this.credentialsType = builder.credentialsType; - } - - // Builder class - public static class BearerTokenBuilder { - private File credentialsFile; - private String credentialsString; - private String ctx; - private String[] roles; - - private String credentialsType; - - private void setCredentialsType(String credentialsType) { - this.credentialsType = credentialsType; - } - - public BearerTokenBuilder setCredentials(File credentialsFile) { - setCredentialsType("FILE"); - this.credentialsFile = credentialsFile; - return this; - } - - public BearerTokenBuilder setCredentials(String credentialsString) { - setCredentialsType("STRING"); - this.credentialsString = credentialsString; - return this; - } - - public BearerTokenBuilder setCtx(String ctx) { - this.ctx = ctx; - return this; - } - - public BearerTokenBuilder setRoles(String[] roles) { - this.roles = roles; - return this; - } - - public BearerToken build() { - return new BearerToken(this); - } - } - - public synchronized String getBearerToken() throws SkyflowException { - // Make API call in generateBearerToken function to get the token - ResponseToken response; - String accessToken = null; - - try { - if (this.credentialsFile != null && Objects.equals(this.credentialsType, "FILE")) { - response = generateBearerTokenFromCredentials(this.credentialsFile, this.ctx, this.roles); - accessToken = response.getAccessToken(); - - } else if (this.credentialsString != null && Objects.equals(this.credentialsType, "STRING")) { - response = generateBearerTokenFromCredentialString(this.credentialsString, this.ctx, this.roles); - accessToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - return accessToken; - } - - private static ResponseToken generateBearerTokenFromCredentials(File credentialsPath, String context, - String[] roles) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.GenerateBearerTokenFromCredsCalled.getLog()); - JSONParser parser = new JSONParser(); - ResponseToken responseToken; - try { - if (credentialsPath == null || !credentialsPath.isFile()) { - LogUtil.printErrorLog(ErrorLogs.EmptyJSONString.getLog()); - throw new SkyflowException(ErrorCode.EmptyJSONString); - } - - Object obj = parser.parse(new FileReader(String.valueOf(credentialsPath))); - JSONObject saCreds = (JSONObject) obj; - - responseToken = getBearerTokenFromCreds(saCreds, context, roles); - - } catch (ParseException e) { - LogUtil.printErrorLog(ErrorLogs.InvalidJSONStringFormat.getLog()); - throw new SkyflowException(ErrorCode.InvalidJSONStringFormat, e); - } catch (IOException e) { - throw new RuntimeException(e); - } - - return responseToken; - } - - private static ResponseToken generateBearerTokenFromCredentialString(String credentials, String context, - String[] roles) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.GenerateBearerTokenFromCredsCalled.getLog()); - JSONParser parser = new JSONParser(); - ResponseToken responseToken; - try { - if (credentials == null || credentials.isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.EmptyJSONString.getLog()); - throw new SkyflowException(ErrorCode.EmptyJSONString); - } - - Object obj = parser.parse(credentials); - JSONObject saCreds = (JSONObject) obj; - - responseToken = getBearerTokenFromCreds(saCreds, context, roles); - - } catch (ParseException e) { - LogUtil.printErrorLog(ErrorLogs.InvalidJSONStringFormat.getLog()); - throw new SkyflowException(ErrorCode.InvalidJSONStringFormat, e); - } - return responseToken; - } - - private static ResponseToken getBearerTokenFromCreds(JSONObject creds, String context, String[] roles) - throws SkyflowException { - ResponseToken responseToken; - try { - String clientID = (String) creds.get("clientID"); - if (clientID == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidClientID.getLog()); - throw new SkyflowException(ErrorCode.InvalidClientID); - } - String keyID = (String) creds.get("keyID"); - if (keyID == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidKeyID.getLog()); - throw new SkyflowException(ErrorCode.InvalidKeyID); - } - String tokenURI = (String) creds.get("tokenURI"); - if (tokenURI == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidTokenURI.getLog()); - throw new SkyflowException(ErrorCode.InvalidTokenURI); - } - - PrivateKey pvtKey = Helpers.getPrivateKeyFromPem((String) creds.get("privateKey")); - - String signedUserJWT = getSignedToken(clientID, keyID, tokenURI, pvtKey, context); - - Map headers = new HashMap<>(); - headers.put(Constants.SDK_METRICS_HEADER_KEY, Helpers.getMetrics().toJSONString()); - - JSONObject parameters = new JSONObject(); - parameters.put("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"); - parameters.put("assertion", signedUserJWT); - if (roles != null) { - String scopedRoles = getScopeUsingRoles(roles); - parameters.put("scope", scopedRoles); - } - - String response = HttpUtility.sendRequest("POST", new URL(tokenURI), parameters, headers); - - responseToken = new ObjectMapper().readValue(response, ResponseToken.class); - - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.UnableToReadResponse.getLog()); - throw new SkyflowException(ErrorCode.UnableToReadResponse, e); - } - - return responseToken; - } - - private static String getSignedToken(String clientID, String keyID, String tokenURI, PrivateKey pvtKey, - String context) { - final Date createdDate = new Date(); - final Date expirationDate = new Date(createdDate.getTime() + (3600 * 1000)); - - return Jwts.builder() - .claim("iss", clientID) - .claim("key", keyID) - .claim("aud", tokenURI) - .claim("sub", clientID) - .claim("ctx", context) - .setExpiration(expirationDate) - .signWith(SignatureAlgorithm.RS256, pvtKey) - .compact(); - } - - private static String getScopeUsingRoles(String[] roles) { - StringBuilder scope = new StringBuilder(); - if (roles != null) { - for (String role : roles) { - scope.append(" role:").append(role); - } - } - return scope.toString(); - } -} diff --git a/v1/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java b/v1/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java deleted file mode 100644 index ed05e541..00000000 --- a/v1/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.serviceaccount.util; - -public class SignedDataTokenResponse { - String dataToken; - String signedDataToken; - - public SignedDataTokenResponse(String dataToken, String signedDataToken) { - this.dataToken = dataToken; - this.signedDataToken = signedDataToken; - } - - @Override - public String toString() { - return "{" + "dataToken: " + dataToken + "," + "signedDataToken: " + signedDataToken + "}"; - - } -} diff --git a/v1/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java b/v1/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java deleted file mode 100644 index d31c5b85..00000000 --- a/v1/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.serviceaccount.util; - -import com.skyflow.common.utils.Helpers; -import com.skyflow.common.utils.LogUtil; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.logs.ErrorLogs; -import com.skyflow.logs.InfoLogs; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.security.PrivateKey; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Objects; - -public class SignedDataTokens { - private final File credentialsFile; - private final String credentialsString; - private final String ctx; - - private final String[] dataTokens; - private final Integer timeToLive; - - private final String credentialsType; - - private SignedDataTokens(SignedDataTokensBuilder builder) { - this.credentialsFile = builder.credentialsFile; - this.credentialsString = builder.credentialsString; - this.ctx = builder.ctx; - this.timeToLive = builder.timeToLive; - this.dataTokens = builder.dataTokens; - this.credentialsType = builder.credentialsType; - } - - // Builder class - public static class SignedDataTokensBuilder { - private File credentialsFile; - private String credentialsString; - private String ctx; - - private String[] dataTokens; - private Integer timeToLive; - - private String credentialsType; - - private void setCredentialsType(String credentialsType) { - this.credentialsType = credentialsType; - } - - public SignedDataTokensBuilder setCredentials(File credentialsFile) { - setCredentialsType("FILE"); - this.credentialsFile = credentialsFile; - return this; - } - - public SignedDataTokensBuilder setCredentials(String credentialsString) { - setCredentialsType("STRING"); - this.credentialsString = credentialsString; - return this; - } - - public SignedDataTokensBuilder setCtx(String ctx) { - this.ctx = ctx; - return this; - } - - public SignedDataTokensBuilder setDataTokens(String[] dataTokens) { - this.dataTokens = dataTokens; - return this; - } - - public SignedDataTokensBuilder setTimeToLive(Integer timeToLive) { - this.timeToLive = timeToLive; - return this; - } - - public SignedDataTokens build() { - return new SignedDataTokens(this); - } - } - - public synchronized List getSignedDataTokens() throws SkyflowException { - List signedToken = new ArrayList<>(); - - try { - if (this.credentialsFile != null && Objects.equals(this.credentialsType, "FILE")) { - signedToken = generateSignedTokens(this.credentialsFile, this.dataTokens, this.timeToLive, - this.ctx); - } else if (this.credentialsString != null && Objects.equals(this.credentialsType, "STRING")) { - signedToken = generateSignedTokensFromCredentialsString(this.credentialsString, this.dataTokens, - this.timeToLive, this.ctx); - - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - return signedToken; - } - - private static List generateSignedTokens(File credentialsPath, String[] dataTokens, - Integer timeToLive, String context) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.GenerateBearerTokenFromCredsCalled.getLog()); - JSONParser parser = new JSONParser(); - List responseToken; - - try { - if (credentialsPath == null || !credentialsPath.isFile()) { - LogUtil.printErrorLog(ErrorLogs.EmptyJSONString.getLog()); - throw new SkyflowException(ErrorCode.EmptyJSONString); - } - - Object obj = parser.parse(new FileReader(String.valueOf(credentialsPath))); - JSONObject saCreds = (JSONObject) obj; - - responseToken = getSignedTokenFromCredsFile(saCreds, dataTokens, timeToLive, context); - - } catch (ParseException e) { - LogUtil.printErrorLog(ErrorLogs.InvalidJSONStringFormat.getLog()); - throw new SkyflowException(ErrorCode.InvalidJSONStringFormat, e); - } catch (IOException e) { - throw new RuntimeException(e); - } - - return responseToken; - } - - private static List generateSignedTokensFromCredentialsString(String credentials, - String[] dataTokens, Integer timeToLive, String context) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.GenerateBearerTokenFromCredsCalled.getLog()); - JSONParser parser = new JSONParser(); - List responseToken; - LogUtil.printInfoLog(InfoLogs.GenerateBearerTokenFromCredsCalled.getLog()); - - try { - if (credentials == null || credentials.isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.EmptyJSONString.getLog()); - throw new SkyflowException(ErrorCode.EmptyJSONString); - } - - Object obj = parser.parse(credentials); - JSONObject saCreds = (JSONObject) obj; - - responseToken = getSignedTokenFromCredsFile(saCreds, dataTokens, timeToLive, context); - - } catch (ParseException e) { - LogUtil.printErrorLog(ErrorLogs.InvalidJSONStringFormat.getLog()); - throw new SkyflowException(ErrorCode.InvalidJSONStringFormat, e); - } - - return responseToken; - } - - private static List getSignedTokenFromCredsFile(JSONObject creds, String[] dataTokens, - Integer timeToLive, String context) throws SkyflowException { - List responseToken; - - try { - String clientID = (String) creds.get("clientID"); - if (clientID == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidClientID.getLog()); - throw new SkyflowException(ErrorCode.InvalidClientID); - } - String keyID = (String) creds.get("keyID"); - if (keyID == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidKeyID.getLog()); - throw new SkyflowException(ErrorCode.InvalidKeyID); - } - - PrivateKey pvtKey = Helpers.getPrivateKeyFromPem((String) creds.get("privateKey")); - - responseToken = getSignedToken(clientID, keyID, pvtKey, dataTokens, timeToLive, context); - - } catch (RuntimeException e) { - throw new SkyflowException(ErrorCode.IncorrectCredentials, e); - } - - return responseToken; - } - - private static List getSignedToken(String clientID, String keyID, PrivateKey pvtKey, - String[] dataTokens, Integer timeToLive, String context) { - final Date createdDate = new Date(); - final Date expirationDate; - - if (timeToLive != null) { - expirationDate = new Date(createdDate.getTime() + (timeToLive * 1000)); - } else { - expirationDate = new Date(createdDate.getTime() + 60000); // Valid for 60 seconds - } - - List list = new ArrayList<>(); - String prefix = "signed_token_"; - for (String dataToken : dataTokens) { - - String eachSignedDataToken = Jwts.builder() - .claim("iss", "sdk") - .claim("iat", (createdDate.getTime()/1000)) - .claim("key", keyID) - .claim("sub", clientID) - .claim("ctx", context) - .claim("tok", dataToken) - .setExpiration(expirationDate) - .signWith(SignatureAlgorithm.RS256, pvtKey) - .compact(); - - SignedDataTokenResponse responseObject = new SignedDataTokenResponse(dataToken, - prefix + eachSignedDataToken); - - list.add(responseObject); - } - return list; - } -} diff --git a/v1/src/main/java/com/skyflow/serviceaccount/util/Token.java b/v1/src/main/java/com/skyflow/serviceaccount/util/Token.java deleted file mode 100644 index 42155e27..00000000 --- a/v1/src/main/java/com/skyflow/serviceaccount/util/Token.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.serviceaccount.util; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.skyflow.common.utils.*; -import com.skyflow.entities.ResponseToken; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.logs.ErrorLogs; -import com.skyflow.logs.InfoLogs; -import com.skyflow.logs.WarnLogs; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.net.URL; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.PrivateKey; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -public final class Token { - - /** - * @param filepath - * @deprecated use generateBearerToken(string filepath), GenerateToken will be removed in future - */ - @Deprecated - public static ResponseToken GenerateToken(String filepath) throws SkyflowException { - LogUtil.printWarningLog(WarnLogs.GetTokenDeprecated.getLog()); - return generateBearerToken(filepath); - } - - /** - * Generates a Bearer Token from the given Service Account Credential file with a default timeout of 60minutes. - * - * @param filepath - */ - public static ResponseToken generateBearerToken(String filepath) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.GenerateBearerTokenCalled.getLog()); - JSONParser parser = new JSONParser(); - ResponseToken responseToken = null; - Path path = null; - try { - if (filepath == null || filepath.isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.EmptyFilePath.getLog()); - throw new SkyflowException(ErrorCode.EmptyFilePath); - } - path = Paths.get((filepath)); - Object obj = parser.parse(new FileReader(String.valueOf(path))); - JSONObject saCreds = (JSONObject) obj; - - responseToken = getSATokenFromCredsFile(saCreds); - - } catch (FileNotFoundException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.InvalidCredentialsPath.getLog(), String.valueOf(path))); - throw new SkyflowException(ErrorCode.InvalidCredentialsPath.getCode(), Helpers.parameterizedString(ErrorCode.InvalidCredentialsPath.getDescription(), String.valueOf(path)), e); - } catch (IOException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.InvalidCredentialsPath.getLog(), String.valueOf(path))); - throw new SkyflowException(ErrorCode.InvalidCredentialsPath.getCode(), Helpers.parameterizedString(ErrorCode.InvalidCredentialsPath.getDescription(), String.valueOf(path)), e); - } catch (ParseException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.InvalidJsonFormat.getLog(), String.valueOf(path))); - throw new SkyflowException(ErrorCode.InvalidJsonFormat.getCode(), Helpers.parameterizedString(ErrorCode.InvalidJsonFormat.getDescription(), String.valueOf(path)), e); - } - - return responseToken; - } - - /** - * Generates a Bearer Token from the given Service Account Credential json string with a default timeout of 60minutes. - * - * @param credentials JSON string of credentials file - */ - - public static ResponseToken generateBearerTokenFromCreds(String credentials) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.GenerateBearerTokenFromCredsCalled.getLog()); - JSONParser parser = new JSONParser(); - ResponseToken responseToken = null; - try { - if (credentials == null || credentials.isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.EmptyJSONString.getLog()); - throw new SkyflowException(ErrorCode.EmptyJSONString); - } - - Object obj = parser.parse(credentials); - JSONObject saCreds = (JSONObject) obj; - - responseToken = getSATokenFromCredsFile(saCreds); - - } catch (ParseException e) { - LogUtil.printErrorLog(ErrorLogs.InvalidJSONStringFormat.getLog()); - throw new SkyflowException(ErrorCode.InvalidJSONStringFormat, e); - } - - return responseToken; - } - - /** - * getSATokenFromCredsFile gets bearer token from service account endpoint - * - * @param creds - */ - private static ResponseToken getSATokenFromCredsFile(JSONObject creds) throws SkyflowException { - ResponseToken responseToken = null; - try { - String clientID = (String) creds.get("clientID"); - if (clientID == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidClientID.getLog()); - throw new SkyflowException(ErrorCode.InvalidClientID); - } - String keyID = (String) creds.get("keyID"); - if (keyID == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidKeyID.getLog()); - throw new SkyflowException(ErrorCode.InvalidKeyID); - } - String tokenURI = (String) creds.get("tokenURI"); - if (tokenURI == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidTokenURI.getLog()); - throw new SkyflowException(ErrorCode.InvalidTokenURI); - } - Map headers = new HashMap<>(); - headers.put(Constants.SDK_METRICS_HEADER_KEY, Helpers.getMetrics().toJSONString()); - - PrivateKey pvtKey = Helpers.getPrivateKeyFromPem((String) creds.get("privateKey")); - - String signedUserJWT = getSignedUserToken(clientID, keyID, tokenURI, pvtKey); - - JSONObject parameters = new JSONObject(); - parameters.put("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"); - parameters.put("assertion", signedUserJWT); - - String response = HttpUtility.sendRequest("POST", new URL(tokenURI), parameters, headers); - - responseToken = new ObjectMapper().readValue(response, ResponseToken.class); - - } catch (JsonMappingException e) { - LogUtil.printErrorLog(ErrorLogs.UnableToReadResponse.getLog()); - throw new SkyflowException(ErrorCode.UnableToReadResponse, e); - } catch (JsonParseException e) { - LogUtil.printErrorLog(ErrorLogs.UnableToReadResponse.getLog()); - throw new SkyflowException(ErrorCode.UnableToReadResponse, e); - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.UnableToReadResponse.getLog()); - throw new SkyflowException(ErrorCode.UnableToReadResponse, e); - } - - return responseToken; - } -// /** -// * Create a PrivateKey instance from raw PKCS#1 bytes. -// */ -// private static PrivateKey parsePkcs1PrivateKey(byte[] pkcs1Bytes) throws SkyflowException { -// int pkcs1Length = pkcs1Bytes.length; -// int totalLength = pkcs1Length + 22; -// byte[] pkcs8Header = new byte[]{ -// 0x30, (byte) 0x82, (byte) ((totalLength >> 8) & 0xff), (byte) (totalLength & 0xff), // Sequence + total length -// 0x2, 0x1, 0x0, // Integer (0) -// 0x30, 0xD, 0x6, 0x9, 0x2A, (byte) 0x86, 0x48, (byte) 0x86, (byte) 0xF7, 0xD, 0x1, 0x1, 0x1, 0x5, 0x0, // Sequence: 1.2.840.113549.1.1.1, NULL -// 0x4, (byte) 0x82, (byte) ((pkcs1Length >> 8) & 0xff), (byte) (pkcs1Length & 0xff) // Octet string + length -// }; -// byte[] pkcs8bytes = joinBytes(pkcs8Header, pkcs1Bytes); -// return parsePkcs8PrivateKey(pkcs8bytes); -// } -// -// private static byte[] joinBytes(byte[] a, byte[] b) { -// byte[] bytes = new byte[a.length + b.length]; -// System.arraycopy(a, 0, bytes, 0, a.length); -// System.arraycopy(b, 0, bytes, a.length, b.length); -// return bytes; -// } - - private static String getSignedUserToken(String clientID, String keyID, String tokenURI, PrivateKey pvtKey) { - final Date createdDate = new Date(); - final Date expirationDate = new Date(createdDate.getTime() + (3600 * 1000)); - String signedToken = Jwts.builder() - .claim("iss", clientID) - .claim("key", keyID) - .claim("aud", tokenURI) - .claim("sub", clientID) - .setExpiration(expirationDate) - .signWith(SignatureAlgorithm.RS256, pvtKey) - .compact(); - - return signedToken; - } - - /** - * @param token - * @deprecated use isExpired(String token), isValid will be removed in future - */ - @Deprecated - public static boolean isValid(String token) { - LogUtil.printWarningLog(WarnLogs.IsValidDeprecated.getLog()); - return !isExpired(token); - } - - public static boolean isExpired(String token) { - - long expiryTime; - long currentTime; - try { - if (token == null || token.isEmpty()) { - LogUtil.printInfoLog(InfoLogs.EmptyBearerToken.getLog()); - return true; - } - - currentTime = new Date().getTime() / 1000; - expiryTime = (long) TokenUtils.decoded(token).get("exp"); - - } catch (ParseException e) { - LogUtil.printInfoLog(ErrorLogs.InvalidBearerToken.getLog()); - return true; - } catch (SkyflowException e) { - LogUtil.printInfoLog(ErrorLogs.InvalidBearerToken.getLog()); - return true; - } - return currentTime > expiryTime; - } -} - diff --git a/v1/src/main/java/com/skyflow/vault/DeleteBySkyflowId.java b/v1/src/main/java/com/skyflow/vault/DeleteBySkyflowId.java deleted file mode 100644 index 3d38787f..00000000 --- a/v1/src/main/java/com/skyflow/vault/DeleteBySkyflowId.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.skyflow.vault; - -import com.skyflow.common.utils.Helpers; -import com.skyflow.common.utils.HttpUtility; -import com.skyflow.common.utils.LogUtil; -import com.skyflow.common.utils.Validators; -import com.skyflow.entities.DeleteOptions; -import com.skyflow.entities.DeleteRecordInput; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.logs.ErrorLogs; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.io.IOException; -import java.net.URL; -import java.util.Map; -import java.util.concurrent.Callable; - -public class DeleteBySkyflowId implements Callable { - private final DeleteRecordInput recordInput; - private final String vaultID; - private final String vaultURL; - private final Map headers; - private final DeleteOptions deleteOptions; - - public DeleteBySkyflowId(DeleteRecordInput recordInput, String vaultID, String vaultURL, Map headers, DeleteOptions deleteOptions) { - this.recordInput = recordInput; - this.vaultID = vaultID; - this.vaultURL = vaultURL; - this.headers = headers; - this.deleteOptions = deleteOptions; - } - - - @Override - public String call() throws SkyflowException { - String response = null; - try { - Validators.validateDeleteBySkyflowId(recordInput); - String url = vaultURL+ "/v1/vaults/"+ vaultID + "/" + recordInput.getTable() + "/" + recordInput.getId(); - response = HttpUtility.sendRequest("DELETE", new URL(url), null,headers); - JSONObject formattedResponse = new JSONObject(); - JSONArray formattedRecords = new JSONArray(); - - JSONObject responseRecords = ((JSONObject) (new JSONParser().parse(response))); - if (responseRecords != null && responseRecords.size() > 0) { - String id = (String) responseRecords.get("skyflow_id"); - JSONObject formattedRecord = new JSONObject(); - formattedRecord.put("skyflow_id", responseRecords.get("skyflow_id")); - formattedRecord.put("deleted", responseRecords.get("deleted")); - formattedRecords.add(formattedRecord); - } - formattedResponse.put("records", formattedRecords); - response = formattedResponse.toJSONString(); - - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.Server.getLog()); - throw new SkyflowException(ErrorCode.Server, e); - } catch (ParseException e) { - LogUtil.printErrorLog(ErrorLogs.ResponseParsingError.getLog()); - throw new SkyflowException(ErrorCode.ResponseParsingError, e); - } catch (SkyflowException e) { - response = constructDeleteByIdErrorObject(e, recordInput.getId()); - } - return response; - } - private String constructDeleteByIdErrorObject(SkyflowException skyflowException, String id){ - String deleteByIdResponse = null; - JSONObject finalResponseError = new JSONObject(); - finalResponseError.put("id", id); - try{ - JSONObject errorObject = (JSONObject) ((JSONObject) new JSONParser().parse(skyflowException.getMessage())).get("error"); - if (errorObject != null) { - JSONObject responseError = new JSONObject(); - responseError.put("code", errorObject.get("http_code")); - responseError.put("description", errorObject.get("message")); - finalResponseError.put("error", responseError); - - deleteByIdResponse = finalResponseError.toString(); - } - - } catch (ParseException e){ - JSONObject responseError = new JSONObject(); - responseError.put("code", skyflowException.getCode()); - responseError.put("description", skyflowException.getMessage()); - finalResponseError.put("error", responseError); - deleteByIdResponse = finalResponseError.toString(); - } - return deleteByIdResponse; - } -} diff --git a/v1/src/main/java/com/skyflow/vault/Detokenize.java b/v1/src/main/java/com/skyflow/vault/Detokenize.java deleted file mode 100644 index da0baec4..00000000 --- a/v1/src/main/java/com/skyflow/vault/Detokenize.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.vault; - -import com.skyflow.common.utils.HttpUtility; -import com.skyflow.common.utils.LogUtil; -import com.skyflow.entities.DetokenizeRecord; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.logs.ErrorLogs; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.io.IOException; -import java.net.URL; -import java.util.Map; -import java.util.concurrent.Callable; - -final class Detokenize implements Callable { - private final DetokenizeRecord record; - private final String endPointURL; - private final Map headers; - - public Detokenize(DetokenizeRecord record, String endPointURL, Map headers) { - this.record = record; - this.endPointURL = endPointURL; - this.headers = headers; - } - - @Override - public String call() throws SkyflowException { - String response = null; - - try { - if (record.getToken() == null || record.getToken().isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.InvalidToken.getLog()); - throw new SkyflowException(ErrorCode.InvalidToken); - } else if (record.getRedaction() == null || record.getRedaction().toString().isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.InvalidDetokenizeInput.getLog()); - throw new SkyflowException(ErrorCode.InvalidDetokenizeInput); - } - - JSONObject bodyJson = new JSONObject(); - JSONArray detokenizationParameters = new JSONArray(); - JSONObject parameterObject = new JSONObject(); - parameterObject.put("token", record.getToken()); - parameterObject.put("redaction", record.getRedaction().toString()); - detokenizationParameters.add(parameterObject); - bodyJson.put("detokenizationParameters", detokenizationParameters); - - String apiResponse = HttpUtility.sendRequest("POST", new URL(endPointURL), bodyJson, headers); - JSONParser parser = new JSONParser(); - JSONObject responseJson = (JSONObject) parser.parse(apiResponse); - JSONArray responseRecords = (JSONArray) responseJson.get("records"); - JSONObject responseObject = (JSONObject) responseRecords.get(0); - JSONObject formattedResponseJson = new JSONObject(); - formattedResponseJson.put("value", responseObject.get("value")); - formattedResponseJson.put("token", responseObject.get("token")); - response = formattedResponseJson.toJSONString(); - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.Server.getLog()); - throw new SkyflowException(ErrorCode.Server, e); - } catch (ParseException e) { - LogUtil.printErrorLog(ErrorLogs.ResponseParsingError.getLog()); - throw new SkyflowException(ErrorCode.ResponseParsingError, e); - } catch (SkyflowException exception) { - response = parseDetokenizeError(exception); - } - return response; - } - - private String parseDetokenizeError(SkyflowException exception) { - String errorResponse = null; - String exceptionMessage = exception.getMessage(); - int exceptionCode = exception.getCode(); - JSONObject errorObject = new JSONObject(); - errorObject.put("token", record.getToken()); - JSONObject errorData = new JSONObject(); - - try { - JSONParser parser = new JSONParser(); - JSONObject errorJson = (JSONObject) parser.parse(exceptionMessage); - JSONObject error = (JSONObject) errorJson.get("error"); - if (error != null) { - errorData.put("code", error.get("http_code")); - errorData.put("description", error.get("message")); - errorObject.put("error", errorData); - errorResponse = errorObject.toJSONString(); - } - } catch (ParseException e) { - errorData.put("code", exceptionCode); - errorData.put("description", exceptionMessage); - errorObject.put("error", errorData); - errorResponse = errorObject.toJSONString(); - } - - return errorResponse; - } -} diff --git a/v1/src/main/java/com/skyflow/vault/Get.java b/v1/src/main/java/com/skyflow/vault/Get.java deleted file mode 100644 index 5951c275..00000000 --- a/v1/src/main/java/com/skyflow/vault/Get.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.skyflow.vault; - -import com.skyflow.common.utils.Helpers; -import com.skyflow.common.utils.HttpUtility; -import com.skyflow.common.utils.LogUtil; -import com.skyflow.common.utils.Validators; -import com.skyflow.entities.GetOptions; -import com.skyflow.entities.GetRecordInput; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.logs.ErrorLogs; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.io.IOException; -import java.net.URL; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.Callable; - -public final class Get implements Callable { - private final GetRecordInput record; - private final String vaultID; - private final String vaultURL; - private final Map headers; - - private final GetOptions getOptions; - - public Get(GetRecordInput record, String vaultID, String vaultURL, Map headers, GetOptions getOptions) { - this.record = record; - this.vaultID = vaultID; - this.vaultURL = vaultURL; - this.headers = headers; - this.getOptions = getOptions; - } - - @Override - public String call() throws Exception { - String response = null; - try { - Validators.validateGetRequestRecord(record, getOptions); - StringBuilder paramsList = Helpers.constructGetRequestURLParams(record, getOptions); - - String url = vaultURL + "/v1/vaults/" + vaultID + "/" + record.getTable() + "?" + paramsList; - - response = HttpUtility.sendRequest("GET", new URL(url), null, headers); - - JSONObject formattedResponse = new JSONObject(); - JSONArray formattedRecords = new JSONArray(); - - JSONArray responseRecords = (JSONArray) ((JSONObject) (new JSONParser().parse(response))).get("records"); - if (responseRecords != null && responseRecords.size() > 0) { - for (Object responseRecord : responseRecords) { - JSONObject fields = (JSONObject) ((JSONObject) responseRecord).get("fields"); - String id = (String) fields.get("skyflow_id"); - fields.remove("skyflow_id"); - fields.put("id", id); - - JSONObject formattedRecord = new JSONObject(); - formattedRecord.put("fields", fields); - formattedRecord.put("table", record.getTable()); - formattedRecords.add(formattedRecord); - } - formattedResponse.put("records", formattedRecords); - - response = formattedResponse.toJSONString(); - } - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.Server.getLog()); - throw new SkyflowException(ErrorCode.Server, e); - } - catch (ParseException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ResponseParsingError.getLog(), "get")); - throw new SkyflowException(ErrorCode.ResponseParsingError, e); - } catch (SkyflowException e) { - response = record.getIds() == null - ? constructGetErrorObject(e, record.getColumnName()) - : constructGetErrorObject(e, record.getIds()); - } - - return response; - } - - private String constructGetErrorObject(SkyflowException skyflowException, String[] ids) { - String getResponse = null; - JSONObject finalResponseError = new JSONObject(); - - try { - JSONObject errorObject = (JSONObject) ((JSONObject) new JSONParser().parse(skyflowException.getMessage())).get("error"); - if (errorObject != null) { - JSONObject responseError = new JSONObject(); - responseError.put("code", errorObject.get("http_code")); - responseError.put("description", errorObject.get("message")); - finalResponseError.put("error", responseError); - - JSONArray idsArray = new JSONArray(); - Collections.addAll(idsArray, ids); - finalResponseError.put("ids", idsArray); - - getResponse = finalResponseError.toString(); - } - } catch (ParseException e) { - JSONObject responseError = new JSONObject(); - responseError.put("code", skyflowException.getCode()); - responseError.put("description", skyflowException.getMessage()); - finalResponseError.put("error", responseError); - getResponse = finalResponseError.toString(); - } - return getResponse; - } - - private String constructGetErrorObject(SkyflowException skyflowException, String columnName) { - String getResponse = null; - JSONObject finalResponseError = new JSONObject(); - - try { - JSONObject errorObject = (JSONObject) ((JSONObject) new JSONParser().parse(skyflowException.getMessage())).get("error"); - if (errorObject != null) { - JSONObject responseError = new JSONObject(); - responseError.put("code", errorObject.get("http_code")); - responseError.put("description", errorObject.get("message")); - finalResponseError.put("error", responseError); - finalResponseError.put("columnName", columnName); - - getResponse = finalResponseError.toString(); - } - } catch (ParseException e) { - JSONObject responseError = new JSONObject(); - responseError.put("code", skyflowException.getCode()); - responseError.put("description", skyflowException.getMessage()); - finalResponseError.put("error", responseError); - getResponse = finalResponseError.toString(); - } - return getResponse; - } -} diff --git a/v1/src/main/java/com/skyflow/vault/GetBySkyflowId.java b/v1/src/main/java/com/skyflow/vault/GetBySkyflowId.java deleted file mode 100644 index 370d1f8f..00000000 --- a/v1/src/main/java/com/skyflow/vault/GetBySkyflowId.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.vault; - -import com.skyflow.common.utils.Helpers; -import com.skyflow.common.utils.HttpUtility; -import com.skyflow.common.utils.LogUtil; -import com.skyflow.common.utils.Validators; -import com.skyflow.entities.GetByIdRecordInput; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.logs.ErrorLogs; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.io.IOException; -import java.net.URL; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.Callable; - -final class GetBySkyflowId implements Callable { - - private final GetByIdRecordInput record; - private final Map headers; - private final String vaultID; - private final String vaultURL; - - GetBySkyflowId(GetByIdRecordInput record, String vaultID, String vaultURL, Map headers) { - this.record = record; - this.vaultID = vaultID; - this.vaultURL = vaultURL; - this.headers = headers; - } - - @Override - public String call() throws SkyflowException { - String response = null; - try { - Validators.validateGetByIdRequestRecord(record); - StringBuilder paramsList = Helpers.constructGetByIdRequestURLParams(record); - - String url = vaultURL + "/v1/vaults/" + vaultID + "/" + record.getTable() + "?" + paramsList; - - response = HttpUtility.sendRequest("GET", new URL(url), null, headers); - - JSONObject formattedResponse = new JSONObject(); - JSONArray formattedRecords = new JSONArray(); - - JSONArray responseRecords = (JSONArray) ((JSONObject) (new JSONParser().parse(response))).get("records"); - if (responseRecords != null && responseRecords.size() > 0) { - for (Object responseRecord : responseRecords) { - JSONObject fields = (JSONObject) ((JSONObject) responseRecord).get("fields"); - String id = (String) fields.get("skyflow_id"); - fields.remove("skyflow_id"); - fields.put("id", id); - - JSONObject formattedRecord = new JSONObject(); - formattedRecord.put("fields", fields); - formattedRecord.put("table", record.getTable()); - formattedRecords.add(formattedRecord); - } - formattedResponse.put("records", formattedRecords); - - response = formattedResponse.toJSONString(); - } - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.Server.getLog()); - throw new SkyflowException(ErrorCode.Server, e); - } catch (ParseException e) { - LogUtil.printErrorLog(ErrorLogs.ResponseParsingError.getLog()); - throw new SkyflowException(ErrorCode.ResponseParsingError, e); - } catch (SkyflowException e) { - response = constructGetByIdErrorObject(e, record.getIds()); - } - - return response; - } - - private String constructGetByIdErrorObject(SkyflowException skyflowException, String[] ids) { - String getByIdResponse = null; - JSONObject finalResponseError = new JSONObject(); - - try { - JSONArray idsArray = new JSONArray(); - Collections.addAll(idsArray, ids); - finalResponseError.put("ids", idsArray); - - JSONObject errorObject = (JSONObject) ((JSONObject) new JSONParser().parse(skyflowException.getMessage())).get("error"); - if (errorObject != null) { - JSONObject responseError = new JSONObject(); - responseError.put("code", errorObject.get("http_code")); - responseError.put("description", errorObject.get("message")); - finalResponseError.put("error", responseError); - - getByIdResponse = finalResponseError.toString(); - } - } catch (ParseException e) { - JSONObject responseError = new JSONObject(); - responseError.put("code", skyflowException.getCode()); - responseError.put("description", skyflowException.getMessage()); - finalResponseError.put("error", responseError); - getByIdResponse = finalResponseError.toString(); - } - return getByIdResponse; - } -} diff --git a/v1/src/main/java/com/skyflow/vault/Insert.java b/v1/src/main/java/com/skyflow/vault/Insert.java deleted file mode 100644 index 94435ee9..00000000 --- a/v1/src/main/java/com/skyflow/vault/Insert.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.skyflow.vault; - -import com.skyflow.common.utils.HttpUtility; -import com.skyflow.common.utils.LogUtil; -import com.skyflow.entities.InsertBulkOptions; -import com.skyflow.entities.InsertRecordInput; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.logs.ErrorLogs; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.io.IOException; -import java.net.URL; -import java.util.Map; -import java.util.concurrent.Callable; - -import static com.skyflow.common.utils.Helpers.getUpsertColumn; - -public final class Insert implements Callable { - private final InsertRecordInput record; - private final String vaultID; - private final String vaultURL; - private final Map headers; - - private final InsertBulkOptions insertOptions; - private final int requestIndex; - - public Insert(InsertRecordInput record, String vaultID, String vaultURL, Map headers, InsertBulkOptions insertOptions, int requestIndex) { - this.record = record; - this.vaultID = vaultID; - this.vaultURL = vaultURL; - this.headers = headers; - this.insertOptions = insertOptions; - this.requestIndex = requestIndex; - } - - @Override - public String call() throws Exception{ - String response = null; - try { - String url = vaultURL+ "/v1/vaults/" +vaultID+"/"+ record.getTable(); - - JSONObject jsonBody = new JSONObject(); - JSONArray insertArray = new JSONArray(); - JSONObject recordObject = new JSONObject(); - recordObject.put("fields", record.getFields()); - - if (insertOptions.getUpsertOptions() != null) - jsonBody.put("upsert", getUpsertColumn(record.getTable(), insertOptions.getUpsertOptions())); - - insertArray.add(recordObject); - jsonBody.put("records", insertArray); - jsonBody.put("tokenization", insertOptions.isTokens()); - response = HttpUtility.sendRequest("POST", new URL(url), jsonBody, headers); - - JSONParser parser = new JSONParser(); - JSONObject responseJson = (JSONObject) parser.parse(response); - JSONArray responseRecords = (JSONArray) responseJson.get("records"); - JSONObject responseObject = (JSONObject) responseRecords.get(0); - JSONObject formattedResponseJson = new JSONObject(); - formattedResponseJson.put("table", record.getTable()); - formattedResponseJson.put("request_index", requestIndex); - if (insertOptions.isTokens()) { - JSONObject responseTokens = (JSONObject) responseObject.get("tokens"); - responseTokens.remove("*"); - responseTokens.put("skyflow_id", responseObject.get("skyflow_id")); - formattedResponseJson.put("fields", responseTokens); - - } else { - formattedResponseJson.put("skyflow_id", responseObject.get("skyflow_id")); - } - - JSONObject resRecords = new JSONObject(); - JSONArray responseArray = new JSONArray(); - responseArray.add(formattedResponseJson); - resRecords.put("records", responseArray); - - response = resRecords.toJSONString(); - - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.Server.getLog()); - throw new SkyflowException(ErrorCode.Server, e); - } catch (SkyflowException exception){ - response = parseInsertError(exception, requestIndex); - } - return response; - } - private String parseInsertError(SkyflowException exception, int requestIndex) { - String errorResponse = null; - String exceptionMessage = exception.getMessage(); - int exceptionCode = exception.getCode(); - JSONObject errorObject = new JSONObject(); - JSONObject errorData = new JSONObject(); - - try { - JSONParser parser = new JSONParser(); - JSONObject errorJson = (JSONObject) parser.parse(exceptionMessage); - JSONObject error = (JSONObject) errorJson.get("error"); - if (error != null) { - errorData.put("code", error.get("http_code")); - errorData.put("description", error.get("message")); - errorData.put("request_index", requestIndex); - errorObject.put("error", errorData); - errorResponse = errorObject.toJSONString(); - } - } catch (ParseException e) { - errorData.put("code", exceptionCode); - errorData.put("description", exceptionMessage); - errorData.put("request_index", requestIndex); - errorObject.put("error", errorData); - errorResponse = errorObject.toJSONString(); - } - - return errorResponse; - } - - } diff --git a/v1/src/main/java/com/skyflow/vault/Skyflow.java b/v1/src/main/java/com/skyflow/vault/Skyflow.java deleted file mode 100644 index b444dc4d..00000000 --- a/v1/src/main/java/com/skyflow/vault/Skyflow.java +++ /dev/null @@ -1,565 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.vault; - - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.skyflow.common.utils.*; -import com.skyflow.entities.*; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.logs.ErrorLogs; -import com.skyflow.logs.InfoLogs; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.io.IOException; -import java.net.URL; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.FutureTask; - -public final class Skyflow { - private final SkyflowConfiguration configuration; - private final TokenUtils tokenUtils; - - private Skyflow(SkyflowConfiguration config) { - this.configuration = config; - this.tokenUtils = new TokenUtils(); - LogUtil.printInfoLog(InfoLogs.InitializedClient.getLog()); - } - - public static Skyflow init(SkyflowConfiguration clientConfig) throws SkyflowException { - return new Skyflow(clientConfig); - } - - public JSONObject insert(JSONObject records) throws SkyflowException { - return insert(records, new InsertOptions(true)); - } - - public JSONObject insertBulk(JSONObject records) throws SkyflowException { - return insertBulk(records, new InsertBulkOptions(true)); - } - - public JSONObject query(JSONObject queryObject) throws SkyflowException { - return query(queryObject, new QueryOptions()); - } - - public JSONObject update(JSONObject records) throws SkyflowException { - return update(records, new UpdateOptions(true)); - } - public JSONObject delete(JSONObject records) throws SkyflowException { - return delete(records, new DeleteOptions()); - } - - public JSONObject insert(JSONObject records, InsertOptions insertOptions) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.InsertMethodCalled.getLog()); - Validators.validateConfiguration(configuration); - LogUtil.printInfoLog(Helpers.parameterizedString(InfoLogs.ValidatedSkyflowConfiguration.getLog(), "insert")); - - if (insertOptions.getUpsertOptions() != null) - Validators.validateUpsertOptions(insertOptions.getUpsertOptions()); - JSONObject insertResponse = null; - try { - InsertInput insertInput = new ObjectMapper().readValue(records.toString(), InsertInput.class); - JSONObject requestBody = Helpers.constructInsertRequest(insertInput, insertOptions); - - String url = configuration.getVaultURL() + "/v1/vaults/" + configuration.getVaultID(); - - Map headers = new HashMap<>(); - headers.put("Authorization", "Bearer " + tokenUtils.getBearerToken(configuration.getTokenProvider())); - headers.put(Constants.SDK_METRICS_HEADER_KEY, Helpers.getMetrics().toJSONString()); - String response = HttpUtility.sendRequest("POST", new URL(url), requestBody, headers); - insertResponse = (JSONObject) new JSONParser().parse(response); - LogUtil.printInfoLog(InfoLogs.ConstructInsertResponse.getLog()); - insertResponse = Helpers.constructInsertResponse(insertResponse, (List) requestBody.get("records"), insertOptions); - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.InvalidInsertInput.getLog()); - throw new SkyflowException(ErrorCode.InvalidInsertInput, e); - } catch (ParseException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ResponseParsingError.getLog(), "insert")); - throw new SkyflowException(ErrorCode.ResponseParsingError, e); - } - - return insertResponse; - } - - public JSONObject detokenize(JSONObject records) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.DetokenizeMethodCalled.getLog()); - Validators.validateConfiguration(configuration); - LogUtil.printInfoLog(Helpers.parameterizedString(InfoLogs.ValidatedSkyflowConfiguration.getLog(), "detokenize")); - - JSONObject finalResponse = new JSONObject(); - JSONArray successRecordsArray = new JSONArray(); - JSONArray errorRecordsArray = new JSONArray(); - try { - DetokenizeInput detokenizeInput = new ObjectMapper().readValue(records.toJSONString(), DetokenizeInput.class); - DetokenizeRecord[] inputRecords = detokenizeInput.getRecords(); - if (inputRecords == null || inputRecords.length == 0) { - throw new SkyflowException(ErrorCode.EmptyRecords); - } - String apiEndpointURL = this.configuration.getVaultURL() + "/v1/vaults/" + this.configuration.getVaultID() + "/detokenize"; - Map headers = new HashMap<>(); - headers.put("Authorization", "Bearer " + tokenUtils.getBearerToken(configuration.getTokenProvider())); - headers.put(Constants.SDK_METRICS_HEADER_KEY, Helpers.getMetrics().toJSONString()); - - FutureTask[] futureTasks = new FutureTask[inputRecords.length]; - for (int index = 0; index < inputRecords.length; index++) { - Callable callable = new Detokenize(inputRecords[index], apiEndpointURL, headers); - futureTasks[index] = new FutureTask(callable); - Thread thread = new Thread(futureTasks[index]); - thread.start(); - } - for (FutureTask task : futureTasks) { - String taskData = (String) task.get(); - JSONParser parser = new JSONParser(); - JSONObject responseJson = (JSONObject) parser.parse(taskData); - if (responseJson.containsKey("error")) { - errorRecordsArray.add(responseJson); - } else if (responseJson.containsKey("value")) { - successRecordsArray.add(responseJson); - } - } - if (errorRecordsArray.isEmpty()) { - finalResponse.put("records", successRecordsArray); - } else if (successRecordsArray.isEmpty()) { - finalResponse.put("errors", errorRecordsArray); - throw new SkyflowException(500, "Server returned errors, check SkyflowException.getData() for more", finalResponse); - } else { - finalResponse.put("records", successRecordsArray); - finalResponse.put("errors", errorRecordsArray); - throw new SkyflowException(500, "Server returned errors, check SkyflowException.getData() for more", finalResponse); - } - } catch (IOException exception) { - LogUtil.printErrorLog(ErrorLogs.InvalidDetokenizeInput.getLog()); - throw new SkyflowException(ErrorCode.InvalidDetokenizeInput, exception); - } catch (InterruptedException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ThreadInterruptedException.getLog(), "detokenize")); - throw new SkyflowException(ErrorCode.ThreadInterruptedException, e); - } catch (ExecutionException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ThreadExecutionException.getLog(), "detokenize")); - throw new SkyflowException(ErrorCode.ThreadExecutionException, e); - } catch (ParseException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ResponseParsingError.getLog(), "detokenize")); - throw new SkyflowException(ErrorCode.ResponseParsingError, e); - } - return finalResponse; - } - - public JSONObject getById(JSONObject getByIdInput) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.GetByIdMethodCalled.getLog()); - Validators.validateConfiguration(configuration); - LogUtil.printInfoLog(Helpers.parameterizedString(InfoLogs.ValidatedSkyflowConfiguration.getLog(), "getById")); - - JSONObject finalResponse = new JSONObject(); - JSONArray successRecordsArray = new JSONArray(); - JSONArray errorRecordsArray = new JSONArray(); - try { - GetByIdInput input = new ObjectMapper().readValue(getByIdInput.toString(), GetByIdInput.class); - GetByIdRecordInput[] recordInputs = input.getRecords(); - - if (recordInputs == null || recordInputs.length == 0) { - throw new SkyflowException(ErrorCode.EmptyRecords); - } - - Map headers = new HashMap<>(); - headers.put("Authorization", "Bearer " + tokenUtils.getBearerToken(configuration.getTokenProvider())); - headers.put(Constants.SDK_METRICS_HEADER_KEY, Helpers.getMetrics().toJSONString()); - - FutureTask[] futureTasks = new FutureTask[recordInputs.length]; - for (int i = 0; i < recordInputs.length; i++) { - Callable callable = new GetBySkyflowId(recordInputs[i], configuration.getVaultID(), configuration.getVaultURL(), headers); - futureTasks[i] = new FutureTask(callable); - - Thread t = new Thread(futureTasks[i]); - t.start(); - } - - for (FutureTask task : futureTasks) { - String taskData = (String) task.get(); - JSONObject responseJson = (JSONObject) new JSONParser().parse(taskData); - if (responseJson.containsKey("error")) { - errorRecordsArray.add(responseJson); - } else if (responseJson.containsKey("records")) { - successRecordsArray.addAll((Collection) responseJson.get("records")); - } - } - - if (errorRecordsArray.isEmpty()) { - finalResponse.put("records", successRecordsArray); - } else if (successRecordsArray.isEmpty()) { - finalResponse.put("errors", errorRecordsArray); - ErrorCode serverError = ErrorCode.ServerReturnedErrors; - throw new SkyflowException(serverError.getCode(), serverError.getDescription(), finalResponse); - } else { - finalResponse.put("records", successRecordsArray); - finalResponse.put("errors", errorRecordsArray); - ErrorCode serverError = ErrorCode.ServerReturnedErrors; - throw new SkyflowException(serverError.getCode(), serverError.getDescription(), finalResponse); - } - - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.InvalidGetByIdInput.getLog()); - throw new SkyflowException(ErrorCode.InvalidGetByIdInput, e); - } catch (InterruptedException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ThreadInterruptedException.getLog(), "getById")); - throw new SkyflowException(ErrorCode.ThreadInterruptedException, e); - } catch (ExecutionException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ThreadExecutionException.getLog(), "getById")); - throw new SkyflowException(ErrorCode.ThreadExecutionException, e); - } catch (ParseException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ResponseParsingError.getLog(), "getById")); - throw new SkyflowException(ErrorCode.ResponseParsingError, e); - } - - return finalResponse; - } - public JSONObject get(JSONObject getInput) throws SkyflowException { - return get(getInput, new GetOptions(false)); - } - public JSONObject get(JSONObject getInput, GetOptions getOptions ) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.GetMethodCalled.getLog()); - Validators.validateConfiguration(configuration); - LogUtil.printInfoLog(Helpers.parameterizedString(InfoLogs.ValidatedSkyflowConfiguration.getLog(), "get")); - - JSONObject finalResponse = new JSONObject(); - JSONArray successRecordsArray = new JSONArray(); - JSONArray errorRecordsArray = new JSONArray(); - try { - GetInput input = new ObjectMapper().readValue(getInput.toJSONString(), GetInput.class); - GetRecordInput[] recordInputs = input.getRecords(); - - if (recordInputs == null || recordInputs.length == 0) { - throw new SkyflowException(ErrorCode.EmptyRecords); - } - - Map headers = new HashMap<>(); - headers.put("Authorization", "Bearer " + tokenUtils.getBearerToken(configuration.getTokenProvider())); - headers.put(Constants.SDK_METRICS_HEADER_KEY, Helpers.getMetrics().toJSONString()); - - FutureTask[] futureTasks = new FutureTask[recordInputs.length]; - for (int i = 0; i < recordInputs.length; i++) { - Callable callable = new Get(recordInputs[i], configuration.getVaultID(), configuration.getVaultURL(), headers, getOptions); - futureTasks[i] = new FutureTask(callable); - - Thread t = new Thread(futureTasks[i]); - t.start(); - } - - for (FutureTask task : futureTasks) { - String taskData = (String) task.get(); - JSONObject responseJson = (JSONObject) new JSONParser().parse(taskData); - if (responseJson.containsKey("error")) { - errorRecordsArray.add(responseJson); - } else if (responseJson.containsKey("records")) { - successRecordsArray.addAll((Collection) responseJson.get("records")); - } - } - - if (errorRecordsArray.isEmpty()) { - finalResponse.put("records", successRecordsArray); - } else if (successRecordsArray.isEmpty()) { - finalResponse.put("errors", errorRecordsArray); - ErrorCode serverError = ErrorCode.ServerReturnedErrors; - throw new SkyflowException(serverError.getCode(), serverError.getDescription(), finalResponse); - } else { - finalResponse.put("records", successRecordsArray); - finalResponse.put("errors", errorRecordsArray); - ErrorCode serverError = ErrorCode.ServerReturnedErrors; - throw new SkyflowException(serverError.getCode(), serverError.getDescription(), finalResponse); - } - - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.InvalidGetInput.getLog()); - throw new SkyflowException(ErrorCode.InvalidGetInput, e); - } catch (InterruptedException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ThreadInterruptedException.getLog(), "get")); - throw new SkyflowException(ErrorCode.ThreadInterruptedException, e); - } catch (ExecutionException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ThreadExecutionException.getLog(), "get")); - throw new SkyflowException(ErrorCode.ThreadExecutionException, e); - } catch (ParseException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ResponseParsingError.getLog(), "get")); - throw new SkyflowException(ErrorCode.ResponseParsingError, e); - } - - return finalResponse; - } - - public JSONObject update(JSONObject records, UpdateOptions updateOptions) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.UpdateMethodCalled.getLog()); - Validators.validateConfiguration(configuration); - LogUtil.printInfoLog(Helpers.parameterizedString(InfoLogs.ValidatedSkyflowConfiguration.getLog(), "update")); - - JSONArray successRecordsArray = new JSONArray(); - JSONArray errorRecordsArray = new JSONArray(); - - JSONObject updateResponse = new JSONObject(); - - try { - UpdateInput updateInput = new ObjectMapper().readValue(records.toString(), UpdateInput.class); - UpdateRecordInput[] recordInputs = updateInput.getRecords(); - if (recordInputs == null || recordInputs.length == 0) { - throw new SkyflowException(ErrorCode.EmptyRecords); - } - - Map headers = new HashMap<>(); - headers.put("Authorization", "Bearer " + tokenUtils.getBearerToken(configuration.getTokenProvider())); - headers.put(Constants.SDK_METRICS_HEADER_KEY, Helpers.getMetrics().toJSONString()); - - FutureTask[] futureTasks = new FutureTask[recordInputs.length]; - for (int i = 0; i < recordInputs.length; i++) { - Callable callable = new UpdateBySkyflowId(recordInputs[i], configuration.getVaultID(), configuration.getVaultURL(), headers, updateOptions); - futureTasks[i] = new FutureTask(callable); - Thread t = new Thread(futureTasks[i]); - t.start(); - } - - for (FutureTask task : futureTasks) { - String taskData = (String) task.get(); - JSONObject responseJson = (JSONObject) new JSONParser().parse(taskData); - if (responseJson.containsKey("error")) { - errorRecordsArray.add(responseJson); - } else if (responseJson.containsKey("records")) { - successRecordsArray.add(responseJson.get("records")); - } - } - if (errorRecordsArray.isEmpty()) { - updateResponse.put("records", successRecordsArray); - } else if (successRecordsArray.isEmpty()) { - updateResponse.put("error", errorRecordsArray); - throw new SkyflowException(500, "Server returned errors, check SkyflowException.Update() for more", updateResponse); - } else { - updateResponse.put("records", successRecordsArray); - updateResponse.put("error", errorRecordsArray); - throw new SkyflowException(500, "Server returned errors, check SkyflowException.Update() for more", updateResponse); - } - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.InvalidUpdateInput.getLog()); - throw new SkyflowException(ErrorCode.InvalidUpdateInput, e); - } catch (InterruptedException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ThreadInterruptedException.getLog(), "updateById")); - throw new SkyflowException(ErrorCode.ThreadInterruptedException, e); - } catch (ExecutionException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ThreadExecutionException.getLog(), "updateById")); - throw new SkyflowException(ErrorCode.ThreadExecutionException, e); - } catch (ParseException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ResponseParsingError.getLog(), "updateById")); - throw new SkyflowException(ErrorCode.ResponseParsingError, e); - } - return updateResponse; - - } - - public JSONObject delete(JSONObject records, DeleteOptions deleteOptions) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.deleteMethodCalled.getLog()); - Validators.validateConfiguration(configuration); - LogUtil.printInfoLog(Helpers.parameterizedString(InfoLogs.ValidatedSkyflowConfiguration.getLog(), "delete")); - - JSONObject deleteResponse = new JSONObject(); - JSONArray successRecordsArray = new JSONArray(); - JSONArray errorRecordsArray = new JSONArray(); - - try { - DeleteInput deleteInput = new ObjectMapper().readValue(records.toString(), DeleteInput.class); - DeleteRecordInput[] recordInputs = deleteInput.getRecords(); - if (recordInputs == null || recordInputs.length == 0) { - throw new SkyflowException(ErrorCode.EmptyRecords); - } - Map headers = new HashMap<>(); - headers.put("Authorization", "Bearer " + tokenUtils.getBearerToken(configuration.getTokenProvider())); - headers.put(Constants.SDK_METRICS_HEADER_KEY, Helpers.getMetrics().toJSONString()); - FutureTask[] futureTasks = new FutureTask[recordInputs.length]; - - - for (int i = 0; i < recordInputs.length; i++) { - Callable callable = new DeleteBySkyflowId(recordInputs[i], configuration.getVaultID(), configuration.getVaultURL(), headers, deleteOptions); - futureTasks[i] = new FutureTask(callable); - Thread t = new Thread(futureTasks[i]); - t.start(); - } - for (FutureTask task : futureTasks) { - String taskData = (String) task.get(); - JSONObject responseJson = (JSONObject) new JSONParser().parse(taskData); - if (responseJson.containsKey("error")) { - errorRecordsArray.add(responseJson); - } else if (responseJson.containsKey("records")) { - JSONArray resp = (JSONArray) new JSONParser().parse(responseJson.get("records").toString()) ; - successRecordsArray.add(resp.get(0)); - } - } - if (errorRecordsArray.isEmpty()) { - deleteResponse.put("records", successRecordsArray); - } else if (successRecordsArray.isEmpty()) { - deleteResponse.put("errors", errorRecordsArray); - ErrorCode serverError = ErrorCode.ServerReturnedErrors; - throw new SkyflowException(serverError.getCode(), serverError.getDescription(), deleteResponse); - } else { - deleteResponse.put("records", successRecordsArray); - deleteResponse.put("errors", errorRecordsArray); - ErrorCode serverError = ErrorCode.ServerReturnedErrors; - throw new SkyflowException(serverError.getCode(), serverError.getDescription(), deleteResponse); - } - - }catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.InvalidDeleteInput.getLog()); - throw new SkyflowException(ErrorCode.InvalidDeleteInput, e); - } catch (InterruptedException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ThreadInterruptedException.getLog(), "deleteById")); - throw new SkyflowException(ErrorCode.ThreadInterruptedException, e); - } catch (ExecutionException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ThreadExecutionException.getLog(), "deleteById")); - throw new SkyflowException(ErrorCode.ThreadExecutionException, e); - } catch (ParseException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ResponseParsingError.getLog(), "deleteById")); - throw new SkyflowException(ErrorCode.ResponseParsingError, e); - } - return deleteResponse; - } - public JSONObject invokeConnection(JSONObject connectionConfig) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.InvokeConnectionCalled.getLog()); - JSONObject connectionResponse; - try { - Validators.validateConnectionConfiguration(connectionConfig, configuration); - String filledURL = Helpers.constructConnectionURL(connectionConfig); - - Map headers = new HashMap<>(); - - if (connectionConfig.containsKey("requestHeader")) { - headers = Helpers.constructConnectionHeadersMap((JSONObject) connectionConfig.get("requestHeader")); - } - if (!headers.containsKey("x-skyflow-authorization")) { - headers.put("x-skyflow-authorization", tokenUtils.getBearerToken(configuration.getTokenProvider())); - } - headers.put(Constants.SDK_METRICS_HEADER_KEY, Helpers.getMetrics().toJSONString()); - String requestMethod = connectionConfig.get("methodName").toString(); - JSONObject requestBody = null; - if (connectionConfig.containsKey("requestBody")) { - requestBody = (JSONObject) connectionConfig.get("requestBody"); - } - - String response = HttpUtility.sendRequest(requestMethod, new URL(filledURL), requestBody, headers); - connectionResponse = (JSONObject) new JSONParser().parse(response); - - } catch (IOException exception) { - LogUtil.printErrorLog(ErrorLogs.InvalidInvokeConnectionInput.getLog()); - throw new SkyflowException(ErrorCode.InvalidConnectionInput, exception); - } catch (ParseException exception) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ResponseParsingError.getLog(), "invokeConnection")); - throw new SkyflowException(ErrorCode.ResponseParsingError, exception); - } - return connectionResponse; - } - - public JSONObject query(JSONObject queryObject,QueryOptions queryOptions) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.QuerySupportCalled.getLog()); - Validators.validateConfiguration(configuration); - LogUtil.printInfoLog(Helpers.parameterizedString(InfoLogs.ValidatedSkyflowConfiguration.getLog(), "query")); - JSONObject queryResponse = null; - try { - JSONObject queryJsonbject = (JSONObject) queryObject; - - QueryRecordInput queryInput = new ObjectMapper().readValue(queryJsonbject.toString(), QueryRecordInput.class); - - JSONObject requestBody = Helpers.constructQueryRequest(queryInput, queryOptions); - - String url = configuration.getVaultURL() + "/v1/vaults/" + configuration.getVaultID() + "/query"; - Map headers = new HashMap<>(); - headers.put("Authorization", "Bearer " + tokenUtils.getBearerToken(configuration.getTokenProvider())); - headers.put(Constants.SDK_METRICS_HEADER_KEY, Helpers.getMetrics().toJSONString()); - String response = HttpUtility.sendRequest("POST", new URL(url), requestBody, headers); - queryResponse = (JSONObject) new JSONParser().parse(response); - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.InvalidQueryInput.getLog()); - throw new SkyflowException(ErrorCode.InvalidQueryInput,e); - } catch (ParseException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ResponseParsingError.getLog(), "query")); - throw new SkyflowException(ErrorCode.ResponseParsingError, e); - } - catch (SkyflowException e) { - JSONObject queryErrorResponse = Helpers.constructQueryErrorObject(e); - throw new SkyflowException(400, "Query is missing", queryErrorResponse); - } - return queryResponse; - } - public JSONObject insertBulk(JSONObject records, InsertBulkOptions insertOptions) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.InsertBulkMethodCalled.getLog()); - Validators.validateConfiguration(configuration); - LogUtil.printInfoLog(Helpers.parameterizedString(InfoLogs.ValidatedSkyflowConfiguration.getLog(), "insert")); - JSONObject finalResponse = new JSONObject(); - JSONArray successRecordsArray = new JSONArray(); - JSONArray errorRecordsArray = new JSONArray(); - - if (insertOptions.getUpsertOptions() != null) - Validators.validateUpsertOptions(insertOptions.getUpsertOptions()); - try { - InsertInput insertInput = new ObjectMapper().readValue(records.toString(), InsertInput.class); - - Map headers = new HashMap<>(); - headers.put("Authorization", "Bearer " + tokenUtils.getBearerToken(configuration.getTokenProvider())); - headers.put(Constants.SDK_METRICS_HEADER_KEY, Helpers.getMetrics().toJSONString()); - - InsertRecordInput[] inputRecords = insertInput.getRecords(); - - if (inputRecords == null || insertInput.getRecords().length == 0) { - throw new SkyflowException(ErrorCode.EmptyRecords); - } - - for (int i = 0; i < inputRecords.length; i++) { - Validators.validateInsertRecord(inputRecords[i]); - } - FutureTask[] futureTasks = new FutureTask[inputRecords.length]; - for (int index = 0; index < inputRecords.length; index++) { - Callable callable = new Insert(inputRecords[index], configuration.getVaultID(), configuration.getVaultURL(), headers, insertOptions, index); - futureTasks[index] = new FutureTask(callable); - - Thread thread = new Thread(futureTasks[index]); - thread.start(); - } - for (FutureTask task : futureTasks) { - String taskData = (String) task.get(); - JSONParser parser = new JSONParser(); - JSONObject responseJson = (JSONObject) parser.parse(taskData); - if (responseJson.containsKey("error")) { - errorRecordsArray.add(responseJson); - } else if (responseJson.containsKey("records")) { - JSONArray successRes = (JSONArray) responseJson.get("records"); - successRecordsArray.add(successRes.get(0)); - } - } - if (errorRecordsArray.isEmpty()) { - finalResponse.put("records", successRecordsArray); - } else if (successRecordsArray.isEmpty()) { - finalResponse.put("errors", errorRecordsArray); - throw new SkyflowException(ErrorCode.ServerReturnedErrors.getCode(), ErrorLogs.ServerReturnedErrors.getLog(), finalResponse); - } else { - finalResponse.put("records", successRecordsArray); - finalResponse.put("errors", errorRecordsArray); - throw new SkyflowException(ErrorCode.ServerReturnedErrors.getCode(), ErrorLogs.ServerReturnedErrors.getLog(), finalResponse); - } - - } catch (IOException var9) { - LogUtil.printErrorLog(ErrorLogs.InvalidInsertInput.getLog()); - throw new SkyflowException(ErrorCode.InvalidInsertInput, var9); - } catch (ParseException var10) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ResponseParsingError.getLog(), new String[]{"Insert"})); - throw new SkyflowException(ErrorCode.ResponseParsingError, var10); - } catch (InterruptedException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ThreadInterruptedException.getLog(), "Insert")); - throw new SkyflowException(ErrorCode.ThreadInterruptedException, e); - } catch (ExecutionException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ThreadExecutionException.getLog(), "Insert")); - throw new SkyflowException(ErrorCode.ThreadExecutionException, e); - } - - return finalResponse; - - } -} diff --git a/v1/src/main/java/com/skyflow/vault/UpdateBySkyflowId.java b/v1/src/main/java/com/skyflow/vault/UpdateBySkyflowId.java deleted file mode 100644 index e26299a0..00000000 --- a/v1/src/main/java/com/skyflow/vault/UpdateBySkyflowId.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.skyflow.vault; - -import com.skyflow.common.utils.Helpers; -import com.skyflow.common.utils.HttpUtility; -import com.skyflow.common.utils.LogUtil; -import com.skyflow.entities.UpdateOptions; -import com.skyflow.entities.UpdateRecordInput; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import com.skyflow.logs.ErrorLogs; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.io.IOException; -import java.net.URL; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.Callable; - -final class UpdateBySkyflowId implements Callable { - - public final UpdateOptions options; - private final UpdateRecordInput record; - private final Map headers; - private final String vaultID; - private final String vaultURL; - - UpdateBySkyflowId(UpdateRecordInput record, String vaultID, String vaultURL, Map headers, UpdateOptions updateOptions) { - this.record = record; - this.vaultID = vaultID; - this.vaultURL = vaultURL; - this.headers = headers; - this.options = updateOptions; - } - - - @Override - public String call() throws Exception { - String response = null; - try { - JSONObject requestBody = Helpers.constructUpdateRequest(record, options); - JSONObject finalBody = new JSONObject(); - - finalBody.put("record", requestBody); - finalBody.put("tokenization", options.isTokens()); - - String url = vaultURL + "/v1/vaults/" + vaultID + "/" + record.getTable() + "/" + record.getId(); - response = HttpUtility.sendRequest("PUT", new URL(url), finalBody, headers); - JSONObject formattedRecords = new JSONObject(); - JSONObject responseRecords = (JSONObject) (new JSONParser().parse(response)); - - - if (responseRecords != null && responseRecords.size() > 0) { - JSONObject fields = (JSONObject) responseRecords.get("tokens"); - String id = (String) responseRecords.get("skyflow_id"); - - JSONObject formattedRecord = new JSONObject(); - formattedRecord.put("id", id); - formattedRecord.put("table", record.getTable()); - formattedRecord.put("fields", fields); - formattedRecords.put("records", formattedRecord); - } - response = formattedRecords.toJSONString(); - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.Server.getLog()); - throw new SkyflowException(ErrorCode.Server, e); - } catch (ParseException e) { - LogUtil.printErrorLog(Helpers.parameterizedString(ErrorLogs.ResponseParsingError.getLog(), "updateById")); - throw new SkyflowException(ErrorCode.ResponseParsingError, e); - } catch (SkyflowException e) { - response = constructUpdateByIdErrorObject(e, record.getId()); - } - return response; - } - - private String constructUpdateByIdErrorObject(SkyflowException skyflowException, String ids) { - - String updateByIdResponse = null; - JSONObject finalResponseError = new JSONObject(); - - try { - JSONArray idsArray = new JSONArray(); - Collections.addAll(idsArray, ids); - finalResponseError.put("ids", idsArray); - - JSONObject errorObject = (JSONObject) ((JSONObject) new JSONParser().parse(skyflowException.getMessage())).get("error"); - if (errorObject != null) { - JSONObject responseError = new JSONObject(); - responseError.put("code", errorObject.get("http_code")); - responseError.put("description", errorObject.get("message")); - finalResponseError.put("error", responseError); - - updateByIdResponse = finalResponseError.toString(); - } - } catch (ParseException e) { - JSONObject responseError = new JSONObject(); - responseError.put("code", skyflowException.getCode()); - responseError.put("description", skyflowException.getMessage()); - finalResponseError.put("error", responseError); - updateByIdResponse = finalResponseError.toString(); - } - return updateByIdResponse; - } -} diff --git a/v1/src/test/java/com/skyflow/common/utils/HelpersTest.java b/v1/src/test/java/com/skyflow/common/utils/HelpersTest.java deleted file mode 100644 index fea055d2..00000000 --- a/v1/src/test/java/com/skyflow/common/utils/HelpersTest.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.common.utils; - -import com.skyflow.Configuration; -import com.skyflow.entities.GetOptions; -import com.skyflow.entities.GetRecordInput; -import com.skyflow.entities.LogLevel; -import com.skyflow.entities.RedactionType; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; - -import static com.skyflow.common.utils.Helpers.constructGetRequestURLParams; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.when; - -import java.security.PrivateKey; -import org.json.simple.JSONObject; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - - -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.TokenUtils", "com.skyflow.common.utils.HttpUtility"}) -public class HelpersTest { - - private static String tableName = null; - private static String columnName = null; - private static String reqId = null; - private static String[] columnValue = new String[1]; - private static String[] ids = new String[1]; - private static String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; - - @BeforeClass - public static void setup() throws SkyflowException { - PowerMockito.mockStatic(TokenUtils.class); - PowerMockito.when(TokenUtils.isTokenValid("valid_token")).thenReturn(true); - PowerMockito.when(TokenUtils.isTokenValid("not_a_valid_token")).thenReturn(false); - - PowerMockito.mockStatic(HttpUtility.class); - PowerMockito.when(HttpUtility.getRequestID()).thenReturn("abc"); - reqId = HttpUtility.getRequestID(); - tableName = "account_details"; - columnName = "card_number"; - columnValue[0] = "123451234554321"; - ids[0] = "123451234554321"; - } - - @Test - public void testMessageWithRequestID(){ - String message = Helpers.appendRequestId("message", reqId); - String expectedMessage = "message" + " - requestId: " + "abc"; - assertEquals(expectedMessage, message); - } - - @Test - public void testFormatJsonToFormEncodedString(){ - Configuration.setLogLevel(LogLevel.DEBUG); - JSONObject testJson = new JSONObject(); - testJson.put("key1","value1"); - JSONObject nestedObj = new JSONObject(); - nestedObj.put("key2","value2"); - testJson.put("nest",nestedObj); - - String testResponse = Helpers.formatJsonToFormEncodedString(testJson); - assert testResponse.contains("key1=value1"); - assert testResponse.contains("nest[key2]=value2"); - } - - @Test - public void testFormatJsonToMultiPartFormDataString(){ - JSONObject testJson = new JSONObject(); - testJson.put("key1","value1"); - JSONObject nestedObj = new JSONObject(); - nestedObj.put("key2","value2"); - testJson.put("nest",nestedObj); - String testBoundary = "123"; - String testResponse = Helpers.formatJsonToMultiPartFormDataString(testJson,testBoundary); - assert testResponse.contains("--"+testBoundary); - assert testResponse.contains("--"+testBoundary+"--"); - assert testResponse.contains("Content-Disposition: form-data; name=\"key1\""); - assert testResponse.contains("value1"); - assert testResponse.contains("Content-Disposition: form-data; name=\"nest[key2]\""); - assert testResponse.contains("value2"); - } - - @Test - public void testInvalidPrivateKey(){ - String pemKey = "abc"; - - try{ - PrivateKey key = Helpers.getPrivateKeyFromPem(pemKey); - }catch (SkyflowException exception) { - assertEquals(exception.getMessage(), ErrorCode.UnableToRetrieveRSA.getDescription()); - } - } - @Test - public void testInvalidKeySpec(){ - byte[] pkcs8Bytes = {}; - try{ - Helpers.parsePkcs8PrivateKey(pkcs8Bytes); - }catch (SkyflowException exception) { - assertEquals(exception.getMessage(), ErrorCode.InvalidKeySpec.getDescription()); - } - } - @Test - public void constructGetRequestURLParamsColumnValueTest(){ - GetRecordInput recordInput = new GetRecordInput(); - - recordInput.setTable(tableName); - recordInput.setColumnValues(columnValue); - recordInput.setColumnName(columnName); - recordInput.setRedaction(RedactionType.PLAIN_TEXT); - StringBuilder paramsList = constructGetRequestURLParams(recordInput, new GetOptions(false)); - - Assert.assertTrue(paramsList.toString().contains("&")); - - Assert.assertTrue(paramsList.toString().contains("column_name="+ columnName)); - Assert.assertTrue(paramsList.toString().contains("column_values="+ columnValue[0])); - Assert.assertTrue(paramsList.toString().contains("redaction="+ RedactionType.PLAIN_TEXT.toString())); - } - @Test - public void constructGetRequestURLParamsIdTest(){ - GetRecordInput recordInput = new GetRecordInput(); - - recordInput.setTable(tableName); - recordInput.setIds(ids); - recordInput.setRedaction(RedactionType.PLAIN_TEXT); - StringBuilder paramsList = constructGetRequestURLParams(recordInput, new GetOptions(false)); - Assert.assertTrue(paramsList.toString().contains("&")); - - Assert.assertTrue(paramsList.toString().contains("skyflow_ids="+ ids[0])); - Assert.assertTrue(paramsList.toString().contains("redaction="+"PLAIN_TEXT")); - - } - @Test - public void constructGetRequestURLParamsIdTokenTrueTest(){ - GetRecordInput recordInput = new GetRecordInput(); - - recordInput.setTable(tableName); - recordInput.setIds(ids); - StringBuilder paramsList = constructGetRequestURLParams(recordInput, new GetOptions(true)); - - Assert.assertTrue(paramsList.toString().contains("&")); - Assert.assertFalse(paramsList.toString().contains("redaction=PLAIN_TEXT")); - - Assert.assertTrue(paramsList.toString().contains("skyflow_ids="+ ids[0])); - Assert.assertTrue(paramsList.toString().contains("tokenization="+"true")); - - } - @Test - public void testGetMetrics() { - JSONObject metrics = Helpers.getMetrics(); - assertEquals(true, metrics.containsKey("sdk_name_version")); - assertEquals(true, metrics.containsKey("sdk_client_device_model")); - assertEquals(true, metrics.containsKey("sdk_client_os_details")); - assertEquals(true, metrics.containsKey("sdk_runtime_details")); - - assertEquals("skyflow-java@"+ Constants.SDK_VERSION, metrics.get("sdk_name_version")); - assertNotNull(metrics.get("sdk_client_device_model")); - - assertNotNull(metrics.get("sdk_client_os_details")); - assertNotNull(metrics.get("sdk_runtime_details")); - assertNotNull(metrics.get("sdk_client_device_model")); - - String runtimeDetails = (String) metrics.get("sdk_runtime_details"); - assertEquals(true, runtimeDetails.startsWith("Java@")); - - } - @Test - public void testGetMetricsWithException() { - // Arrange - String expectedSdkVersion = Constants.SDK_VERSION; - String expectedDeviceModel = ""; - String expectedOsDetails = ""; - String expectedJavaVersion = ""; - - // Mocking the System.getProperty() method to throw an exception - System.setProperty("os.name", ""); - System.setProperty("os.version", ""); - System.setProperty("java.version", ""); - - // Act - JSONObject metrics = Helpers.getMetrics(); - assertEquals(true, metrics.containsKey("sdk_name_version")); - assertEquals(true, metrics.containsKey("sdk_client_device_model")); - assertEquals(true, metrics.containsKey("sdk_client_os_details")); - assertEquals(true, metrics.containsKey("sdk_runtime_details")); - // Assert - assertEquals("skyflow-java@" + expectedSdkVersion, metrics.get("sdk_name_version")); - assertEquals(expectedDeviceModel, metrics.get("sdk_client_device_model")); - assertEquals(expectedOsDetails, metrics.get("sdk_client_os_details")); - assertEquals("Java@" + expectedJavaVersion, metrics.get("sdk_runtime_details")); - } -} - diff --git a/v1/src/test/java/com/skyflow/common/utils/HttpUtilityTest.java b/v1/src/test/java/com/skyflow/common/utils/HttpUtilityTest.java deleted file mode 100644 index e473ee1f..00000000 --- a/v1/src/test/java/com/skyflow/common/utils/HttpUtilityTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.common.utils; - -import com.skyflow.errors.SkyflowException; -import org.json.simple.JSONObject; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLStreamHandler; - -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.BDDMockito.given; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ URL.class, HttpURLConnection.class }) -public class HttpUtilityTest { - - @InjectMocks - HttpUtility httpUtility; - - @Mock - OutputStream outputStream; - - private String expected; - - private String expectedError; - private URL url; - - private HttpURLConnection mockConnection; - private static String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; - - @Before - public void setup() throws IOException { - expected = "{\"status\":\"success\"}"; - expectedError = "{\"status\":\"something went wrong\"}"; - mockConnection = Mockito.mock(HttpURLConnection.class); - given(mockConnection.getInputStream()).willReturn(new ByteArrayInputStream(expected.getBytes())); - given(mockConnection.getErrorStream()).willReturn(new ByteArrayInputStream(expectedError.getBytes())); - given(mockConnection.getOutputStream()).willReturn(outputStream); - given(mockConnection.getResponseCode()).willReturn(200); - given(mockConnection.getHeaderField(anyString())).willReturn("id"); - final URLStreamHandler handler = new URLStreamHandler() { - @Override - protected URLConnection openConnection(final URL arg0) throws IOException { - return mockConnection; - } - }; - url = new URL("https://google.com", "google.com", 80, "", handler); - } - - @Test - @PrepareForTest({ URL.class, HttpURLConnection.class }) - public void testSendRequest() { - try { - given(mockConnection.getRequestProperty("content-type")).willReturn("application/json"); - - JSONObject headers = new JSONObject(); - headers.put("content-type", "application/json"); - - JSONObject params = new JSONObject(); - params.put("key", "value"); - - String response = httpUtility.sendRequest("GET", url, params, headers); - - Assert.assertEquals(expected, response); - } catch (IOException e) { - fail(INVALID_EXCEPTION_THROWN); - } catch (SkyflowException e) { - fail(INVALID_EXCEPTION_THROWN); - } catch (Exception e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - - @Test - @PrepareForTest({ URL.class, HttpURLConnection.class }) - public void testSendRequestFormData() { - try { - given(mockConnection.getRequestProperty("content-type")).willReturn("multipart/form-data"); - - JSONObject headers = new JSONObject(); - headers.put("content-type", "multipart/form-data"); - - JSONObject params = new JSONObject(); - params.put("key", "value"); - - String response = httpUtility.sendRequest("GET", url, params, headers); - Assert.assertEquals(expected, response); - } catch (IOException e) { - fail(INVALID_EXCEPTION_THROWN); - } catch (SkyflowException e) { - fail(INVALID_EXCEPTION_THROWN); - } catch (Exception e) { - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest({ URL.class, HttpURLConnection.class }) - public void testSendRequestFormURLEncoded() { - try { - given(mockConnection.getRequestProperty("content-type")).willReturn("application/x-www-form-urlencoded"); - - JSONObject headers = new JSONObject(); - headers.put("content-type", "application/x-www-form-urlencoded"); - - JSONObject params = new JSONObject(); - params.put("key", "value"); - - String response = httpUtility.sendRequest("GET", url, params, headers); - Assert.assertEquals(expected, response); - } catch (IOException e) { - fail(INVALID_EXCEPTION_THROWN); - } catch (SkyflowException e) { - fail(INVALID_EXCEPTION_THROWN); - } catch (Exception e) { - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest({ URL.class, HttpURLConnection.class }) - public void testSendRequestError() { - try { - given(mockConnection.getResponseCode()).willReturn(500); - - String response = httpUtility.sendRequest("GET", url, null, null); - } catch (IOException e) { - fail(INVALID_EXCEPTION_THROWN); - } catch (SkyflowException e) { - Assert.assertEquals(expectedError, e.getMessage()); - } catch (Exception e) { - fail(INVALID_EXCEPTION_THROWN); - } - } -} diff --git a/v1/src/test/java/com/skyflow/common/utils/TokenUtilsTest.java b/v1/src/test/java/com/skyflow/common/utils/TokenUtilsTest.java deleted file mode 100644 index 1e242cfb..00000000 --- a/v1/src/test/java/com/skyflow/common/utils/TokenUtilsTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.common.utils; - -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import static org.junit.Assert.assertEquals; - -class InvalidTokenProvider implements TokenProvider { - - private final boolean isException; - - public InvalidTokenProvider() { - this.isException = false; - } - - public InvalidTokenProvider(boolean isException) { - this.isException = isException; - } - - @Override - public String getBearerToken() throws Exception { - if (!isException) - return "invalid_token"; - else - throw new Exception("EXCEPTION THROWN!!"); - } -} - -class InvalidTokenProvider2 implements TokenProvider { - @Override - public String getBearerToken() throws Exception { - return "a.b.c"; - } -} - -@RunWith(PowerMockRunner.class) -@PrepareForTest -public class TokenUtilsTest { - - TokenUtils tokenUtils = new TokenUtils(); - - @Test - public void testInvalidGetBearerToken() { - try { - String token = tokenUtils.getBearerToken(new InvalidTokenProvider()); - } catch (SkyflowException e) { - assertEquals(e.getMessage(), ErrorCode.InvalidBearerToken.getDescription()); - } - } - - @Test - @PrepareForTest - public void testInvalidGetBearerToken2() { - try { - String token = tokenUtils.getBearerToken(new InvalidTokenProvider2()); - } catch (SkyflowException e) { - assertEquals(e.getMessage(), ErrorCode.InvalidBearerToken.getDescription()); - } - } - - @Test - public void testIsTokenValid() { - try { - String token = System.getProperty("TEST_EXPIRED_TOKEN"); - assertEquals(false, TokenUtils.isTokenValid(token)); - } catch (SkyflowException e) { - throw new RuntimeException(e); - } - } - - @Test - public void testGetBearerTokenException() { - try { - String token = tokenUtils.getBearerToken(new InvalidTokenProvider(true)); - } catch (SkyflowException e) { - assertEquals(e.getMessage(), "EXCEPTION THROWN!!"); - } - } -} diff --git a/v1/src/test/java/com/skyflow/common/utils/TokenUtilsValidTokenTest.java b/v1/src/test/java/com/skyflow/common/utils/TokenUtilsValidTokenTest.java deleted file mode 100644 index 75623fb7..00000000 --- a/v1/src/test/java/com/skyflow/common/utils/TokenUtilsValidTokenTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.skyflow.common.utils; - -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import org.apache.commons.codec.binary.Base64; -import org.json.simple.JSONObject; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import static org.junit.Assert.assertEquals; - -class ValidTokenProvider implements TokenProvider { - - @Override - public String getBearerToken() throws Exception { - return "aa.valid_token.dd"; - } -} -class InvalidBearerTokenProvider implements TokenProvider { - - @Override - public String getBearerToken() throws Exception { - return "aa.invalid_token.dd"; - } -} - -class MockDataProvider { - - public byte[] returnValidDecodeBytes(){ - JSONObject validJson = new JSONObject(); - validJson.put("exp", (System.currentTimeMillis()+3000) / 1000); - byte[] encodedBytes = Base64.encodeBase64(validJson.toJSONString().getBytes()); - return Base64.decodeBase64(encodedBytes); - - } - public byte[] returnInValidDecodeBytes(){ - JSONObject expiredJson = new JSONObject(); - expiredJson.put("exp", (System.currentTimeMillis()-3000) / 1000); - byte[] encodedByte = Base64.encodeBase64(expiredJson.toJSONString().getBytes()); - return Base64.decodeBase64(encodedByte); - - } -} - - -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "org.apache.commons.codec.binary.Base64") -public class TokenUtilsValidTokenTest { - - @Before - public void init(){ - MockDataProvider dd = new MockDataProvider(); - byte[] validDecodeBytes = dd.returnValidDecodeBytes(); - byte[] inValidDecodeBytes = dd.returnInValidDecodeBytes(); - PowerMockito.mockStatic(Base64.class); - PowerMockito.when(Base64.decodeBase64("valid_token")).thenReturn(validDecodeBytes); - PowerMockito.when(Base64.decodeBase64("invalid_token")).thenReturn(inValidDecodeBytes); - } - @Test - public void testValidToken() { - try { - TokenUtils tokenUtils = new TokenUtils(); - String token = tokenUtils.getBearerToken(new ValidTokenProvider()); - assertEquals(token,"aa.valid_token.dd"); - String secondToken = tokenUtils.getBearerToken(new ValidTokenProvider()); - assertEquals(secondToken,"aa.valid_token.dd"); - } catch (SkyflowException e) { - Assert.fail("Should not throw EXCEPTION !!"); - } - } - - @Test - public void testInValidToken() { - try { - TokenUtils tokenUtils = new TokenUtils(); - String token = tokenUtils.getBearerToken(new InvalidBearerTokenProvider()); - Assert.fail("should throw execution"); - } catch (SkyflowException e) { - assertEquals(e.getMessage(), ErrorCode.BearerTokenExpired.getDescription()); - - } - } -} diff --git a/v1/src/test/java/com/skyflow/common/utils/ValidatorsTest.java b/v1/src/test/java/com/skyflow/common/utils/ValidatorsTest.java deleted file mode 100644 index 52abcc15..00000000 --- a/v1/src/test/java/com/skyflow/common/utils/ValidatorsTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.skyflow.common.utils; - - -import com.skyflow.entities.GetOptions; -import com.skyflow.entities.GetRecordInput; -import com.skyflow.entities.RedactionType; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.skyflow.common.utils.TokenUtils") -public class ValidatorsTest { - private static String tableName = null; - private static String columnName = null; - private static String[] columnValue = new String[1]; - private static String[] ids = new String[1]; - private static String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; - - @BeforeClass - public static void setup() throws SkyflowException { - PowerMockito.mockStatic(TokenUtils.class); - PowerMockito.when(TokenUtils.isTokenValid("valid_token")).thenReturn(true); - PowerMockito.when(TokenUtils.isTokenValid("not_a_valid_token")).thenReturn(false); - - tableName = "account_details"; - columnName = "card_number"; - columnValue[0] = "123451234554321"; - ids[0] = "123451234554321"; - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void validateGetRequestRecordValidTest() { - //column values with redaction - GetRecordInput recordInput = new GetRecordInput(); - - recordInput.setTable(tableName); - recordInput.setColumnValues(columnValue); - recordInput.setColumnName(columnName); - recordInput.setRedaction(RedactionType.PLAIN_TEXT); - try { - Validators.validateGetRequestRecord(recordInput, new GetOptions(false)); - } catch (SkyflowException exception) { - exception.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void validateGetRequestRecordValidIdTest() { - //Id values with redaction - - GetRecordInput recordInput = new GetRecordInput(); - recordInput.setTable(tableName); - recordInput.setIds(ids); - recordInput.setRedaction(RedactionType.PLAIN_TEXT); - try { - Validators.validateGetRequestRecord(recordInput, new GetOptions(false)); - } catch (SkyflowException exception) { - exception.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - // missing redaction when token is false - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void validateGetRequestRecordMisiingRedaction() { - //Id values with redaction - - GetRecordInput recordInput = new GetRecordInput(); - recordInput.setTable(tableName); - recordInput.setIds(ids); - try { - Validators.validateGetRequestRecord(recordInput, new GetOptions(false)); - } catch (SkyflowException exception) { - Assert.assertTrue(ErrorCode.MissingRedaction.getDescription().contains(exception.getMessage())); - exception.printStackTrace(); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void validateGetRequestRecordValidIdTokenTrueTest() throws SkyflowException { - //Id values with redaction - - GetRecordInput recordInput = new GetRecordInput(); - recordInput.setTable(tableName); - recordInput.setIds(ids); - try { - Validators.validateGetRequestRecord(recordInput, new GetOptions(true)); - } catch (SkyflowException exception) { - exception.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void validateGetRequestRecordIdRedactionTokenTest() throws SkyflowException { - //Id values with redaction - - GetRecordInput recordInput = new GetRecordInput(); - recordInput.setTable(tableName); - recordInput.setIds(ids); - recordInput.setRedaction(RedactionType.PLAIN_TEXT); - - try { - Validators.validateGetRequestRecord(recordInput, new GetOptions(true)); - } catch (SkyflowException e) { - Assert.assertTrue(ErrorCode.RedactionWithTokenNotSupported.getDescription().contains(e.getMessage())); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void validateGetRequestRecordColumnRedactionTokenTest() { - //Id values with redaction - GetRecordInput recordInput = new GetRecordInput(); - recordInput.setTable(tableName); - recordInput.setColumnName(columnName); - recordInput.setColumnValues(columnValue); - recordInput.setRedaction(RedactionType.PLAIN_TEXT); - - try { - Validators.validateGetRequestRecord(recordInput, new GetOptions(true)); - } catch (SkyflowException e) { - Assert.assertTrue(ErrorCode.TokensGetColumnNotSupported.getDescription().contains(e.getMessage())); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void validateGetRecordColumnNameIDSBothSpecified() { - GetRecordInput recordInput = new GetRecordInput(); - recordInput.setTable(tableName); - recordInput.setIds(ids); - recordInput.setColumnName(columnName); - recordInput.setColumnValues(columnValue); - recordInput.setRedaction(RedactionType.PLAIN_TEXT); - - try { - Validators.validateGetRequestRecord(recordInput, new GetOptions(false)); - } catch (SkyflowException e) { - Assert.assertTrue(ErrorCode.SkyflowIdAndColumnNameBothSpecified.getDescription().contains(e.getMessage())); - } - } - @Test - public void getOptionsTest(){ - GetOptions options = new GetOptions(); - Assert.assertFalse(options.getOptionToken()); - } - @Test - public void getOptionsTestWhenTokenTrue(){ - GetOptions options = new GetOptions(true); - Assert.assertTrue(options.getOptionToken()); - } - -} diff --git a/v1/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTest.java b/v1/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTest.java deleted file mode 100644 index e78501e0..00000000 --- a/v1/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTest.java +++ /dev/null @@ -1,275 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.serviceaccount.util; - -import com.skyflow.Configuration; -import com.skyflow.common.utils.Helpers; -import com.skyflow.common.utils.HttpUtility; -import com.skyflow.entities.LogLevel; -import com.skyflow.entities.ResponseToken; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; - -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.junit.Assert; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.net.URL; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility"}) -public class BearerTokenTest { - - private final String VALID_CREDENTIALS_FILE_PATH = "./credentials.json"; - - @Test - public void testEmptyFilePath() { - Configuration.setLogLevel(LogLevel.DEBUG); - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File("")) - .build(); - try { - token.getBearerToken(); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), ErrorCode.EmptyFilePath.getDescription()); - } - } - - @Test - public void testNullFile() { - Configuration.setLogLevel(LogLevel.DEBUG); - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials((File) null) - .build(); - try { - token.getBearerToken(); - - } catch (SkyflowException exception) { - assertEquals(ErrorCode.EmptyJSONString.getDescription(), exception.getMessage()); - } - } - - @Test - public void testInvalidFileContent() { - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File("./src/test/resources/invalidCredentials.json")) - .build(); - try { - token.getBearerToken(); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), ErrorCode.InvalidClientID.getDescription()); - } - - } - - @Test - public void testFileNotFound() { - String fileNotFoundPath = "./src/test/resources/nofile.json"; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(fileNotFoundPath)) - .build(); - try { - token.getBearerToken(); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), - Helpers.parameterizedString(ErrorCode.InvalidCredentialsPath.getDescription(), fileNotFoundPath)); - } - } - - @Test - public void testFiledIsNotJsonFile() { - String notJsonFilePath = "./src/test/resources/notJson.txt"; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(notJsonFilePath)) - .build(); - try { - token.getBearerToken(); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), - Helpers.parameterizedString(ErrorCode.InvalidJsonFormat.getDescription(), notJsonFilePath)); - } - } - - @Test - public void testEmptyString() { - Configuration.setLogLevel(LogLevel.DEBUG); - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials("") - .build(); - try { - token.getBearerToken(); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), ErrorCode.EmptyFilePath.getDescription()); - } - } - - @Test - public void testNullString() { - Configuration.setLogLevel(LogLevel.DEBUG); - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials((String) null) - .build(); - try { - token.getBearerToken(); - - } catch (SkyflowException exception) { - assertEquals(ErrorCode.EmptyJSONString.getDescription(), exception.getMessage()); - } - } - - @Test - public void testInvalidString() { - String creds = "key:'not_a_json'"; - Configuration.setLogLevel(LogLevel.DEBUG); - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(creds) - .build(); - try { - token.getBearerToken(); - } catch (SkyflowException exception) { - assertEquals(ErrorCode.InvalidJSONStringFormat.getDescription(), exception.getMessage()); - } - } - - @Test - public void testInvalidKeyId() { - String creds = "{\"clientID\":\"test_client_ID\"}"; - Configuration.setLogLevel(LogLevel.DEBUG); - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(creds) - .build(); - try { - token.getBearerToken(); - } catch (SkyflowException exception) { - assertEquals(ErrorCode.InvalidKeyID.getDescription(), exception.getMessage()); - } - } - - @Test - public void testInvalidTokenURI() { - String creds = "{\"clientID\":\"test_client_ID\",\"keyID\":\"test_key_id\"}"; - Configuration.setLogLevel(LogLevel.DEBUG); - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(creds) - .build(); - try { - token.getBearerToken(); - } catch (SkyflowException exception) { - assertEquals(ErrorCode.InvalidTokenURI.getDescription(), exception.getMessage()); - } - } - - @Test - public void testEmptyContext() { - Configuration.setLogLevel(LogLevel.DEBUG); - String creds = System.getProperty("TEST_CREDENTIALS_FILE_STRING_WITH_CONTEXT"); - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(creds) - .setCtx("") - .build(); - try { - token.getBearerToken(); - } catch (SkyflowException exception) { - assertEquals(ErrorCode.EmptyContext.getDescription(), exception.getMessage()); - } - } - - @Test - public void testEmptyRoleProvided() { - Configuration.setLogLevel(LogLevel.DEBUG); - String creds = System.getProperty("TEST_CREDENTIALS_FILE_STRING_WITH_CONTEXT"); - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(creds) - .setCtx("abcd") - .setRoles(new String[] { "" }) - .build(); - try { - token.getBearerToken(); - } catch (SkyflowException exception) { - assertEquals(ErrorCode.IncorrectRole.getDescription(), exception.getMessage()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility"}) - public void testValidWithContextString() { - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"accessToken\":\"valid.bearer.token\",\"tokenType\":\"Bearer\"}"; - try { - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(VALID_CREDENTIALS_FILE_PATH)) - .setCtx("abc") - .build(); - - String bearerToken = token.getBearerToken(); - assertEquals(bearerToken,"valid.bearer.token"); - } catch (SkyflowException | IOException exception) { - assertNull(exception); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility"}) - public void testValidWithRoles() { - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"accessToken\":\"valid.bearer.token\",\"tokenType\":\"Bearer\"}"; - try { - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(VALID_CREDENTIALS_FILE_PATH)) - .setCtx("abc") - .setRoles(new String[]{"role_id"}) - .build(); - - String bearerToken = token.getBearerToken(); - assertEquals(bearerToken,"valid.bearer.token"); - } catch (SkyflowException | IOException exception) { - assertNull(exception); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility"}) - public void testValidWithContextFromCreds() { - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"accessToken\":\"valid.bearer.token\",\"tokenType\":\"Bearer\"}"; - try { - JSONParser parser = new JSONParser(); - Object obj = parser.parse(new FileReader(VALID_CREDENTIALS_FILE_PATH)); - JSONObject saCreds = (JSONObject) obj; - - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(saCreds.toJSONString()) - .setCtx("abc") - .setRoles(new String[]{"role_id"}) - .build(); - - String bearerToken = token.getBearerToken(); - assertEquals(bearerToken,"valid.bearer.token"); - } catch (SkyflowException | IOException | ParseException exception) { - assertNull(exception); - } - } - - -} diff --git a/v1/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokenResponseTest.java b/v1/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokenResponseTest.java deleted file mode 100644 index b75cb031..00000000 --- a/v1/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokenResponseTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.skyflow.serviceaccount.util; - -import com.skyflow.errors.ErrorCode; -import org.junit.Assert; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class SignedDataTokenResponseTest { - @Test - public void testSignedDataTokenResponse() { - String response = "{dataToken: token,signedDataToken: signed_token}"; - SignedDataTokenResponse res = new SignedDataTokenResponse("token", "signed_token"); - Assert.assertNotNull(res); - assertEquals(response,res.toString()); - assertEquals(res.dataToken, "token"); - assertEquals(res.signedDataToken, "signed_token"); - } -} diff --git a/v1/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTest.java b/v1/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTest.java deleted file mode 100644 index 00e74383..00000000 --- a/v1/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTest.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.serviceaccount.util; - -import com.skyflow.Configuration; -import com.skyflow.common.utils.Helpers; -import com.skyflow.entities.LogLevel; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.junit.Assert; -import org.junit.Test; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.List; - -import static org.junit.Assert.*; - -public class SignedDataTokensTest { - - private final String VALID_CREDENTIALS_FILE_PATH = "./credentials.json"; - - @Test - public void testEmptyFilePath() { - Configuration.setLogLevel(LogLevel.DEBUG); - SignedDataTokens token = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(new File("")) - .build(); - try { - token.getSignedDataTokens(); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), ErrorCode.EmptyFilePath.getDescription()); - } - } - - @Test - public void testNullFile() { - Configuration.setLogLevel(LogLevel.DEBUG); - SignedDataTokens token = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials((File) null) - .build(); - try { - token.getSignedDataTokens(); - - } catch (SkyflowException exception) { - assertEquals(ErrorCode.EmptyJSONString.getDescription(), exception.getMessage()); - } - } - - @Test - public void testInvalidFileContent() { - SignedDataTokens token = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(new File("./src/test/resources/invalidCredentials.json")) - .build(); - try { - token.getSignedDataTokens(); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), ErrorCode.InvalidClientID.getDescription()); - } - } - - @Test - public void testFileNotFound() { - String fileNotFoundPath = "./src/test/resources/nofile.json"; - SignedDataTokens token = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(new File(fileNotFoundPath)) - .build(); - try { - token.getSignedDataTokens(); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), - Helpers.parameterizedString(ErrorCode.InvalidCredentialsPath.getDescription(), fileNotFoundPath)); - } - } - - @Test - public void testFiledIsNotJsonFile() { - String notJsonFilePath = "./src/test/resources/notJson.txt"; - SignedDataTokens token = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(new File(notJsonFilePath)) - .build(); - try { - token.getSignedDataTokens(); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), - Helpers.parameterizedString(ErrorCode.InvalidJsonFormat.getDescription(), notJsonFilePath)); - } - } - - @Test - public void testEmptyString() { - Configuration.setLogLevel(LogLevel.DEBUG); - SignedDataTokens token = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials("") - .build(); - try { - token.getSignedDataTokens(); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), ErrorCode.EmptyFilePath.getDescription()); - } - } - - @Test - public void testNullString() { - Configuration.setLogLevel(LogLevel.DEBUG); - SignedDataTokens token = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials((String) null) - .build(); - try { - token.getSignedDataTokens(); - - } catch (SkyflowException exception) { - assertEquals(ErrorCode.EmptyJSONString.getDescription(), exception.getMessage()); - } - } - - @Test - public void testInvalidString() { - String creds = "key:'not_a_json'"; - Configuration.setLogLevel(LogLevel.DEBUG); - SignedDataTokens token = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(creds) - .build(); - try { - token.getSignedDataTokens(); - } catch (SkyflowException exception) { - assertEquals(ErrorCode.InvalidJSONStringFormat.getDescription(), exception.getMessage()); - } - } - - @Test - public void testInvalidKeyId() { - String creds = "{\"clientID\":\"test_client_ID\"}"; - Configuration.setLogLevel(LogLevel.DEBUG); - SignedDataTokens token = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(creds) - .build(); - try { - token.getSignedDataTokens(); - } catch (SkyflowException exception) { - assertEquals(ErrorCode.InvalidKeyID.getDescription(), exception.getMessage()); - } - } - - @Test - public void testNoDataTokenProvided() { - String creds = System.getProperty("TEST_CREDENTIALS_FILE_STRING"); - SignedDataTokens token = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(creds) - .setDataTokens(new String[] {}).build(); - try { - assertTrue(token.getSignedDataTokens().isEmpty()); - - } catch (SkyflowException exception) { - System.out.println(exception); - } - } - - @Test - public void testValidSignedTokenWithTTL() { - try { - JSONParser parser = new JSONParser(); - Object obj = parser.parse(new FileReader(VALID_CREDENTIALS_FILE_PATH)); - JSONObject saCreds = (JSONObject) obj; - SignedDataTokens token = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(saCreds.toJSONString()) - .setCtx("abc") - .setTimeToLive(30) - .setDataTokens(new String[] { "5230-0316-0674-5728" }).build(); - List signedToken = token.getSignedDataTokens(); - Assert.assertNotNull(signedToken); - - } catch (SkyflowException | IOException | ParseException exception) { - assertNull(exception); - } - } - - @Test - public void testValidSignedToken() { - try { - SignedDataTokens token = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(new File(VALID_CREDENTIALS_FILE_PATH)) - .setCtx("abc") - .setDataTokens(new String[] { "5230-0316-0674-5728" }).build(); - List signedToken = token.getSignedDataTokens(); - Assert.assertNotNull(signedToken); - - } catch (SkyflowException exception) { - assertNull(exception); - } - } - -} diff --git a/v1/src/test/java/com/skyflow/serviceaccount/util/TokenTest.java b/v1/src/test/java/com/skyflow/serviceaccount/util/TokenTest.java deleted file mode 100644 index 19eee9e1..00000000 --- a/v1/src/test/java/com/skyflow/serviceaccount/util/TokenTest.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.serviceaccount.util; - -import com.skyflow.Configuration; -import com.skyflow.common.utils.Helpers; -import com.skyflow.common.utils.HttpUtility; -import com.skyflow.common.utils.TokenUtils; -import com.skyflow.entities.LogLevel; -import com.skyflow.entities.ResponseToken; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.io.FileReader; -import java.io.IOException; -import java.net.URL; -import java.nio.file.Paths; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) -public class TokenTest { - // replace the path, when running local, do not commit - private final String VALID_CREDENTIALS_FILE_PATH = "./credentials.json"; - - private static String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; - @Test - public void testInvalidFilePath() { - try { - Configuration.setLogLevel(LogLevel.DEBUG); - Token.GenerateToken(""); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), ErrorCode.EmptyFilePath.getDescription()); - } - - } - - @Test - public void testNullFilePath() { - try { - Token.generateBearerToken(""); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), ErrorCode.EmptyFilePath.getDescription()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInvalidFileContent() { - try { - Token.generateBearerToken(Paths.get("./src/test/resources/invalidCredentials.json").toString()); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), ErrorCode.InvalidClientID.getDescription()); - } - - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testFileNotFoundPath() { - String fileNotFoundPath = "./src/test/resources/nofile.json"; - try { - Token.generateBearerToken(Paths.get(fileNotFoundPath).toString()); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), Helpers.parameterizedString(ErrorCode.InvalidCredentialsPath.getDescription(), fileNotFoundPath)); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testFiledNotJsonFile() { - String notJsonFilePath = "./src/test/resources/notJson.txt"; - try { - Token.generateBearerToken(Paths.get(notJsonFilePath).toString()); - } catch (SkyflowException exception) { - assertEquals(exception.getMessage(), Helpers.parameterizedString(ErrorCode.InvalidJsonFormat.getDescription(), notJsonFilePath)); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testCallingDeprecatedMethod() { - try { - PowerMockito.mockStatic(TokenUtils.class); - PowerMockito.when(TokenUtils.isTokenValid("a.b.c")).thenReturn(true); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"accessToken\":\"a.b.c\",\"tokenType\":\"Bearer\"}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - ResponseToken token = Token.GenerateToken(VALID_CREDENTIALS_FILE_PATH); - Assert.assertNotNull(token.getAccessToken()); - Assert.assertEquals("Bearer", token.getTokenType()); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - Assert.assertNull(skyflowException); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testValidFileContent() { - try { - PowerMockito.mockStatic(TokenUtils.class); - PowerMockito.when(TokenUtils.isTokenValid("a.b.c")).thenReturn(true); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"accessToken\":\"a.b.c\",\"tokenType\":\"Bearer\"}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - ResponseToken token = Token.generateBearerToken(VALID_CREDENTIALS_FILE_PATH); - Assert.assertNotNull(token.getAccessToken()); - Assert.assertEquals("Bearer", token.getTokenType()); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - Assert.assertNull(skyflowException); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testValidString() { - try { - JSONParser parser = new JSONParser(); - Object obj = parser.parse(new FileReader(VALID_CREDENTIALS_FILE_PATH)); - JSONObject saCreds = (JSONObject) obj; - - PowerMockito.mockStatic(TokenUtils.class); - PowerMockito.when(TokenUtils.isTokenValid("a.b.c")).thenReturn(true); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"accessToken\":\"a.b.c\",\"tokenType\":\"Bearer\"}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - - ResponseToken token = Token.generateBearerTokenFromCreds(saCreds.toJSONString()); - Assert.assertNotNull(token.getAccessToken()); - Assert.assertEquals("Bearer", token.getTokenType()); - } catch (SkyflowException | IOException | ParseException skyflowException) { - skyflowException.printStackTrace(); - Assert.assertNull(skyflowException); - } - } - - @Test - public void testEmptyString() { - try { - ResponseToken token = Token.generateBearerTokenFromCreds(""); - } catch (SkyflowException exception) { - assertEquals(ErrorCode.EmptyJSONString.getDescription(), exception.getMessage()); - } - } - - @Test - public void testNullString() { - try { - ResponseToken token = Token.generateBearerTokenFromCreds(null); - } catch (SkyflowException exception) { - assertEquals(ErrorCode.EmptyJSONString.getDescription(), exception.getMessage()); - } - } - - @Test - public void testInvalidString() { - String creds = "key:'not_a_json'"; - try { - ResponseToken token = Token.generateBearerTokenFromCreds(creds); - } catch (SkyflowException exception) { - assertEquals(ErrorCode.InvalidJSONStringFormat.getDescription(), exception.getMessage()); - } - } - - @Test - public void testInvalidKeyId() { - String creds = "{\"clientID\":\"test_client_ID\"}"; - try { - ResponseToken token = Token.generateBearerTokenFromCreds(creds); - } catch (SkyflowException exception) { - assertEquals(ErrorCode.InvalidKeyID.getDescription(), exception.getMessage()); - } - } - - @Test - public void testInvalidTokenURI() { - String creds = "{\"clientID\":\"test_client_ID\",\"keyID\":\"test_key_id\"}"; - try { - ResponseToken token = Token.generateBearerTokenFromCreds(creds); - } catch (SkyflowException exception) { - assertEquals(ErrorCode.InvalidTokenURI.getDescription(), exception.getMessage()); - } - } - - @Test - public void testIsValidForEmptyToken() { - String token = ""; - assertEquals(false, Token.isValid(token)); - } - - @Test - public void testIsValidForInvalidToken() { - String token = "invalidToken"; - assertEquals(false, Token.isValid(token)); - } - - @Test - public void testIsExpiredForExpiredToken() { - String token = System.getProperty("TEST_EXPIRED_TOKEN"); - assertEquals(true, Token.isExpired(token)); - } - -} \ No newline at end of file diff --git a/v1/src/test/java/com/skyflow/vault/DeleteMethodTest.java b/v1/src/test/java/com/skyflow/vault/DeleteMethodTest.java deleted file mode 100644 index 9ad439e8..00000000 --- a/v1/src/test/java/com/skyflow/vault/DeleteMethodTest.java +++ /dev/null @@ -1,421 +0,0 @@ -package com.skyflow.vault; - -import com.skyflow.common.utils.HttpUtility; -import com.skyflow.common.utils.TokenUtils; -import com.skyflow.common.utils.Validators; -import com.skyflow.entities.DeleteRecordInput; -import com.skyflow.entities.RedactionType; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.io.IOException; -import java.net.URL; - -import static org.junit.Assert.*; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.skyflow.common.utils.TokenUtils") -public class DeleteMethodTest { - private static String vaultID = null; - private static String vaultURL = null; - private static String skyflowId = null; - private static String token = null; - private static String tableName = null; - private static String columnName = null; - private static String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; - - - @BeforeClass - public static void setup() throws SkyflowException { - PowerMockito.mockStatic(TokenUtils.class); - PowerMockito.when(TokenUtils.isTokenValid("valid_token")).thenReturn(true); - PowerMockito.when(TokenUtils.isTokenValid("not_a_valid_token")).thenReturn(false); - - vaultID = "vault123"; - vaultURL = "https://test.com"; - skyflowId = "skyflowId123"; - token = "token123"; - tableName = "pii_fields"; - columnName = "first_name"; - } - @Test - public void testValidInput() { - DeleteRecordInput validInput = new DeleteRecordInput(); - validInput.setTable("users"); - validInput.setId("12345"); - - try { - Validators.validateDeleteBySkyflowId(validInput); - } catch (SkyflowException e) { - fail("Unexpected exception thrown"); - } - } - @Test - public void testValidInputCase2() { - DeleteRecordInput validInput = new DeleteRecordInput(); - validInput.setTable(""); - validInput.setId("12345"); - - try { - Validators.validateDeleteBySkyflowId(validInput); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.InvalidTable.getDescription(), e.getMessage()); - } - } - @Test - public void testValidInputCase3() { - DeleteRecordInput validInput = new DeleteRecordInput(); - validInput.setTable(null); - validInput.setId("12345"); - - try { - Validators.validateDeleteBySkyflowId(validInput); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.InvalidTable.getDescription(), e.getMessage()); - } - } - @Test - public void testValidInputCase4() { - DeleteRecordInput validInput = new DeleteRecordInput(); - validInput.setTable("table"); - validInput.setId(null); - - try { - Validators.validateDeleteBySkyflowId(validInput); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.InvalidId.getDescription(), e.getMessage()); - } - } - @Test - public void testValidInputInvalidInput() { - DeleteRecordInput validInput = new DeleteRecordInput(); - validInput.setTable("table"); - validInput.setId(""); - - try { - Validators.validateDeleteBySkyflowId(validInput); - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.InvalidId.getDescription(), e.getMessage()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testDeleteEmptyRecords() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - records.put("records", recordsArray); - JSONObject response = skyflowClient.delete(records); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.EmptyRecords.getDescription(), skyflowException.getMessage()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testDeleteEmptyRecordsCase2() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - records.put("", recordsArray); - JSONObject response = skyflowClient.delete(records); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidDeleteInput.getDescription(), skyflowException.getMessage()); - } - } - @Test - public void testDeleteMethodErrorWhenNullRecordsArePassed() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - records.put("records", null); - - JSONObject response = skyflowClient.delete(records); - - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.EmptyRecords.getDescription(), e.getMessage()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.TokenUtils"}) - public void testDeleteMethodErrorWhenNullTableNameIsPassed() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - record.put("table", null); - - recordsArray.add(record); - records.put("records", recordsArray); - - JSONObject response = skyflowClient.delete(records); - - } catch (SkyflowException skyflowException) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) skyflowException.getData().get("errors")).get(0))).get("error"); - Assert.assertEquals(ErrorCode.InvalidTable.getDescription(), error.get("description")); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testDeleteEmptyRecordsCase3() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONObject record = new JSONObject(); - - JSONArray recordsArray = new JSONArray(); - recordsArray.add(record); - record.put("table", "name"); - records.put("records", recordsArray); - JSONObject response = skyflowClient.delete(records); - } catch (SkyflowException skyflowException) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) skyflowException.getData().get("errors")).get(0))).get("error"); - Assert.assertEquals(ErrorCode.InvalidId.getDescription(), error.get("description")); - } - - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testDeleteMethodErrorWhenWrongTableNameIsPassed() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - record.put("id", "skyflowid"); - record.put("table", "invalidTable"); - - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"error\":{\"grpc_code\":13,\"http_code\":500,\"message\":\"Couldn't load data\",\"http_status\":\"Internal Server Error\"}}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new SkyflowException(500, mockResponse)); - - JSONObject response = skyflowClient.delete(records); - - } catch (SkyflowException e) { - JSONArray errors = (JSONArray) e.getData().get("errors"); - Assert.assertEquals(1, errors.size()); - } catch (IOException e) { - e.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testDeleteMethodPartialError() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject firstRecord = new JSONObject(); - firstRecord.put("id", "id1"); - firstRecord.put("table", "table1"); - - - JSONObject secondRecord = new JSONObject(); - secondRecord.put("id", "id2"); - secondRecord.put("table", "invalidTable1"); - - JSONObject thirdRecord = new JSONObject(); - thirdRecord.put("id", "id3"); - thirdRecord.put("table", "invalidTable2"); - - - recordsArray.add(firstRecord); - recordsArray.add(secondRecord); - recordsArray.add(thirdRecord); - records.put("records", recordsArray); - - String firstRequestUrl = "https://test.com/v1/vaults/vault123/table1/id1"; - String secondRequestUrl = "https://test.com/v1/vaults/vault123/invalidTable1/id2"; - String thirdRequestUrl = "https://test.com/v1/vaults/vault123/invalidTable2/id3"; - - PowerMockito.mockStatic(HttpUtility.class); - String mockValidResponse = "{\"skyflow_id\":\"id1\",\"deleted\":\"true\"}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.eq(new URL(firstRequestUrl)), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenReturn(mockValidResponse); - - String mockInvalidResponse1 = "{\"error\":{\"http_code\":404,\"http_status\":\"Not Found\",\"details\":[],\"message\":\"No Records Found - requestId: 968fc4a8-53ef-92fb-9c0d-3393d3361790\",\"grpc_code\":5}}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.eq(new URL(secondRequestUrl)), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new SkyflowException(500, mockInvalidResponse1)); - - String mockInvalidResponse2 = "{\"error\":{\"http_code\":404,\"http_status\":\"Not Found\",\"details\":[],\"message\":\"No Records Found - requestId: 968fc4a8-53ef-92fb-9c0d-3393d3361790\",\"grpc_code\":5}}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.eq(new URL(thirdRequestUrl)), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new SkyflowException(500, mockInvalidResponse2)); - - JSONObject response = skyflowClient.delete(records); - - } catch (SkyflowException e) { - JSONObject partialError = e.getData(); - Assert.assertTrue(partialError.containsKey("records")); - Assert.assertTrue(partialError.containsKey("errors")); - - JSONArray errors = (JSONArray) e.getData().get("errors"); - Assert.assertEquals(2, errors.size()); - } catch (IOException e) { - e.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testDeleteMethodSuccess() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - record.put("table", tableName); - record.put("id", "id1"); - - - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"skyflow_id\":\"id1\",\"deleted\":\"true\"}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenReturn(mockResponse); - JSONObject response = skyflowClient.delete(records); - JSONArray responseRecords = (JSONArray) response.get("records"); - Assert.assertEquals(1, responseRecords.size()); - Assert.assertEquals("id1", ((JSONObject) responseRecords.get(0)).get("skyflow_id")); - Assert.assertEquals("true", ((JSONObject) responseRecords.get(0)).get("deleted")); - - } catch (SkyflowException | IOException exception) { - exception.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testDeleteMethodParseException() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - record.put("table", tableName); - record.put("id", "id1"); - - - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"skyflow_id\":\"id1\",\"deleted\":\"true\"}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenReturn(mockResponse); - JSONObject response = skyflowClient.delete(records); - - } catch (SkyflowException e) { - String error = e.getMessage(); - assertEquals(ErrorCode.ThreadExecutionException.getDescription(), error); - } catch (IOException exception) { - exception.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodIOException() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - record.put("table", tableName); - record.put("id", "id1"); - - - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"skyflow_id\":\"id1\",\"deleted\":\"true\"}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new IOException()); - - JSONObject response = skyflowClient.delete(records); - } catch (SkyflowException e) { - String error = e.getMessage(); - assertEquals(ErrorCode.ThreadExecutionException.getDescription(), error); - } catch (IOException exception) { - exception.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } -} diff --git a/v1/src/test/java/com/skyflow/vault/GetMethodTest.java b/v1/src/test/java/com/skyflow/vault/GetMethodTest.java deleted file mode 100644 index 2477cbbf..00000000 --- a/v1/src/test/java/com/skyflow/vault/GetMethodTest.java +++ /dev/null @@ -1,870 +0,0 @@ -package com.skyflow.vault; - -import com.skyflow.common.utils.HttpUtility; -import com.skyflow.common.utils.TokenUtils; -import com.skyflow.entities.GetOptions; -import com.skyflow.entities.GetRecordInput; -import com.skyflow.entities.RedactionType; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.io.IOException; -import java.net.URL; - -import static org.junit.Assert.assertEquals; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.skyflow.common.utils.TokenUtils") -public class GetMethodTest { - private static String vaultID = null; - private static String vaultURL = null; - private static String skyflowId = null; - private static String token = null; - private static String tableName = null; - private static String columnName = null; - private static String columnValue = null; - private static String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; - - @BeforeClass - public static void setup() throws SkyflowException { - PowerMockito.mockStatic(TokenUtils.class); - PowerMockito.when(TokenUtils.isTokenValid("valid_token")).thenReturn(true); - PowerMockito.when(TokenUtils.isTokenValid("not_a_valid_token")).thenReturn(false); - - vaultID = "vault123"; - vaultURL = "https://test.com"; - skyflowId = "skyflowId123"; - token = "token123"; - tableName = "account_details"; - columnName = "bank_account_number"; - columnValue = "123451234554321"; - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodSuccess() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray values = new JSONArray(); - values.add(columnValue); - - record.put("table", tableName); - record.put("columnName", columnName); - record.put("columnValues", values); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"records\":[{\"fields\":{\"bank_account_number\":\"123451234554321\",\"pin_code\":\"121342\",\"name\":\"vivek jain\",\"skyflow_id\":\"skyflowId123\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenReturn(mockResponse); - JSONObject response = skyflowClient.get(records); - JSONArray responseRecords = (JSONArray) response.get("records"); - - Assert.assertEquals(1, responseRecords.size()); - Assert.assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - Assert.assertNotNull(((JSONObject) responseRecords.get(0)).get("fields")); - - } catch (SkyflowException | IOException exception) { - exception.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - public void testGetMethodErrorWhenInvalidInputIsPassed() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - records.put("invalidRecordsKey", recordsArray); - - JSONObject response = skyflowClient.get(records); - } catch (SkyflowException skyflowException) { - Assert.assertEquals(ErrorCode.InvalidGetInput.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testGetMethodErrorWhenEmptyRecordsArePassed() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - records.put("records", recordsArray); - - JSONObject response = skyflowClient.get(records); - - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.EmptyRecords.getDescription(), e.getMessage()); - } - } - - @Test - public void testGetMethodErrorWhenNullRecordsArePassed() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - records.put("records", null); - - JSONObject response = skyflowClient.get(records); - - } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.EmptyRecords.getDescription(), e.getMessage()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodErrorWhenNullTableNameIsPassed() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - record.put("table", null); - - recordsArray.add(record); - records.put("records", recordsArray); - - JSONObject response = skyflowClient.get(records); - - } catch (SkyflowException skyflowException) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) skyflowException.getData().get("errors")).get(0))).get("error"); - Assert.assertEquals(ErrorCode.InvalidTable.getDescription(), error.get("description")); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodErrorWhenEmptyTableNameIsPassed() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - record.put("table", " "); - - recordsArray.add(record); - records.put("records", recordsArray); - - JSONObject response = skyflowClient.get(records); - - } catch (SkyflowException skyflowException) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) skyflowException.getData().get("errors")).get(0))).get("error"); - Assert.assertEquals(ErrorCode.InvalidTable.getDescription(), error.get("description")); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodErrorWhenWrongTableNameIsPassed() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray ids = new JSONArray(); - ids.add(skyflowId); - - record.put("ids", ids); - record.put("table", "invalidTable"); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"error\":{\"grpc_code\":13,\"http_code\":500,\"message\":\"Couldn't load data\",\"http_status\":\"Internal Server Error\"}}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new SkyflowException(500, mockResponse)); - - JSONObject response = skyflowClient.get(records); - - } catch (SkyflowException e) { - JSONArray errors = (JSONArray) e.getData().get("errors"); - Assert.assertEquals(1, errors.size()); - } catch (IOException e) { - e.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodPartialError() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject firstRecord = new JSONObject(); - JSONArray firstRecordColumnValues = new JSONArray(); - firstRecordColumnValues.add(columnValue); - firstRecord.put("table", tableName); - firstRecord.put("columnName", columnName); - firstRecord.put("columnValues", firstRecordColumnValues); - firstRecord.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - JSONObject secondRecord = new JSONObject(); - JSONArray ids = new JSONArray(); - ids.add(skyflowId); - secondRecord.put("ids", ids); - secondRecord.put("table", "invalidTable"); - secondRecord.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - JSONObject thirdRecord = new JSONObject(); - JSONArray thirdRecordColumnValues = new JSONArray(); - thirdRecordColumnValues.add(columnValue); - thirdRecord.put("table", "invalidTable"); - thirdRecord.put("columnName", columnName); - thirdRecord.put("columnValues", thirdRecordColumnValues); - thirdRecord.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - recordsArray.add(firstRecord); - recordsArray.add(secondRecord); - recordsArray.add(thirdRecord); - records.put("records", recordsArray); - - String firstRequestUrl = "https://test.com/v1/vaults/vault123/account_details?column_name=bank_account_number&column_values=123451234554321&redaction=PLAIN_TEXT"; - String secondRequestUrl = "https://test.com/v1/vaults/vault123/invalidTable?skyflow_ids=skyflowId123&redaction=PLAIN_TEXT"; - String thirdRequestUrl = "https://test.com/v1/vaults/vault123/invalidTable?column_name=bank_account_number&column_values=123451234554321&redaction=PLAIN_TEXT"; - - PowerMockito.mockStatic(HttpUtility.class); - String mockValidResponse = "{\"records\":[{\"fields\":{\"bank_account_number\":\"123455432112345\",\"pin_code\":\"123123\",\"name\":\"vivek jain\",\"id\":\"492c21a1-107f-4d10-ba2c-3482a411827d\"},\"table\":\"account_details\"}]}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.eq(new URL(firstRequestUrl)), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenReturn(mockValidResponse); - - String mockInvalidResponse1 = "{\"error\":{\"code\":500,\"description\":\"Couldn't load data - requestId: 496c3a0b-3d24-9052-bbba-28bf3f04b97d\"},\"ids\":[\"skyflowId123\"]}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.eq(new URL(secondRequestUrl)), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new SkyflowException(500, mockInvalidResponse1)); - - String mockInvalidResponse2 = "{\"error\":{\"code\":500,\"description\":\"Couldn't load data - requestId: 496c3a0b-3d24-9052-bbba-28bf3f04b97d\"},\"columnName\":\"bank_account_number\"}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.eq(new URL(thirdRequestUrl)), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new SkyflowException(500, mockInvalidResponse2)); - - JSONObject response = skyflowClient.get(records); - - } catch (SkyflowException e) { - JSONObject partialError = e.getData(); - Assert.assertTrue(partialError.containsKey("records")); - Assert.assertTrue(partialError.containsKey("errors")); - - JSONArray errors = (JSONArray) e.getData().get("errors"); - Assert.assertEquals(2, errors.size()); - } catch (IOException e) { - e.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodErrorWhenBothSkyflowIDsAndColumnDetailsArePassed() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray values = new JSONArray(); - values.add(columnValue); - - JSONArray ids = new JSONArray(); - ids.add(skyflowId); - - record.put("ids", ids); - record.put("table", tableName); - record.put("columnName", columnName); - record.put("columnValues", values); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"error\":{\"grpc_code\":13,\"http_code\":500,\"message\":\"Couldn't load data\",\"http_status\":\"Internal Server Error\"}}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new SkyflowException(500, mockResponse)); - JSONObject response = skyflowClient.get(records); - - } catch (SkyflowException e) { - JSONArray errors = (JSONArray) e.getData().get("errors"); - Assert.assertEquals(1, errors.size()); - } catch (IOException e) { - e.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodErrorWhenNeitherSkyflowIDsNorColumnDetailsArePassed() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - record.put("table", tableName); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"errors\":[{\"error\":{\"code\":400,\"description\":\"Provide either Ids or column name to get records.\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new SkyflowException(400, mockResponse)); - JSONObject response = skyflowClient.get(records); - - } catch (SkyflowException e) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) e.getData().get("errors")).get(0))).get("error"); - Assert.assertEquals(ErrorCode.MissingIdAndColumnName.getDescription(), error.get("description")); - } catch (IOException e) { - e.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodErrorWhenColumnNameIsPassedWithoutColumnValues() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - record.put("table", tableName); - record.put("columnName", columnName); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"errors\":[{\"error\":{\"code\":400,\"description\":\"Column Values can not be empty when Column Name is specified.\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new SkyflowException(500, mockResponse)); - JSONObject response = skyflowClient.get(records); - - } catch (SkyflowException e) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) e.getData().get("errors")).get(0))).get("error"); - Assert.assertEquals(ErrorCode.MissingRecordColumnValue.getDescription(), error.get("description")); - } catch (IOException e) { - e.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodErrorWhenColumnValuesArePassedWithoutColumnName() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray values = new JSONArray(); - values.add(columnValue); - - record.put("table", tableName); - record.put("columnValues", values); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"errors\":[{\"error\":{\"code\":400,\"description\":\"Column Name can not be empty when Column Values are specified.\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new SkyflowException(500, mockResponse)); - JSONObject response = skyflowClient.get(records); - - } catch (SkyflowException e) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) e.getData().get("errors")).get(0))).get("error"); - Assert.assertEquals(ErrorCode.MissingRecordColumnName.getDescription(), error.get("description")); - } catch (IOException e) { - e.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodIOException() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray values = new JSONArray(); - values.add(columnValue); - - record.put("table", tableName); - record.put("columnName", columnName); - record.put("columnValues", values); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "a{\"records\":[{\"fields\":{\"bank_account_number\":\"123451234554321\",\"pin_code\":\"121342\",\"name\":\"vivek jain\",\"skyflow_id\":\"skyflowId123\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new IOException()); - - JSONObject response = skyflowClient.get(records); - - } catch (SkyflowException e) { - String error = e.getMessage(); - assertEquals(ErrorCode.ThreadExecutionException.getDescription(), error); - } catch (IOException exception) { - exception.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodParseException() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray values = new JSONArray(); - values.add(columnValue); - - record.put("table", tableName); - record.put("columnName", columnName); - record.put("columnValues", values); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "a{\"records\":[{\"fields\":{\"bank_account_number\":\"123451234554321\",\"pin_code\":\"121342\",\"name\":\"vivek jain\",\"skyflow_id\":\"skyflowId123\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenReturn(mockResponse); - JSONObject response = skyflowClient.get(records); - - } catch (SkyflowException e) { - String error = e.getMessage(); - assertEquals(ErrorCode.ThreadExecutionException.getDescription(), error); - } catch (IOException exception) { - exception.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodWithNoRedactionNoToken() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray ids = new JSONArray(); - ids.add(skyflowId); - - record.put("ids", ids); - record.put("table", tableName); - - recordsArray.add(record); - records.put("records", recordsArray); - - skyflowClient.get(records); - - } catch (SkyflowException e) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) e.getData().get("errors")).get(0))).get("error"); - - JSONArray errors = (JSONArray) e.getData().get("errors"); - Assert.assertEquals(1, errors.size()); - Assert.assertEquals(error.get("description"), ErrorCode.MissingRedaction.getDescription()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodWithRedactionToken() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray ids = new JSONArray(); - ids.add(skyflowId); - - record.put("ids", ids); - record.put("table", tableName); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - recordsArray.add(record); - records.put("records", recordsArray); - - skyflowClient.get(records, new GetOptions(true)); - - } catch (SkyflowException e) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) e.getData().get("errors")).get(0))).get("error"); - - JSONArray errors = (JSONArray) e.getData().get("errors"); - Assert.assertEquals(1, errors.size()); - Assert.assertEquals(error.get("description"), ErrorCode.RedactionWithTokenNotSupported.getDescription()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodWithNoRedactionTokenForColumnValues() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray values = new JSONArray(); - values.add(columnValue); - - record.put("table", tableName); - record.put("columnName", columnName); - record.put("columnValues", values); - - recordsArray.add(record); - records.put("records", recordsArray); - - skyflowClient.get(records, new GetOptions(true)); - - } catch (SkyflowException e) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) e.getData().get("errors")).get(0))).get("error"); - - JSONArray errors = (JSONArray) e.getData().get("errors"); - Assert.assertEquals(1, errors.size()); - Assert.assertEquals(error.get("description"), ErrorCode.TokensGetColumnNotSupported.getDescription()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodWithRedactionWithTokenForColumnValues() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray values = new JSONArray(); - values.add(columnValue); - - record.put("table", tableName); - record.put("columnName", columnName); - record.put("columnValues", values); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - recordsArray.add(record); - records.put("records", recordsArray); - - - skyflowClient.get(records, new GetOptions(true)); - - } catch (SkyflowException e) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) e.getData().get("errors")).get(0))).get("error"); - - JSONArray errors = (JSONArray) e.getData().get("errors"); - Assert.assertEquals(1, errors.size()); - Assert.assertEquals(error.get("description"), ErrorCode.TokensGetColumnNotSupported.getDescription()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodWithNoRedactionNoTokenForColumnValues() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray values = new JSONArray(); - values.add(columnValue); - - record.put("table", tableName); - record.put("columnName", columnName); - record.put("columnValues", values); - - recordsArray.add(record); - records.put("records", recordsArray); - - skyflowClient.get(records); - - } catch (SkyflowException e) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) e.getData().get("errors")).get(0))).get("error"); - - JSONArray errors = (JSONArray) e.getData().get("errors"); - Assert.assertEquals(1, errors.size()); - Assert.assertEquals(error.get("description"), ErrorCode.MissingRedaction.getDescription()); - } - - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodWithNoRedactionFalseTokenForColumnValues() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray values = new JSONArray(); - values.add(columnValue); - - record.put("table", tableName); - record.put("columnName", columnName); - record.put("columnValues", values); - - recordsArray.add(record); - records.put("records", recordsArray); - - skyflowClient.get(records, new GetOptions(false)); - - } catch (SkyflowException e) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) e.getData().get("errors")).get(0))).get("error"); - - JSONArray errors = (JSONArray) e.getData().get("errors"); - Assert.assertEquals(1, errors.size()); - Assert.assertEquals(error.get("description"), ErrorCode.MissingRedaction.getDescription()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodWithNoRedactionFalseToken() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray ids = new JSONArray(); - ids.add(skyflowId); - - record.put("ids", ids); - record.put("table", tableName); - recordsArray.add(record); - records.put("records", recordsArray); - - skyflowClient.get(records, new GetOptions(false)); - - } catch (SkyflowException e) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) e.getData().get("errors")).get(0))).get("error"); - - JSONArray errors = (JSONArray) e.getData().get("errors"); - Assert.assertEquals(1, errors.size()); - Assert.assertEquals(error.get("description"), ErrorCode.MissingRedaction.getDescription()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodWithRedactionFalseTokenSuccess() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray ids = new JSONArray(); - ids.add(skyflowId); - - record.put("ids", ids); - record.put("table", tableName); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"records\":[{\"fields\":{\"bank_account_number\":\"123451234554321\",\"pin_code\":\"121342\",\"name\":\"demo\",\"skyflow_id\":\"skyflowId123\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenReturn(mockResponse); - JSONObject response = skyflowClient.get(records, new GetOptions(false)); - JSONArray responseRecords = (JSONArray) response.get("records"); - - Assert.assertEquals(1, responseRecords.size()); - Assert.assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - Assert.assertNotNull(((JSONObject) responseRecords.get(0)).get("fields")); - - } catch (SkyflowException | IOException exception) { - exception.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetMethodWithRedactionFalseTokenSuccess2() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - JSONArray values = new JSONArray(); - values.add(columnValue); - - record.put("table", tableName); - record.put("columnName", columnName); - record.put("columnValues", values); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"records\":[{\"fields\":{\"bank_account_number\":\"123451234554321\",\"pin_code\":\"121342\",\"name\":\"demo\",\"skyflow_id\":\"skyflowId123\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenReturn(mockResponse); - JSONObject response = skyflowClient.get(records, new GetOptions(false)); - JSONArray responseRecords = (JSONArray) response.get("records"); - - Assert.assertEquals(1, responseRecords.size()); - Assert.assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - Assert.assertNotNull(((JSONObject) responseRecords.get(0)).get("fields")); - - } catch (SkyflowException | IOException exception) { - exception.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - -} diff --git a/v1/src/test/java/com/skyflow/vault/InvokeConnectionTest.java b/v1/src/test/java/com/skyflow/vault/InvokeConnectionTest.java deleted file mode 100644 index 70319cc3..00000000 --- a/v1/src/test/java/com/skyflow/vault/InvokeConnectionTest.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.vault; - -import com.skyflow.common.utils.HttpUtility; -import com.skyflow.common.utils.TokenUtils; -import com.skyflow.entities.RequestMethod; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import org.json.simple.JSONObject; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.io.IOException; -import java.net.URL; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; - - -class TestTokenProvider implements TokenProvider { - @Override - public String getBearerToken() throws Exception { - return "test_auth_token"; - } -} - - -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.skyflow.common.utils.TokenUtils") -public class InvokeConnectionTest { - private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; - private JSONObject testConfig; - private static Skyflow skyflowClient; - - @BeforeClass - public static void init() throws Exception { - SkyflowConfiguration config = new SkyflowConfiguration(new TestTokenProvider()); - skyflowClient = Skyflow.init(config); - - PowerMockito.mockStatic(TokenUtils.class); - PowerMockito.when(TokenUtils.isTokenValid("test_auth_token")).thenReturn(true); - } - - @Before - public void setup() { - testConfig = new JSONObject(); - testConfig.put("connectionURL", "https://testgatewayurl.com/{card_number}/pay"); - testConfig.put("methodName", RequestMethod.POST); - - JSONObject pathParamsJson = new JSONObject(); - pathParamsJson.put("card_number", "1234"); - testConfig.put("pathParams", pathParamsJson); - - JSONObject queryParamsJson = new JSONObject(); - queryParamsJson.put("id", "1"); - testConfig.put("queryParams", queryParamsJson); - - JSONObject requestHeadersJson = new JSONObject(); - requestHeadersJson.put("content-type", "application/json"); - testConfig.put("requestHeader", requestHeadersJson); - - JSONObject requestBodyJson = new JSONObject(); - requestBodyJson.put("userName", "testUser"); - requestBodyJson.put("itemName", "item1"); - testConfig.put("requestBody", requestBodyJson); - - } - - @Test - public void testInvokeConnectionWithInvalidSkyflowConfig() { - try{ - SkyflowConfiguration config = new SkyflowConfiguration(null); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject request = new JSONObject(); - - JSONObject res = skyflowClient.invokeConnection(request); - } catch (SkyflowException e) { - assertEquals(ErrorCode.InvalidTokenProvider.getDescription(), e.getMessage()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInvokeConnectionValidInput() { - try { - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"processingTimeinMs\":\"116\"}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject gatewayResponse = skyflowClient.invokeConnection(testConfig); - - Assert.assertNotNull(gatewayResponse); - Assert.assertEquals(gatewayResponse.toJSONString(), mockResponse); - } catch (SkyflowException exception) { - Assert.assertNull(exception); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException exception) { - exception.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - - - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInvokeConnectionThrowsErrorResponse() { - String mockErrorResponse = "{\"error\":{\"code\":\"400\",\"message\":\"missing required field\"}}"; - try { - PowerMockito.mockStatic(HttpUtility.class); - PowerMockito.when(HttpUtility.sendRequest(anyString(),ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenThrow(new SkyflowException(400, mockErrorResponse)); - JSONObject gatewayResponse = skyflowClient.invokeConnection(testConfig); - Assert.assertNull(gatewayResponse); - } catch (SkyflowException exception) { - Assert.assertEquals(exception.getCode(), 400); - Assert.assertEquals(exception.getMessage(), mockErrorResponse); - } catch (IOException exception) { - exception.printStackTrace(); - } - } - - - @Test - public void testInvokeConnectionInvalidConnectionURL() { - JSONObject testConnectionConfig = new JSONObject(); - testConnectionConfig.put("connectionURL", "INVALID_CONNECTION_URL"); - try { - skyflowClient.invokeConnection(testConnectionConfig); - } catch (SkyflowException exception) { - Assert.assertEquals(exception.getCode(), ErrorCode.InvalidConnectionURL.getCode()); - Assert.assertEquals(exception.getMessage(), ErrorCode.InvalidConnectionURL.getDescription()); - } - - } - - @Test - public void testInvokeConnectionMissingConnectionURL() { - JSONObject testConnectionConfig = new JSONObject(); - try { - skyflowClient.invokeConnection(testConnectionConfig); - } catch (SkyflowException exception) { - Assert.assertEquals(exception.getCode(), ErrorCode.ConnectionURLMissing.getCode()); - Assert.assertEquals(exception.getMessage(), ErrorCode.ConnectionURLMissing.getDescription()); - } - } - - @Test - public void testInvokeConnectionMissingMethodName() { - JSONObject testConnectionConfig = new JSONObject(); - testConnectionConfig.put("connectionURL", "https://testgatewayurl.com/{card_number}/pay"); - try { - skyflowClient.invokeConnection(testConnectionConfig); - } catch (SkyflowException exception) { - Assert.assertEquals(exception.getCode(), ErrorCode.MethodNameMissing.getCode()); - Assert.assertEquals(exception.getMessage(), ErrorCode.MethodNameMissing.getDescription()); - } - } - - @Test - public void testInvokeConnectionInvalidMethodName() { - JSONObject testConnectionConfig = new JSONObject(); - testConnectionConfig.put("connectionURL", "https://testgatewayurl.com/{card_number}/pay"); - testConnectionConfig.put("methodName", "INVALID_METHOD_NAME"); - try { - Skyflow.init(new SkyflowConfiguration(new TestTokenProvider())).invokeConnection(testConnectionConfig); - } catch (SkyflowException exception) { - Assert.assertEquals(exception.getCode(), ErrorCode.InvalidMethodName.getCode()); - Assert.assertEquals(exception.getMessage(), ErrorCode.InvalidMethodName.getDescription()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInvokeConnectionWithFormEncoded() { - JSONObject testConfig = new JSONObject(); - testConfig.put("connectionURL", "https://testgatewayurl.com/"); - testConfig.put("methodName", RequestMethod.POST); - - JSONObject requestHeadersJson = new JSONObject(); - requestHeadersJson.put("content-type", "application/x-www-form-urlencoded"); - testConfig.put("requestHeader", requestHeadersJson); - - JSONObject testJson = new JSONObject(); - testJson.put("key1","value1"); - JSONObject nestedObj = new JSONObject(); - nestedObj.put("key2","value2"); - testJson.put("nest",nestedObj); - - testConfig.put("requestBody", testJson); - - try { - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"id\":\"12345\"}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject gatewayResponse = skyflowClient.invokeConnection(testConfig); - - Assert.assertNotNull(gatewayResponse); - Assert.assertEquals(gatewayResponse.toJSONString(), mockResponse); - } catch (SkyflowException exception) { - Assert.assertNull(exception); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException exception) { - exception.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInvokeConnectionWithMultipartFormData() { - JSONObject testConfig = new JSONObject(); - testConfig.put("connectionURL", "https://testgatewayurl.com/"); - testConfig.put("methodName", RequestMethod.POST); - - JSONObject requestHeadersJson = new JSONObject(); - requestHeadersJson.put("content-type", "multipart/form-data"); - testConfig.put("requestHeader", requestHeadersJson); - - JSONObject testJson = new JSONObject(); - testJson.put("key1","value1"); - JSONObject nestedObj = new JSONObject(); - nestedObj.put("key2","value2"); - testJson.put("nest",nestedObj); - - testConfig.put("requestBody", testJson); - - try { - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"id\":\"12345\"}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject gatewayResponse = skyflowClient.invokeConnection(testConfig); - - Assert.assertNotNull(gatewayResponse); - Assert.assertEquals(gatewayResponse.toJSONString(), mockResponse); - } catch (SkyflowException exception) { - Assert.assertNull(exception); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException exception) { - exception.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - - } - -} diff --git a/v1/src/test/java/com/skyflow/vault/SkyflowTest.java b/v1/src/test/java/com/skyflow/vault/SkyflowTest.java deleted file mode 100644 index 70dd193f..00000000 --- a/v1/src/test/java/com/skyflow/vault/SkyflowTest.java +++ /dev/null @@ -1,2485 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.vault; - -import com.skyflow.Configuration; -import com.skyflow.common.utils.Helpers; -import com.skyflow.common.utils.HttpUtility; -import com.skyflow.common.utils.TokenUtils; -import com.skyflow.entities.*; -import com.skyflow.errors.ErrorCode; -import com.skyflow.errors.SkyflowException; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatchers; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.io.IOException; -import java.net.URL; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.FutureTask; - -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -class DemoTokenProvider implements TokenProvider { - @Override - public String getBearerToken() throws Exception { - return "valid_token"; - } -} - -class InvalidTokenProvider implements TokenProvider { - @Override - public String getBearerToken() throws Exception { - return "not_a_valid_token"; - } -} - -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.skyflow.common.utils.TokenUtils") -public class SkyflowTest { - - private static String vaultID = null; - private static String vaultURL = null; - private static String skyflowId = null; - private static String token = null; - private static String tableName = null; - private static String columnName = null; - private static String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; - private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; - - - @BeforeClass - public static void setup() throws SkyflowException { - PowerMockito.mockStatic(TokenUtils.class); - PowerMockito.when(TokenUtils.isTokenValid("valid_token")).thenReturn(true); - PowerMockito.when(TokenUtils.isTokenValid("not_a_valid_token")).thenReturn(false); - - vaultID = "vault123"; - vaultURL = "https://test.com"; - skyflowId = "skyflowId123"; - token = "token123"; - tableName = "pii_fields"; - columnName = "first_name"; - } - - @Test - public void testValidConfig() { - Configuration.setLogLevel(LogLevel.INFO); - SkyflowConfiguration testConfig = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - try { - Skyflow skyflow = Skyflow.init(testConfig); - assert (skyflow instanceof Skyflow); - } catch (SkyflowException e) { - assertNotNull(e); - } - } - - - @Test - public void testInValidConfigWithNullValues() { - Configuration.setLogLevel(LogLevel.ERROR); - SkyflowConfiguration testConfig = new SkyflowConfiguration(null, null, new DemoTokenProvider()); - try { - Skyflow skyflow = Skyflow.init(testConfig); - skyflow.detokenize(new JSONObject()); - - } catch (SkyflowException e) { - assertEquals(e.getCode(), ErrorCode.EmptyVaultID.getCode()); - assertEquals(e.getMessage(), ErrorCode.EmptyVaultID.getDescription()); - } - } - - @Test - public void testInValidConfigWithNullValues2() { - Configuration.setLogLevel(LogLevel.DEBUG); - SkyflowConfiguration testConfig = new SkyflowConfiguration(vaultID, null, new DemoTokenProvider()); - try { - Skyflow skyflow = Skyflow.init(testConfig); - skyflow.detokenize(new JSONObject()); - - } catch (SkyflowException e) { - assertEquals(e.getCode(), ErrorCode.InvalidVaultURL.getCode()); - assertEquals(e.getMessage(), ErrorCode.InvalidVaultURL.getDescription()); - } - } - - @Test - public void testInvalidConfigWithEmptyVaultID() { - Configuration.setLogLevel(LogLevel.WARN); - SkyflowConfiguration testConfig = new SkyflowConfiguration("", vaultURL, new DemoTokenProvider()); - try { - Skyflow skyflow = Skyflow.init(testConfig); - skyflow.insert(new JSONObject(), new InsertOptions()); - } catch (SkyflowException e) { - assertEquals(e.getCode(), ErrorCode.EmptyVaultID.getCode()); - assertEquals(e.getMessage(), ErrorCode.EmptyVaultID.getDescription()); - } - } - - @Test - public void testInvalidConfigWithInvalidVaultURL() { - Configuration.setLogLevel(LogLevel.OFF); - SkyflowConfiguration testConfig = new SkyflowConfiguration(vaultID, "//valid.url.com", new DemoTokenProvider()); - try { - Skyflow skyflow = Skyflow.init(testConfig); - skyflow.insert(new JSONObject(), new InsertOptions()); - } catch (SkyflowException e) { - assertEquals(e.getCode(), ErrorCode.InvalidVaultURL.getCode()); - assertEquals(e.getMessage(), ErrorCode.InvalidVaultURL.getDescription()); - } - } - - @Test - public void testInvalidConfigWithHttpVaultURL() { - SkyflowConfiguration testConfig = new SkyflowConfiguration(vaultID, "http://valid.url.com", new DemoTokenProvider()); - try { - Skyflow skyflow = Skyflow.init(testConfig); - } catch (SkyflowException e) { - assertEquals(e.getCode(), ErrorCode.InvalidVaultURL.getCode()); - assertEquals(e.getMessage(), ErrorCode.InvalidVaultURL.getDescription()); - } - } - - @Test - public void testInsertWithInvalidSkyflowConfig() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, null); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - - JSONObject res = skyflowClient.insert(records); - } catch (SkyflowException e) { - assertEquals(ErrorCode.InvalidTokenProvider.getDescription(), e.getMessage()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertSuccessWithTokens() { - try { - SkyflowConfiguration config = new SkyflowConfiguration("vaultID", "https://vaulturl.com", new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", tableName); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = - "{\"vaultID\":\"vault123\",\"responses\":[{\"records\":[{\"skyflow_id\":\"id1\", \"tokens\":{\"first_name\":\"token1\"}}]}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - - JSONObject res = skyflowClient.insert(records, insertOptions); - JSONArray responseRecords = (JSONArray) res.get("records"); - - assertEquals(1, responseRecords.size()); - assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - assertNotNull(((JSONObject) responseRecords.get(0)).get("fields")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertSuccessWithoutInsertOptions() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", tableName); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = - "{\"vaultID\":\"vault123\",\"responses\":[{\"records\":[{\"skyflow_id\":\"id1\", \"tokens\":{\"first_name\":\"token1\"}}]}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject res = skyflowClient.insert(records); - JSONArray responseRecords = (JSONArray) res.get("records"); - - assertEquals(1, responseRecords.size()); - assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - assertNotNull(((JSONObject) responseRecords.get(0)).get("fields")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertSuccessWithUpsertOptions() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", tableName); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - UpsertOption upsertOption = new UpsertOption(tableName, columnName); - InsertOptions insertOptions = new InsertOptions(new UpsertOption[]{upsertOption}); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = - "{\"vaultID\":\"vault123\",\"responses\":[{\"records\":[{\"skyflow_id\":\"id1\", \"tokens\":{\"first_name\":\"token1\"}}]}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - - JSONObject res = skyflowClient.insert(records, insertOptions); - JSONArray responseRecords = (JSONArray) res.get("records"); - - assertEquals(1, responseRecords.size()); - assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - assertNotNull(((JSONObject) responseRecords.get(0)).get("fields")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertSuccessWithoutTokens() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", tableName); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(false); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"vaultID\":\"vault123\",\"responses\":[{\"records\":[{\"skyflow_id\":\"id1\"}]}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject res = skyflowClient.insert(records, insertOptions); - JSONArray responseRecords = (JSONArray) res.get("records"); - - assertEquals(1, responseRecords.size()); - assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - assertNotNull(((JSONObject) responseRecords.get(0)).get("skyflow_id")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertWithContinueOnErrorAsTrueWithTokens() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record1 = new JSONObject(); - record1.put("table", tableName); - JSONObject fields1 = new JSONObject(); - fields1.put(columnName, "john"); - record1.put("fields", fields1); - - JSONObject record2 = new JSONObject(); - record2.put("table", tableName); - JSONObject fields2 = new JSONObject(); - fields2.put(columnName, "jane"); - record2.put("fields", fields2); - - recordsArray.add(record1); - recordsArray.add(record2); - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(true, true); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"vaultID\":\"vault123\",\"responses\":[{\"Status\":400,\"Body\":{\"error\":\"Error Inserting Records due to unique constraint violation\"}},{\"Status\":200,\"Body\":{\"records\":[{\"skyflow_id\":\"id1\",\"tokens\":{\"first_name\":\"token1\"}}]}}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject res = skyflowClient.insert(records, insertOptions); - JSONArray responseSuccessRecords = (JSONArray) res.get("records"); - JSONArray responseErrorRecords = (JSONArray) res.get("errors"); - - assertEquals(1, responseSuccessRecords.size()); - assertEquals(tableName, ((JSONObject) responseSuccessRecords.get(0)).get("table")); - assertEquals(1, ((JSONObject) responseSuccessRecords.get(0)).get("request_index")); - assertNotNull(((JSONObject) responseSuccessRecords.get(0)).get("fields")); - - assertEquals(1, responseErrorRecords.size()); - assertEquals(0, ((JSONObject) ((JSONObject) responseErrorRecords.get(0)).get("error")).get("request_index")); - assertNotNull(((JSONObject) ((JSONObject) responseErrorRecords.get(0)).get("error")).get("description")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertWithContinueOnErrorAsTrueWithoutTokens() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record1 = new JSONObject(); - record1.put("table", tableName); - JSONObject fields1 = new JSONObject(); - fields1.put(columnName, "first"); - record1.put("fields", fields1); - - JSONObject record2 = new JSONObject(); - record2.put("table", tableName); - JSONObject fields2 = new JSONObject(); - fields2.put(columnName, "second"); - record2.put("fields", fields2); - - recordsArray.add(record1); - recordsArray.add(record2); - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(false, true); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"vaultID\":\"vault123\",\"responses\":[{\"Status\":400,\"Body\":{\"error\":\"Error Inserting Records due to unique constraint violation\"}},{\"Status\":200,\"Body\":{\"records\":[{\"skyflow_id\":\"id1\"}]}}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject res = skyflowClient.insert(records, insertOptions); - JSONArray responseSuccessRecords = (JSONArray) res.get("records"); - JSONArray responseErrorRecords = (JSONArray) res.get("errors"); - - assertEquals(1, responseSuccessRecords.size()); - assertEquals(tableName, ((JSONObject) responseSuccessRecords.get(0)).get("table")); - assertEquals(1, ((JSONObject) responseSuccessRecords.get(0)).get("request_index")); - assertNotNull(((JSONObject) responseSuccessRecords.get(0)).get("skyflow_id")); - assertNull(((JSONObject) responseSuccessRecords.get(0)).get("tokens")); - - assertEquals(1, responseErrorRecords.size()); - assertEquals(0, ((JSONObject) ((JSONObject) responseErrorRecords.get(0)).get("error")).get("request_index")); - assertNotNull(((JSONObject) ((JSONObject) responseErrorRecords.get(0)).get("error")).get("description")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertWithContinueOnErrorAsTrueWithUpsert() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record1 = new JSONObject(); - record1.put("table", tableName); - JSONObject fields1 = new JSONObject(); - fields1.put(columnName, "first"); - record1.put("fields", fields1); - - JSONObject record2 = new JSONObject(); - record2.put("table", tableName); - JSONObject fields2 = new JSONObject(); - fields2.put(columnName, "second"); - record2.put("fields", fields2); - - recordsArray.add(record1); - recordsArray.add(record2); - records.put("records", recordsArray); - - UpsertOption upsertOption = new UpsertOption(tableName, columnName); - InsertOptions insertOptions = new InsertOptions(new UpsertOption[]{upsertOption}, true); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"vaultID\":\"vault123\",\"responses\":[{\"Status\":400,\"Body\":{\"error\":\"Error Inserting Records due to unique constraint violation\"}},{\"Status\":200,\"Body\":{\"records\":[{\"skyflow_id\":\"id1\"}]}}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject res = skyflowClient.insert(records, insertOptions); - JSONArray responseSuccessRecords = (JSONArray) res.get("records"); - JSONArray responseErrorRecords = (JSONArray) res.get("errors"); - - assertEquals(1, responseSuccessRecords.size()); - assertEquals(tableName, ((JSONObject) responseSuccessRecords.get(0)).get("table")); - assertEquals(1, ((JSONObject) responseSuccessRecords.get(0)).get("request_index")); - assertNotNull(((JSONObject) responseSuccessRecords.get(0)).get("skyflow_id")); - assertNull(((JSONObject) responseSuccessRecords.get(0)).get("tokens")); - - assertEquals(1, responseErrorRecords.size()); - assertEquals(0, ((JSONObject) ((JSONObject) responseErrorRecords.get(0)).get("error")).get("request_index")); - assertNotNull(((JSONObject) ((JSONObject) responseErrorRecords.get(0)).get("error")).get("description")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertWithContinueOnErrorWithUpsertAndTokens() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record1 = new JSONObject(); - record1.put("table", tableName); - JSONObject fields1 = new JSONObject(); - fields1.put(columnName, "first"); - record1.put("fields", fields1); - - JSONObject record2 = new JSONObject(); - record2.put("table", tableName); - JSONObject fields2 = new JSONObject(); - fields2.put(columnName, "second"); - record2.put("fields", fields2); - - recordsArray.add(record1); - recordsArray.add(record2); - records.put("records", recordsArray); - - UpsertOption upsertOption = new UpsertOption(tableName, columnName); - InsertOptions insertOptions = new InsertOptions(false, new UpsertOption[]{upsertOption}, true); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"vaultID\":\"vault123\",\"responses\":[{\"Status\":400,\"Body\":{\"error\":\"Error Inserting Records due to unique constraint violation\"}},{\"Status\":200,\"Body\":{\"records\":[{\"skyflow_id\":\"id1\"}]}}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject res = skyflowClient.insert(records, insertOptions); - JSONArray responseSuccessRecords = (JSONArray) res.get("records"); - JSONArray responseErrorRecords = (JSONArray) res.get("errors"); - - assertEquals(1, responseSuccessRecords.size()); - assertEquals(tableName, ((JSONObject) responseSuccessRecords.get(0)).get("table")); - assertEquals(1, ((JSONObject) responseSuccessRecords.get(0)).get("request_index")); - assertNotNull(((JSONObject) responseSuccessRecords.get(0)).get("skyflow_id")); - assertNull(((JSONObject) responseSuccessRecords.get(0)).get("tokens")); - - assertEquals(1, responseErrorRecords.size()); - assertEquals(0, ((JSONObject) ((JSONObject) responseErrorRecords.get(0)).get("error")).get("request_index")); - assertNotNull(((JSONObject) ((JSONObject) responseErrorRecords.get(0)).get("error")).get("description")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertParseException() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record1 = new JSONObject(); - record1.put("table", tableName); - JSONObject fields1 = new JSONObject(); - fields1.put(columnName, "first"); - record1.put("fields", fields1); - - recordsArray.add(record1); - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(false, true); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"vaultID\":\"vault123\",\"responses\":[{\"Status\":200,\"Body\":{\"records\":[{\"skyflow_id\":\"id1\"]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject res = skyflowClient.insert(records, insertOptions); - fail(EXCEPTION_NOT_THROWN); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.ResponseParsingError.getDescription(), skyflowException.getMessage()); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - public void testInsertEmptyRecords() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(false); - JSONObject res = skyflowClient.insert(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.EmptyRecords.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testInsertEmptyTable() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(false); - JSONObject res = skyflowClient.insert(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidTable.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testInsertEmptyFields() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", tableName); - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(true); - JSONObject res = skyflowClient.insert(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidFields.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testInsertInvalidInput() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("invalidTableKey", tableName); - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(true); - JSONObject res = skyflowClient.insert(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidInsertInput.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testInsertWithEmptyArrayUpsertOptions() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - UpsertOption[] upsertOptions = new UpsertOption[]{}; - InsertOptions insertOptions = new InsertOptions(true, upsertOptions); - JSONObject records = new JSONObject(); - JSONObject res = skyflowClient.insert(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidUpsertOptionType.getDescription(), skyflowException.getMessage()); - } - - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - UpsertOption[] upsertOptions = new UpsertOption[3]; - InsertOptions insertOptions = new InsertOptions(true, upsertOptions); - JSONObject records = new JSONObject(); - JSONObject res = skyflowClient.insert(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidUpsertObjectType.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testInsertWithInvalidTableInUpsertOptions() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - InsertOptions insertOptions = new InsertOptions(true, new UpsertOption[]{new UpsertOption(null, "column")}); - JSONObject records = new JSONObject(); - JSONObject res = skyflowClient.insert(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidTableInUpsertOption.getDescription(), skyflowException.getMessage()); - } - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - InsertOptions insertOptions = new InsertOptions(true, new UpsertOption[]{new UpsertOption("", "column")}); - JSONObject records = new JSONObject(); - JSONObject res = skyflowClient.insert(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidTableInUpsertOption.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testInsertWithInvalidColumnInUpsertOptions() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - InsertOptions insertOptions = new InsertOptions(true, new UpsertOption[]{new UpsertOption("table1", null)}); - JSONObject records = new JSONObject(); - JSONObject res = skyflowClient.insert(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidColumnInUpsertOption.getDescription(), skyflowException.getMessage()); - } - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - InsertOptions insertOptions = new InsertOptions(true, new UpsertOption[]{new UpsertOption("table2", "")}); - JSONObject records = new JSONObject(); - JSONObject res = skyflowClient.insert(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidColumnInUpsertOption.getDescription(), skyflowException.getMessage()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testQuerySuccess() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject queryInput = new JSONObject(); - queryInput.put("query", "SELECT * FROM users"); - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"response_key\":\"response_value\"}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject response = skyflowClient.query(queryInput, new QueryOptions()); - assertNotNull(response); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - public void testQueryMissing() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject queryInput = new JSONObject(); - queryInput.put("query", ""); - QueryOptions queryOptions = new QueryOptions(); - boolean exceptionThrown = false; - try { - JSONObject res = skyflowClient.query(queryInput, queryOptions); - } catch (SkyflowException skyflowException) { - exceptionThrown = true; - assertEquals(ErrorCode.InvalidQuery.getCode(), skyflowException.getCode()); - assertEquals("Query is missing", skyflowException.getMessage()); - } - assertTrue(exceptionThrown); - } catch (Exception e) { - fail("Caught unexpected exception: " + e.getMessage()); - } - } - @Test - public void testInvalidQueryInput() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject queryInput = new JSONObject(); - queryInput.put("invalidQueryKey", "select * from cards"); - QueryOptions queryOptions = new QueryOptions(); - boolean exceptionThrown = false; - try { - JSONObject res = skyflowClient.query(queryInput, queryOptions); - } catch (SkyflowException skyflowException) { - exceptionThrown = true; - assertEquals("Invalid query input", skyflowException.getMessage()); - } - assertTrue(exceptionThrown); - } catch (Exception e) { - } - } - @Test - public void testValidJsonParsing() { - String jsonMessage = "{\"error\":{\"http_code\":404,\"message\":\"Not Found\"}}"; - SkyflowException skyflowException = new SkyflowException( - ErrorCode.InvalidVaultURL.getCode(), - jsonMessage - ); - JSONObject result = Helpers.constructQueryErrorObject(skyflowException); - } - - @Test - public void testValidSkyflowExceptionWithoutJson() { - SkyflowException skyflowException = new SkyflowException( - ErrorCode.EmptyVaultID.getCode(), - "Empty vaultID" - ); - JSONObject result = Helpers.constructQueryErrorObject(skyflowException); - } - @Test - public void testInvalidJsonParsing() { - String invalidJsonMessage = "Invalid JSON"; - SkyflowException skyflowException = new SkyflowException( - ErrorCode.InvalidVaultURL.getCode(), - invalidJsonMessage - ); - JSONObject result = Helpers.constructQueryErrorObject(skyflowException); - } - @Test - public void testMissingErrorKeyInJson() { - String jsonMessage = "{\"status\":\"error\",\"http_code\":404,\"message\":\"Not Found\"}"; - SkyflowException skyflowException = new SkyflowException( - ErrorCode.InvalidVaultURL.getCode(), - jsonMessage - ); - JSONObject result = Helpers.constructQueryErrorObject(skyflowException); - } - @Test - public void testMissingHttpCodeInErrorJson() { - String jsonMessage = "{\"error\":{\"message\":\"Not Found\"}}"; - SkyflowException skyflowException = new SkyflowException( - ErrorCode.InvalidVaultURL.getCode(), - jsonMessage - ); - JSONObject result = Helpers.constructQueryErrorObject(skyflowException); - } - @Test - public void testMissingMessageInErrorJson() { - String jsonMessage = "{\"error\":{\"http_code\":404}}"; - SkyflowException skyflowException = new SkyflowException( - ErrorCode.InvalidVaultURL.getCode(), - jsonMessage - ); - JSONObject result = Helpers.constructQueryErrorObject(skyflowException); - } - @Test - public void testEmptyErrorObjectInJson() { - String jsonMessage = "{\"error\":{}}"; - SkyflowException skyflowException = new SkyflowException( - ErrorCode.InvalidVaultURL.getCode(), - jsonMessage - ); - JSONObject result = Helpers.constructQueryErrorObject(skyflowException); - } - @Test - public void testConstructQueryRequest() throws SkyflowException { - QueryRecordInput record = new QueryRecordInput(); - record.setQuery("SELECT * FROM users"); - QueryOptions options = new QueryOptions(); - - JSONObject result = Helpers.constructQueryRequest(record, options); - assertTrue(result.containsKey("query")); - assertEquals("SELECT * FROM users", result.get("query")); - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testQueryIOException() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject queryInput = new JSONObject(); - queryInput.put("query", "SELECT * FROM table"); - QueryOptions queryOptions = new QueryOptions(); - PowerMockito.mockStatic(HttpUtility.class); - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenThrow(new IOException()); - - try { - skyflowClient.query(queryInput, queryOptions); - fail("Expected SkyflowException to be thrown"); - } catch (SkyflowException e) { - assertEquals(ErrorCode.InvalidQueryInput.getCode(), e.getCode()); - } - } catch (SkyflowException e) { - fail("Caught unexpected SkyflowException: " + e.getMessage()); - } catch (IOException ioException) { - fail("Caught unexpected IOException: " + ioException.getMessage()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testQueryParseException() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject queryInput = new JSONObject(); - queryInput.put("query", "SELECT * FROM table"); - QueryOptions queryOptions = new QueryOptions(); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "Invalid JSON"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - - try { - skyflowClient.query(queryInput, queryOptions); - fail("Expected SkyflowException to be thrown"); - } catch (SkyflowException e) { - assertEquals(ErrorCode.ResponseParsingError.getCode(), e.getCode()); - } - } catch (SkyflowException e) { - fail("Caught unexpected SkyflowException: " + e.getMessage()); - } catch (IOException e) { - fail("Caught unexpected IOException: " + e.getMessage()); - } - } - @Test - public void testGetAndSetRecords() { - QueryRecordInput inputRecord = new QueryRecordInput(); - QueryInput queryInput = new QueryInput(); - - assertNull(queryInput.getQueryInput()); - - queryInput.setQueryInput(inputRecord); - assertEquals(inputRecord, queryInput.getQueryInput()); - } - @Test - public void testGetAndSetQuery() { - QueryRecordInput queryRecordInput = new QueryRecordInput(); - assertNull(queryRecordInput.getQuery()); - - String testQuery = "SELECT * FROM table"; - queryRecordInput.setQuery(testQuery); - assertEquals(testQuery, queryRecordInput.getQuery()); - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testDetokenizeSuccess() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("token", token); - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"records\":[{\"token\":\"token123\",\"valueType\":\"INTEGER\",\"value\":\"10\"}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - - JSONObject res = skyflowClient.detokenize(records); - JSONArray responseRecords = (JSONArray) res.get("records"); - assertEquals(1, responseRecords.size()); - assertEquals(token, ((JSONObject) responseRecords.get(0)).get("token")); - assertTrue(((JSONObject) responseRecords.get(0)).containsKey("value")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testFormattedDetokenizeSuccess() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("token", token); - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"records\":[{\"token\":\"token123\",\"valueType\":\"INTEGER\",\"value\":\"10\",\"test\":\"test123\"}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - - JSONObject res = skyflowClient.detokenize(records); - JSONArray responseRecords = (JSONArray) res.get("records"); - assertEquals(1, responseRecords.size()); - assertEquals(token, ((JSONObject) responseRecords.get(0)).get("token")); - assertEquals(null, ((JSONObject) responseRecords.get(0)).get("test")); - assertTrue(((JSONObject) responseRecords.get(0)).containsKey("value")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testDetokenizeError() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("token", "invalidToken"); - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = - "{\"error\":{\"grpc_code\":5,\"http_code\":404,\"message\":\"Token not found for invalidToken\",\"http_status\":\"Not Found\",\"details\":[]}}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenThrow(new SkyflowException(404, mockResponse)); - - JSONObject res = skyflowClient.detokenize(records); - } catch (SkyflowException skyflowException) { - JSONArray errors = (JSONArray) skyflowException.getData().get("errors"); - assertEquals(1, errors.size()); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testDetokenizePartialError() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("token", "invalidToken1"); - JSONObject validRecord = new JSONObject(); - validRecord.put("token", token); - recordsArray.add(record); - recordsArray.add(validRecord); - records.put("records", recordsArray); - - JSONParser jsonParser = new JSONParser(); - JSONObject validRequest = (JSONObject) - jsonParser.parse("{\"detokenizationParameters\":[{\"token\":\"token123\",\"redaction\":\"PLAIN_TEXT\"}]}"); - PowerMockito.mockStatic(HttpUtility.class); - String mockValidResponse = "{\"records\":[{\"token\":\"token123\",\"valueType\":\"INTEGER\",\"value\":\"10\"}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), eq(validRequest), ArgumentMatchers.anyMap())).thenReturn(mockValidResponse); - - JSONObject invalidRequest = (JSONObject) - jsonParser.parse("{\"detokenizationParameters\":[{\"token\":\"invalidToken1\",\"redaction\":\"PLAIN_TEXT\"}]}"); - String mockInvalidResponse = - "{\"error\":{\"grpc_code\":5,\"http_code\":404,\"message\":\"Token not found for invalidToken1\",\"http_status\":\"Not Found\",\"details\":[]}}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), eq(invalidRequest), ArgumentMatchers.anyMap())).thenThrow(new SkyflowException(404, mockInvalidResponse)); - - - JSONObject res = skyflowClient.detokenize(records); - } catch (SkyflowException skyflowException) { - JSONArray responseRecords = (JSONArray) skyflowException.getData().get("records"); - JSONArray errors = (JSONArray) skyflowException.getData().get("errors"); - assertEquals(1, errors.size()); - assertEquals(1, responseRecords.size()); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (ParseException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - public void testDetokenizeInvalidInput() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - records.put("invalidRecordsKey", recordsArray); - - JSONObject res = skyflowClient.detokenize(records); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidDetokenizeInput.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testDetokenizeEmptyRecords() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - records.put("records", recordsArray); - - JSONObject res = skyflowClient.detokenize(records); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.EmptyRecords.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testDetokenizeEmptyRecords2() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - records.put("records", null); - - JSONObject res = skyflowClient.detokenize(records); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.EmptyRecords.getDescription(), skyflowException.getMessage()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.TokenUtils"}) - public void testDetokenizeInvalidToken() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("token", ""); - recordsArray.add(record); - records.put("records", recordsArray); - - JSONObject res = skyflowClient.detokenize(records); - } catch (SkyflowException skyflowException) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) skyflowException.getData().get("errors")).get(0))).get("error"); - assertEquals(ErrorCode.InvalidToken.getDescription(), error.get("description")); - } - } - - @Test - public void testDetokenizeInvalidRedaction() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("token", "3423-4671-5420-2425"); - record.put("redaction", "invalid"); - recordsArray.add(record); - records.put("records", recordsArray); - - JSONObject res = skyflowClient.detokenize(records); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidDetokenizeInput.getDescription(), skyflowException.getMessage()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testDetokenizeWhenNullRedactionIsPassed() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("token", "3423-4671-5420-2425"); - record.put("redaction", null); - recordsArray.add(record); - records.put("records", recordsArray); - - JSONObject res = skyflowClient.detokenize(records); - } catch (SkyflowException skyflowException) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) skyflowException.getData().get("errors")).get(0))).get("error"); - assertEquals(ErrorCode.InvalidDetokenizeInput.getDescription(), error.get("description")); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetByIdSuccess() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - JSONArray ids = new JSONArray(); - ids.add(skyflowId); - record.put("ids", ids); - record.put("table", tableName); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - recordsArray.add(record); - - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"records\":[{\"fields\":{\"age\":10,\"skyflow_id\":\"skyflowId123\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject response = skyflowClient.getById(records); - JSONArray responseRecords = (JSONArray) response.get("records"); - - assertEquals(1, responseRecords.size()); - assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - assertNotNull(((JSONObject) responseRecords.get(0)).get("fields")); - - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetByIdError() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - JSONArray ids = new JSONArray(); - ids.add(skyflowId); - record.put("ids", ids); - record.put("table", "invalidTable"); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - recordsArray.add(record); - - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"error\":{\"grpc_code\":13,\"http_code\":500,\"message\":\"Couldn't load data\",\"http_status\":\"Internal Server Error\"}}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenThrow(new SkyflowException(500, mockResponse)); - JSONObject response = skyflowClient.getById(records); - - } catch (SkyflowException e) { - JSONArray errors = (JSONArray) e.getData().get("errors"); - assertEquals(1, errors.size()); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testGetByIdPartialError() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - JSONArray ids = new JSONArray(); - ids.add(skyflowId); - record.put("ids", ids); - record.put("table", tableName); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - recordsArray.add(record); - - JSONObject record2 = new JSONObject(); - JSONArray id2 = new JSONArray(); - id2.add("invalidId"); - record2.put("ids", id2); - record2.put("table", "invalidTable2"); - record2.put("redaction", RedactionType.PLAIN_TEXT.toString()); - recordsArray.add(record2); - - records.put("records", recordsArray); - - String validRequestUrl = "https://test.com/v1/vaults/vault123/pii_fields?skyflow_ids=skyflowId123&redaction=PLAIN_TEXT"; - String invalidRequestUrl = "https://test.com/v1/vaults/vault123/invalidTable2?skyflow_ids=invalidId&redaction=PLAIN_TEXT"; - - PowerMockito.mockStatic(HttpUtility.class); - String mockValidResponse = "{\"records\":[{\"fields\":{\"age\":10,\"skyflow_id\":\"skyflowId123\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), eq(new URL(validRequestUrl)), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockValidResponse); - - String mockInvalidResponse = "{\"error\":{\"grpc_code\":13,\"http_code\":500,\"message\":\"Couldn't load data\",\"http_status\":\"Internal Server Error\"}}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), eq(new URL(invalidRequestUrl)), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenThrow(new SkyflowException(500, mockInvalidResponse)); - - JSONObject response = skyflowClient.getById(records); - - } catch (SkyflowException e) { - JSONObject partialError = e.getData(); - assertTrue(partialError.containsKey("records")); - assertTrue(partialError.containsKey("errors")); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - public void testGetByIdInvalidInput() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - records.put("invalidRecordsKey", recordsArray); - - JSONObject response = skyflowClient.getById(records); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidGetByIdInput.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testGetByIdEmptyRecords() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - records.put("records", recordsArray); - - JSONObject response = skyflowClient.getById(records); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.EmptyRecords.getDescription(), skyflowException.getMessage()); - } - } - - - @Test - public void testGetByIdEmptyRecords2() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - records.put("records", null); - - JSONObject response = skyflowClient.getById(records); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.EmptyRecords.getDescription(), skyflowException.getMessage()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.TokenUtils"}) - public void testGetByIdEmptyTable() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - JSONArray ids = new JSONArray(); - ids.add(skyflowId); - record.put("ids", ids); - record.put("table", ""); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - recordsArray.add(record); - - records.put("records", recordsArray); - - JSONObject response = skyflowClient.getById(records); - } catch (SkyflowException skyflowException) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) skyflowException.getData().get("errors")).get(0))).get("error"); - assertEquals(ErrorCode.InvalidTable.getDescription(), error.get("description")); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testUpdateSuccessWithToken() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", tableName); - record.put("id", skyflowId); - JSONObject fields = new JSONObject(); - fields.put(columnName, "name"); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - UpdateOptions updateOptions = new UpdateOptions(true); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"skyflow_id\":\"skyflowId123\",\"tokens\":{\"first_name\":\"token2\"}}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - - JSONObject res = skyflowClient.update(records, updateOptions); - JSONArray responseRecords = (JSONArray) res.get("records"); - - assertEquals(1, responseRecords.size()); - assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - assertNotNull(((JSONObject) responseRecords.get(0)).get("fields")); - } catch (SkyflowException e) { - JSONArray errors = (JSONArray) e.getData().get("errors"); - assertEquals(1, errors.size()); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testUpdateSuccessWithOutToken() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", tableName); - record.put("id", skyflowId); - JSONObject fields = new JSONObject(); - fields.put(columnName, "name"); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - UpdateOptions updateOptions = new UpdateOptions(false); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"skyflow_id\":\"skyflowId123\",\"tokens\":null}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - - JSONObject res = skyflowClient.update(records, updateOptions); - JSONArray responseRecords = (JSONArray) res.get("records"); - - assertEquals(1, responseRecords.size()); - assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - assertNull(((JSONObject) responseRecords.get(0)).get("fields")); - } catch (SkyflowException e) { - JSONArray errors = (JSONArray) e.getData().get("errors"); - assertEquals(1, errors.size()); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testUpdateSuccessWithOutUpdateOptions() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", tableName); - record.put("id", skyflowId); - JSONObject fields = new JSONObject(); - fields.put(columnName, "name"); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"skyflow_id\":\"skyflowId123\",\"tokens\":{\"first_name\":\"token2\"}}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - - JSONObject res = skyflowClient.update(records); - JSONArray responseRecords = (JSONArray) res.get("records"); - - assertEquals(1, responseRecords.size()); - assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - assertNotNull(((JSONObject) responseRecords.get(0)).get("fields")); - } catch (SkyflowException e) { - JSONArray errors = (JSONArray) e.getData().get("errors"); - assertEquals(1, errors.size()); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - - } - - @Test - public void testUpdateEmptyRecords() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - records.put("records", recordsArray); - UpdateOptions updateOptions = new UpdateOptions(); - JSONObject response = skyflowClient.update(records, updateOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.EmptyRecords.getDescription(), skyflowException.getMessage()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.TokenUtils"}) - public void testUpdateEmptyFields() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - JSONObject fields = new JSONObject(); - record.put("table", tableName); - record.put("id", skyflowId); - record.put("fields", fields); - recordsArray.add(record); - - records.put("records", recordsArray); - UpdateOptions updateOptions = new UpdateOptions(); - JSONObject response = skyflowClient.update(records, updateOptions); - } catch (SkyflowException skyflowException) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) skyflowException.getData().get("error")).get(0))).get("error"); - assertEquals(ErrorCode.InvalidFields.getDescription(), error.get("description")); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.TokenUtils"}) - public void testUpdateInvalidTable() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - JSONObject fields = new JSONObject(); - record.put("table", null); - record.put("id", skyflowId); - record.put("fields", fields); - recordsArray.add(record); - - records.put("records", recordsArray); - UpdateOptions updateOptions = new UpdateOptions(); - JSONObject response = skyflowClient.update(records, updateOptions); - } catch (SkyflowException skyflowException) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) skyflowException.getData().get("error")).get(0))).get("error"); - assertEquals(ErrorCode.InvalidTable.getDescription(), error.get("description")); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.TokenUtils"}) - public void testUpdateEmptySkyflowId() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - JSONObject fields = new JSONObject(); - record.put("table", tableName); - record.put("id", ""); - record.put("fields", fields); - recordsArray.add(record); - - records.put("records", recordsArray); - UpdateOptions updateOptions = new UpdateOptions(); - JSONObject response = skyflowClient.update(records, updateOptions); - } catch (SkyflowException skyflowException) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) skyflowException.getData().get("error")).get(0))).get("error"); - assertEquals(ErrorCode.InvalidSkyflowId.getDescription(), error.get("description")); - } - } - - @Test - public void testUpdateEmptyRecords2() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - records.put("records", null); - - JSONObject response = skyflowClient.getById(records); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.EmptyRecords.getDescription(), skyflowException.getMessage()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.TokenUtils"}) - public void testUpdateEmptyTable() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", ""); - record.put("id", skyflowId); - JSONObject fields = new JSONObject(); - fields.put(columnName, "name"); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - UpdateOptions updateOptions = new UpdateOptions(true); - - JSONObject res = skyflowClient.update(records, updateOptions); - } catch (SkyflowException e) { - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) e.getData().get("error")).get(0))).get("error"); - assertEquals(ErrorCode.InvalidTable.getDescription(), error.get("description")); - } - - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testUpdateError() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", "invalid_table"); - record.put("id", skyflowId); - JSONObject fields = new JSONObject(); - fields.put(columnName, "name"); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - UpdateOptions updateOptions = new UpdateOptions(true); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"error\":{\"grpc_code\":3,\"http_code\":400,\"message\":\"Object Name table was not found for Vault vault123\",\"http_status\":\"Bad Request\",\"details\":[]}}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - - JSONObject res = skyflowClient.update(records, updateOptions); - - } catch (SkyflowException e) { - JSONArray errors = (JSONArray) e.getData().get("error"); - assertEquals(1, errors.size()); - JSONObject error = (JSONObject) ((JSONObject) (((JSONArray) e.getData().get("error")).get(0))).get("error"); - assertEquals(ErrorCode.InvalidTable.getDescription(), error.get("description")); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - - } - - @Test - public void testUpdateInvalidInput() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - records.put("invalidRecordsKey", recordsArray); - - UpdateOptions updateOptions = new UpdateOptions(true); - JSONObject response = skyflowClient.update(records, updateOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidUpdateInput.getDescription(), skyflowException.getMessage()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testUpdatePartialError() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", tableName); - record.put("id", skyflowId); - JSONObject fields = new JSONObject(); - fields.put(columnName, "name"); - record.put("fields", fields); - recordsArray.add(record); - - JSONObject record2 = new JSONObject(); - record2.put("table", "invalidTable"); - record2.put("id", "invalidId"); - JSONObject fields2 = new JSONObject(); - fields2.put(columnName, "name"); - record2.put("fields", fields2); - recordsArray.add(record2); - records.put("records", recordsArray); - - String validRequestUrl = "https://test.com/v1/vaults/vault123/pii_fields/skyflowId123"; - String invalidRequestUrl = "https://test.com/v1/vaults/vault123/invalidTable/invalidId"; - - PowerMockito.mockStatic(HttpUtility.class); - - String mockInvalidResponse = "{\"error\":{\"grpc_code\":3,\"http_code\":400,\"message\":\"Object Name table was not found for Vault vault123\",\"http_status\":\"Bad Request\",\"details\":[]}}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), eq(new URL(invalidRequestUrl)), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenThrow(new SkyflowException(400, mockInvalidResponse)); - - String mockValidResponse = "{\"skyflow_id\":\"skyflowId123\",\"tokens\":{\"first_name\":\"token2\"}}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), eq(new URL(validRequestUrl)), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockValidResponse); - - JSONObject response = skyflowClient.update(records, new UpdateOptions(true)); - - } catch (SkyflowException e) { - JSONObject partialError = e.getData(); - assertTrue(partialError.containsKey("records")); - assertTrue(partialError.containsKey("error")); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testUpdateWrongVaultError() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", tableName); - record.put("id", skyflowId); - JSONObject fields = new JSONObject(); - fields.put(columnName, "name"); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - String invalidRequestUrl = "https://test.com/v1/vaults/vault1234/invalidTable/vault123/invalidId"; - - PowerMockito.mockStatic(HttpUtility.class); - - String mockInvalidResponse = "ThreadExecution exception"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), eq(new URL(invalidRequestUrl)), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenThrow(new SkyflowException(500, mockInvalidResponse)); - - JSONObject response = skyflowClient.update(records, new UpdateOptions(true)); - - } catch (SkyflowException e) { - String error = e.getMessage(); - assertEquals(ErrorCode.ThreadExecutionException.getDescription(), error); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testUpdateIOException() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", tableName); - record.put("id", skyflowId); - JSONObject fields = new JSONObject(); - fields.put(columnName, "name"); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - PowerMockito.when(HttpUtility.sendRequest(anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new IOException()); - - JSONObject response = skyflowClient.update(records, new UpdateOptions(true)); - - } catch (SkyflowException e) { - String error = e.getMessage(); - assertEquals(ErrorCode.ThreadExecutionException.getDescription(), error); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testUpdateParseException() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", tableName); - record.put("id", skyflowId); - JSONObject fields = new JSONObject(); - fields.put(columnName, "name"); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - String invalidMockResponse = "a{\"skyflow_id\":\"skyflowId123\",\"tokens\":{\"first_name\":\"token2\"}}"; - - PowerMockito.mockStatic(HttpUtility.class); - PowerMockito.when(HttpUtility.sendRequest(anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenReturn(invalidMockResponse); - - JSONObject response = skyflowClient.update(records, new UpdateOptions(true)); - - } catch (SkyflowException e) { - String error = e.getMessage(); - assertEquals(ErrorCode.ThreadExecutionException.getDescription(), error); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkEmptyTable() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertBulkOptions insertOptions = new InsertBulkOptions(false); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidTable.getDescription(), skyflowException.getMessage()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkEmptyTableCase2() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("table", null); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertBulkOptions insertOptions = new InsertBulkOptions(false); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidTable.getDescription(), skyflowException.getMessage()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkEmptyTableCase3() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("table", ""); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertBulkOptions insertOptions = new InsertBulkOptions(false); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidTable.getDescription(), skyflowException.getMessage()); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkEmptyFields() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", tableName); - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertBulkOptions insertOptions = new InsertBulkOptions(true); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidFields.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testInsertBulkInvalidInput() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("invalidTableKey", tableName); - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertBulkOptions insertOptions = new InsertBulkOptions(true); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidInsertInput.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testInsertBulkWithEmptyArrayUpsertOptions() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - UpsertOption[] upsertOptions = new UpsertOption[]{}; - InsertBulkOptions insertOptions = new InsertBulkOptions(true, upsertOptions); - JSONObject records = new JSONObject(); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidUpsertOptionType.getDescription(), skyflowException.getMessage()); - } - - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - UpsertOption[] upsertOptions = new UpsertOption[3]; - InsertBulkOptions insertOptions = new InsertBulkOptions(true, upsertOptions); - JSONObject records = new JSONObject(); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidUpsertObjectType.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testInsertBulkWithInvalidTableInUpsertOptions() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - InsertBulkOptions insertOptions = new InsertBulkOptions(true, new UpsertOption[]{new UpsertOption(null, "column")}); - JSONObject records = new JSONObject(); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidTableInUpsertOption.getDescription(), skyflowException.getMessage()); - } - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - InsertBulkOptions insertOptions = new InsertBulkOptions(true, new UpsertOption[]{new UpsertOption("", "column")}); - JSONObject records = new JSONObject(); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidTableInUpsertOption.getDescription(), skyflowException.getMessage()); - } - } - - @Test - public void testInsertBulkWithInvalidColumnInUpsertOptions() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - InsertBulkOptions insertOptions = new InsertBulkOptions(true, new UpsertOption[]{new UpsertOption("table1", null)}); - JSONObject records = new JSONObject(); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidColumnInUpsertOption.getDescription(), skyflowException.getMessage()); - } - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - InsertBulkOptions insertOptions = new InsertBulkOptions(true, new UpsertOption[]{new UpsertOption("table2", "")}); - JSONObject records = new JSONObject(); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.InvalidColumnInUpsertOption.getDescription(), skyflowException.getMessage()); - } - } - - - @Test - public void testInvalidConfigWithEmptyVaultIDIninsertBulk() { - Configuration.setLogLevel(LogLevel.WARN); - SkyflowConfiguration testConfig = new SkyflowConfiguration("", vaultURL, new DemoTokenProvider()); - try { - Skyflow skyflow = Skyflow.init(testConfig); - skyflow.insertBulk(new JSONObject(), new InsertBulkOptions()); - } catch (SkyflowException e) { - assertEquals(e.getCode(), ErrorCode.EmptyVaultID.getCode()); - assertEquals(e.getMessage(), ErrorCode.EmptyVaultID.getDescription()); - } - } - - @Test - public void testInvalidConfigWithInvalidVaultURLIninsertBulk() { - Configuration.setLogLevel(LogLevel.OFF); - SkyflowConfiguration testConfig = new SkyflowConfiguration(vaultID, "//valid.url.com", new DemoTokenProvider()); - try { - Skyflow skyflow = Skyflow.init(testConfig); - skyflow.insertBulk(new JSONObject(), new InsertBulkOptions()); - } catch (SkyflowException e) { - assertEquals(e.getCode(), ErrorCode.InvalidVaultURL.getCode()); - assertEquals(e.getMessage(), ErrorCode.InvalidVaultURL.getDescription()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkSuccessWithUpsertOptions() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", tableName); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - UpsertOption upsertOption = new UpsertOption(tableName, columnName); - InsertBulkOptions insertOptions = new InsertBulkOptions(new UpsertOption[]{upsertOption}); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = - "{\"records\":[{\"skyflow_id\":\"id1\", \"tokens\":{\"first_name\":\"token1\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - JSONArray responseRecords = (JSONArray) res.get("records"); - - assertEquals(1, responseRecords.size()); - assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - assertNotNull(((JSONObject) responseRecords.get(0)).get("fields")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkSuccessWithoutTokens() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", tableName); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertBulkOptions insertOptions = new InsertBulkOptions(false); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = "{\"records\":[{\"skyflow_id\":\"id1\"}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - JSONArray responseRecords = (JSONArray) res.get("records"); - - assertEquals(1, responseRecords.size()); - assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - assertNotNull(((JSONObject) responseRecords.get(0)).get("skyflow_id")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - public void testInsertBulkWithInvalidSkyflowConfig() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, null); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - - JSONObject res = skyflowClient.insertBulk(records); - } catch (SkyflowException e) { - assertEquals(ErrorCode.InvalidTokenProvider.getDescription(), e.getMessage()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkSuccessWithTokens() { - try { - SkyflowConfiguration config = new SkyflowConfiguration("vaultID", "https://vaulturl.com", new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", tableName); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertBulkOptions insertOptions = new InsertBulkOptions(); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = - "{\"records\":[{\"skyflow_id\":\"id1\", \"tokens\":{\"first_name\":\"token1\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - JSONArray responseRecords = (JSONArray) res.get("records"); - - assertEquals(1, responseRecords.size()); - assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - assertNotNull(((JSONObject) responseRecords.get(0)).get("fields")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkErrorsWithTokens() { - try { - SkyflowConfiguration config = new SkyflowConfiguration("vaultID", "https://vaulturl.com", new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", tableName); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertBulkOptions insertOptions = new InsertBulkOptions(); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = - "{\"error\":{\"grpc_code\":3,\"http_code\":400,\"message\":\"Invalid field present in JSON cardholder_nam\",\"http_status\":\"Bad Request\",\"details\":[]}}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenThrow(new SkyflowException(500, mockResponse)); - - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - JSONArray errors = (JSONArray) skyflowException.getData().get("errors"); - Assert.assertEquals(1, errors.size()); - skyflowException.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkSuccessWithoutInsertOptions() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", tableName); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = - "{\"records\":[{\"skyflow_id\":\"id1\", \"tokens\":{\"first_name\":\"token1\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse); - JSONObject res = skyflowClient.insertBulk(records); - JSONArray responseRecords = (JSONArray) res.get("records"); - - assertEquals(1, responseRecords.size()); - assertEquals(tableName, ((JSONObject) responseRecords.get(0)).get("table")); - assertNotNull(((JSONObject) responseRecords.get(0)).get("fields")); - } catch (SkyflowException skyflowException) { - skyflowException.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkErrorsWithTokensParseException() { - try { - SkyflowConfiguration config = new SkyflowConfiguration("vaultID", "https://vaulturl.com", new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", tableName); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - - InsertBulkOptions insertOptions = new InsertBulkOptions(); - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse = - "{\"grpc_code\":3,\"http_code\":400,\"message\":\"Invalid field present in JSON cardholder_nam\",\"http_status\":\"Bad Request\",\"details\":"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenThrow(new SkyflowException(500, mockResponse)); - - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - JSONArray errors = (JSONArray) skyflowException.getData().get("errors"); - Assert.assertEquals(1, errors.size()); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkPartialSuccess() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", "pii_fields"); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - JSONObject record2 = new JSONObject(); - record2.put("table", "cards"); - JSONObject fields2 = new JSONObject(); - fields.put(columnName, "first"); - record2.put("fields", fields2); - recordsArray.add(record2); - - - records.put("records", recordsArray); - String firstRequestUrl = "https://test.com/v1/vaults/vault123/pii_fields"; - String secondRequestUrl = "https://test.com/v1/vaults/vault123/cards"; - - - PowerMockito.mockStatic(HttpUtility.class); - String mockResponse2 = - "{\"records\":[{\"skyflow_id\":\"id1\", \"tokens\":{\"first_name\":\"token1\"}}]}"; - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.eq(new URL(firstRequestUrl)), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenReturn(mockResponse2); - - String mockResponse = - "{\"error\":{\"grpc_code\":3,\"http_code\":400,\"message\":\"Invalid field present in JSON cardholder_nam\",\"http_status\":\"Bad Request\",\"details\":[]}}"; - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.eq(new URL(secondRequestUrl)), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new SkyflowException(500, mockResponse - )); - - JSONObject res = skyflowClient.insertBulk(records); - - } catch (SkyflowException e) { - JSONObject partialError = e.getData(); - Assert.assertTrue(partialError.containsKey("records")); - Assert.assertTrue(partialError.containsKey("errors")); - JSONArray records = (JSONArray) e.getData().get("records"); - - Assert.assertEquals(1, records.size()); - - JSONArray errors = (JSONArray) e.getData().get("errors"); - Assert.assertEquals(1, errors.size()); - } catch (IOException e) { - e.printStackTrace(); - fail(INVALID_EXCEPTION_THROWN); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkInterruptedException() { - try { - SkyflowConfiguration config = new SkyflowConfiguration("vaultID", "https://demo.com", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - record.put("table", tableName); - JSONObject fields = new JSONObject(); - fields.put(columnName, "first"); - record.put("fields", fields); - - recordsArray.add(record); - - records.put("records", recordsArray); - PowerMockito.mockStatic(HttpUtility.class); - - InsertBulkOptions insertOptions = new InsertBulkOptions(true); - PowerMockito.when(HttpUtility.sendRequest(ArgumentMatchers.anyString(), - ArgumentMatchers.any(), - ArgumentMatchers.any(), - ArgumentMatchers.anyMap())) - .thenThrow(new IOException("Exception occurred")); - Callable mockCallable = mock(Callable.class); - when(mockCallable.call()).thenThrow(new InterruptedException("Thread was interrupted")); - - FutureTask mockFutureTask = new FutureTask<>(mockCallable); - mockFutureTask.run(); - - when(mockFutureTask.get()).thenThrow(new InterruptedException("Thread was interrupted")); - - PowerMockito.mockStatic(HttpUtility.class); - PowerMockito.when(HttpUtility.sendRequest(anyString(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyMap())).thenThrow(new InterruptedException("Thread was interrupted")); - - - JSONObject response = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException e) { - String error = e.getMessage(); - assertEquals(ErrorCode.ThreadExecutionException.getDescription(), error); - } catch (IOException exception) { - exception.printStackTrace(); - Assert.fail(INVALID_EXCEPTION_THROWN); - } catch (Exception e) { - Assert.assertTrue((e.toString()).contains(ErrorCode.ThreadInterruptedException.getDescription())); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkEmptyRecords() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - records.put("records", recordsArray); - - InsertBulkOptions insertOptions = new InsertBulkOptions(false); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.EmptyRecords.getDescription(), skyflowException.getMessage()); - } - } - @Test - @PrepareForTest(fullyQualifiedNames = {"com.skyflow.common.utils.HttpUtility", "com.skyflow.common.utils.TokenUtils"}) - public void testInsertBulkEmptyRecordsCase2() { - try { - SkyflowConfiguration config = new SkyflowConfiguration(vaultID, vaultURL, new DemoTokenProvider()); - - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - - records.put("records", null); - - InsertBulkOptions insertOptions = new InsertBulkOptions(false); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - } catch (SkyflowException skyflowException) { - assertEquals(ErrorCode.EmptyRecords.getDescription(), skyflowException.getMessage()); - } - } -} - diff --git a/v1/src/test/resources/invalidCredentials.json b/v1/src/test/resources/invalidCredentials.json deleted file mode 100644 index 9e26dfee..00000000 --- a/v1/src/test/resources/invalidCredentials.json +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/v1/src/test/resources/notJson.txt b/v1/src/test/resources/notJson.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/v2/pom.xml b/v2/pom.xml deleted file mode 100644 index bddf1ae2..00000000 --- a/v2/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - 4.0.0 - - com.skyflow - skyflow-java - 1.15.0 - - - v2 - - - 8 - 8 - UTF-8 - 4.12.0 - 2.10.1 - 1.9.0 - 5.10.3 - 1.10.0 - - - - - io.github.cdimascio - dotenv-java - 3.0.0 - - - com.google.code.findbugs - jsr305 - 3.0.2 - - - io.gsonfire - gson-fire - ${gson-fire-version} - - - com.google.code.gson - gson - ${gson-version} - - - com.squareup.okhttp3 - okhttp - ${okhttp-version} - - - com.squareup.okhttp3 - logging-interceptor - ${okhttp-version} - - - - org.junit.jupiter - junit-jupiter-engine - ${junit-version} - test - - - org.junit.platform - junit-platform-runner - ${junit-platform-runner.version} - test - - - \ No newline at end of file From 60279729bc72e2bc54b05dd019aaa98895b0b738 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 15 Nov 2024 19:18:17 +0530 Subject: [PATCH 044/126] SK-1623 Downgrade dotenv to work with java 8 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 12533834..b719865b 100644 --- a/pom.xml +++ b/pom.xml @@ -60,7 +60,7 @@ io.github.cdimascio dotenv-java - 3.0.0 + 2.2.0 com.google.code.findbugs From f4affdf383001e4a9eb58b85e91d6a43dfb1e55b Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 18 Nov 2024 12:15:09 +0530 Subject: [PATCH 045/126] SK-1767 Fix unit tests not running in CI pipeline --- pom.xml | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/pom.xml b/pom.xml index b719865b..8b8452dc 100644 --- a/pom.xml +++ b/pom.xml @@ -39,8 +39,8 @@ 1.9.0 UTF-8 4.12.0 - 5.10.3 - 1.10.0 + 4.13.2 + 2.3.1 1.3.5 @@ -104,20 +104,18 @@ ${jakarta-annotation-version} provided - - org.junit.jupiter - junit-jupiter-engine - ${junit-version} - test + javax.xml.bind + jaxb-api + ${javax-xml-bind-version} + - org.junit.platform - junit-platform-runner - ${junit-platform-runner.version} + junit + junit + ${junit-version} test - org.powermock powermock-module-junit4 From 8fa94f7ea79c79bbd2e6ac6421aa561fb8b92ebd Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 18 Nov 2024 12:45:34 +0530 Subject: [PATCH 046/126] SK-1767 Add new secret for Java SDK v2 tests --- .github/workflows/pr.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index c3a33dc8..3e8586a2 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -32,7 +32,7 @@ jobs: json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - name: Build & Run tests with Maven - run: mvn -B package -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -DTEST_DATA_CREDENTIALS_FILE=${{ secrets.TEST_DATA_CREDENTIALS_FILE }} -f pom.xml + run: mvn -B package -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -DTEST_DATA_CREDENTIALS_FILE=${{ secrets.TEST_DATA_CREDENTIALS_FILE }} -DSKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} -f pom.xml - name: Codecov uses: codecov/codecov-action@v2.1.0 From 8e9193ea9d23d9e9cfaeebd3b96e024e55dea38d Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 18 Nov 2024 15:03:23 +0530 Subject: [PATCH 047/126] SK-1767 Fix issues in CI pipeline --- .github/workflows/pr.yml | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 3e8586a2..a2d39562 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -1,6 +1,6 @@ name: PR CI Checks -on: [ pull_request ] +on: [pull_request] jobs: check-commit-message: @@ -11,18 +11,18 @@ jobs: uses: gsactions/commit-message-checker@v1 with: pattern: '\[?[A-Z]{1,5}-[1-9][0-9]*.+$' - flags: 'gm' - excludeDescription: 'true' - checkAllCommitMessages: 'true' + flags: "gm" + excludeDescription: "true" + checkAllCommitMessages: "true" accessToken: ${{ secrets.PAT_ACTIONS }} - error: 'One of your your commit messages is not matching the format with JIRA ID Ex: ( SDK-123 commit message )' + error: "One of your your commit messages is not matching the format with JIRA ID Ex: ( SDK-123 commit message )" Test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions/setup-java@v1 with: - java-version: '1.8' + java-version: "1.8" - name: create-json id: create-json @@ -31,8 +31,15 @@ jobs: name: "credentials.json" json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} + - name: create env + id: create-env + run: | + touch .env + echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env + echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + - name: Build & Run tests with Maven - run: mvn -B package -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -DTEST_DATA_CREDENTIALS_FILE=${{ secrets.TEST_DATA_CREDENTIALS_FILE }} -DSKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} -f pom.xml + run: mvn -B package -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -DTEST_DATA_CREDENTIALS_FILE=${{ secrets.TEST_DATA_CREDENTIALS_FILE }} -f pom.xml - name: Codecov uses: codecov/codecov-action@v2.1.0 From f63b903c2421e678a98d7800c3fd6ac9c3dc38e1 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 18 Nov 2024 15:10:16 +0530 Subject: [PATCH 048/126] SK-1767 Fix compilation issues in CI pipeline - Excluding generating code from javadoc generation --- pom.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pom.xml b/pom.xml index 8b8452dc..ea4cbd29 100644 --- a/pom.xml +++ b/pom.xml @@ -160,6 +160,14 @@ org.apache.maven.plugins maven-javadoc-plugin 3.2.0 + + + :com.skyflow.generated.rest + :com.skyflow.generated.rest.api + :com.skyflow.generated.rest.auth + :com.skyflow.generated.rest.models + + attach-javadocs From f092e787b06badb443fe358128a165cb8802cdf7 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 19 Nov 2024 11:37:45 +0530 Subject: [PATCH 049/126] SK-1682 Modified the structure of Skyflow error --- .../com/skyflow/errors/SkyflowException.java | 46 ++++++++++++++----- src/test/java/com/skyflow/SkyflowTests.java | 30 ++++++------ .../skyflow/config/ConnectionConfigTests.java | 12 ++--- .../com/skyflow/config/CredentialsTests.java | 20 ++++---- .../com/skyflow/config/VaultConfigTests.java | 8 ++-- .../serviceaccount/util/BearerTokenTests.java | 24 +++++----- .../util/SignedDataTokensTests.java | 20 ++++---- .../java/com/skyflow/utils/UtilsTests.java | 4 +- .../connection/InvokeConnectionTests.java | 32 ++++++------- .../controller/ConnectionControllerTests.java | 2 +- .../controller/VaultControllerTests.java | 18 +++++--- .../com/skyflow/vault/data/DeleteTests.java | 10 ++-- .../java/com/skyflow/vault/data/GetTests.java | 40 ++++++++-------- .../com/skyflow/vault/data/InsertTests.java | 34 +++++++------- .../com/skyflow/vault/data/QueryTests.java | 4 +- .../com/skyflow/vault/data/UpdateTests.java | 32 ++++++------- .../skyflow/vault/tokens/DetokenizeTests.java | 6 +-- .../skyflow/vault/tokens/TokenizeTests.java | 8 ++-- 18 files changed, 187 insertions(+), 163 deletions(-) diff --git a/src/main/java/com/skyflow/errors/SkyflowException.java b/src/main/java/com/skyflow/errors/SkyflowException.java index 625b0d2e..6cff3cdd 100644 --- a/src/main/java/com/skyflow/errors/SkyflowException.java +++ b/src/main/java/com/skyflow/errors/SkyflowException.java @@ -11,8 +11,10 @@ public class SkyflowException extends Exception { private String requestId; - private int code; + private Integer grpcCode; + private Integer httpCode; private String message; + private String httpStatus; private JsonArray details; private JsonObject responseBody; @@ -23,21 +25,23 @@ public SkyflowException(String message) { public SkyflowException(Throwable cause) { super(cause); + this.message = cause.getMessage(); } public SkyflowException(String message, Throwable cause) { super(message, cause); + this.message = message; } public SkyflowException(int code, String message) { super(message); - this.code = code; + this.httpCode = code; this.message = message; } - public SkyflowException(int code, Throwable cause, Map> responseHeaders, String responseBody) { + public SkyflowException(int httpCode, Throwable cause, Map> responseHeaders, String responseBody) { this(cause); - this.code = code; + this.httpCode = httpCode; String contentType = responseHeaders.get("content-type").get(0); setRequestId(responseHeaders); if (Objects.equals(contentType, "application/json")) { @@ -51,6 +55,8 @@ private void setResponseBody(String responseBody) { try { if (responseBody != null) { this.responseBody = JsonParser.parseString(responseBody).getAsJsonObject(); + setGrpcCode(); + setHttpStatus(); setMessage(); setDetails(); } @@ -74,12 +80,32 @@ private void setMessage() { this.message = ((JsonObject) responseBody.get("error")).get("message").getAsString(); } + private void setGrpcCode() { + this.grpcCode = ((JsonObject) responseBody.get("error")).get("grpc_code").getAsInt(); + } + + private void setHttpStatus() { + this.httpStatus = ((JsonObject) responseBody.get("error")).get("http_status").getAsString(); + } + private void setDetails() { this.details = ((JsonObject) responseBody.get("error")).get("details").getAsJsonArray(); } - public int getCode() { - return code; + public int getHttpCode() { + return httpCode; + } + + public JsonArray getDetails() { + return details; + } + + public Integer getGrpcCode() { + return grpcCode; + } + + public String getHttpStatus() { + return httpStatus; } @Override @@ -90,12 +116,8 @@ public String getMessage() { @Override public String toString() { return String.format( - "%n requestId: %s%n code: %s%n message: %s", - this.requestId, this.code, this.message + "%n requestId: %s%n grpcCode: %s%n httpCode: %s%n httpStatus: %s%n message: %s%n details: %s", + this.requestId, this.grpcCode, this.httpCode, this.httpStatus, this.message, this.details ); } - - public JsonArray getDetails() { - return details; - } } diff --git a/src/test/java/com/skyflow/SkyflowTests.java b/src/test/java/com/skyflow/SkyflowTests.java index efdc54dc..041969a7 100644 --- a/src/test/java/com/skyflow/SkyflowTests.java +++ b/src/test/java/com/skyflow/SkyflowTests.java @@ -44,7 +44,7 @@ public void testAddingInvalidVaultConfigInSkyflowBuilder() { Skyflow.builder().addVaultConfig(config).build(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyVaultId.getMessage(), e.getMessage()); } } @@ -60,7 +60,7 @@ public void testAddingInvalidVaultConfigInSkyflowClient() { skyflowClient.addVaultConfig(config); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyVaultId.getMessage(), e.getMessage()); } } @@ -90,7 +90,7 @@ public void testAddingExistingVaultConfigInSkyflowClient() { skyflowClient.addVaultConfig(config).addVaultConfig(config); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.VaultIdAlreadyInConfigList.getMessage(), e.getMessage()); } } @@ -105,7 +105,7 @@ public void testUpdatingNonExistentVaultConfigInSkyflowBuilder() { Skyflow.builder().updateVaultConfig(config).build(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); } } @@ -121,7 +121,7 @@ public void testUpdatingNonExistentVaultConfigInSkyflowClient() { skyflowClient.updateVaultConfig(config); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); } catch (Exception e) { Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); @@ -158,7 +158,7 @@ public void testRemovingNonExistentVaultConfigInSkyflowBuilder() { Skyflow.builder().removeVaultConfig(vaultID).build(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); } } @@ -184,7 +184,7 @@ public void testRemovingValidVaultConfigInSkyflowClient() { skyflowClient.removeVaultConfig(vaultID); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); } } @@ -210,7 +210,7 @@ public void testAddingInvalidConnectionConfigInSkyflowBuilder() { Skyflow.builder().addConnectionConfig(config).build(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyConnectionId.getMessage(), e.getMessage()); } } @@ -225,7 +225,7 @@ public void testAddingInvalidConnectionConfigInSkyflowClient() { skyflowClient.addConnectionConfig(config); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyConnectionId.getMessage(), e.getMessage()); } } @@ -253,7 +253,7 @@ public void testAddingExistingConnectionConfigInSkyflowClient() { skyflowClient.addConnectionConfig(config); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.ConnectionIdAlreadyInConfigList.getMessage(), e.getMessage()); } } @@ -267,7 +267,7 @@ public void testUpdatingNonExistentConnectionConfigInSkyflowBuilder() { Skyflow.builder().updateConnectionConfig(config).build(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.ConnectionIdNotInConfigList.getMessage(), e.getMessage()); } } @@ -282,7 +282,7 @@ public void testUpdatingNonExistentConnectionConfigInSkyflowClient() { skyflowClient.updateConnectionConfig(config); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.ConnectionIdNotInConfigList.getMessage(), e.getMessage()); } } @@ -313,7 +313,7 @@ public void testRemovingNonExistentConnectionConfigInSkyflowBuilder() { Skyflow.builder().removeConnectionConfig(connectionID).build(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.ConnectionIdNotInConfigList.getMessage(), e.getMessage()); } } @@ -325,7 +325,7 @@ public void testRemovingNonExistentConnectionConfigInSkyflowClient() { skyflowClient.removeConnectionConfig(connectionID); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.ConnectionIdNotInConfigList.getMessage(), e.getMessage()); } } @@ -361,7 +361,7 @@ public void testAddingInvalidSkyflowCredentialsInSkyflowBuilder() { Skyflow.builder().addSkyflowCredentials(credentials).build(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.NoTokenGenerationMeansPassed.getMessage(), e.getMessage()); } } diff --git a/src/test/java/com/skyflow/config/ConnectionConfigTests.java b/src/test/java/com/skyflow/config/ConnectionConfigTests.java index 03b1021e..5ff32ca5 100644 --- a/src/test/java/com/skyflow/config/ConnectionConfigTests.java +++ b/src/test/java/com/skyflow/config/ConnectionConfigTests.java @@ -1,7 +1,5 @@ package com.skyflow.config; -import com.skyflow.config.ConnectionConfig; -import com.skyflow.config.Credentials; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; @@ -82,7 +80,7 @@ public void testNoConnectionIdInConnectionConfig() { Validations.validateConnectionConfig(connectionConfig); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidConnectionId.getMessage(), e.getMessage()); } } @@ -96,7 +94,7 @@ public void testEmptyConnectionIdInConnectionConfig() { Validations.validateConnectionConfig(connectionConfig); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyConnectionId.getMessage(), e.getMessage()); } } @@ -109,7 +107,7 @@ public void testNoConnectionURLInConnectionConfig() { Validations.validateConnectionConfig(connectionConfig); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidConnectionUrl.getMessage(), e.getMessage()); } } @@ -123,7 +121,7 @@ public void testEmptyConnectionURLInConnectionConfig() { Validations.validateConnectionConfig(connectionConfig); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyConnectionUrl.getMessage(), e.getMessage()); } } @@ -137,7 +135,7 @@ public void testInvalidConnectionURLInConnectionConfig() { Validations.validateConnectionConfig(connectionConfig); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidConnectionUrlFormat.getMessage(), e.getMessage()); } } diff --git a/src/test/java/com/skyflow/config/CredentialsTests.java b/src/test/java/com/skyflow/config/CredentialsTests.java index 1b7f6e64..cfc61de6 100644 --- a/src/test/java/com/skyflow/config/CredentialsTests.java +++ b/src/test/java/com/skyflow/config/CredentialsTests.java @@ -136,7 +136,7 @@ public void testEmptyPathInCredentials() { Validations.validateCredentials(credentials); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyCredentialFilePath.getMessage(), e.getMessage()); } } @@ -149,7 +149,7 @@ public void testEmptyCredentialsStringInCredentials() { Validations.validateCredentials(credentials); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyCredentialsString.getMessage(), e.getMessage()); } } @@ -162,7 +162,7 @@ public void testEmptyTokenInCredentials() { Validations.validateCredentials(credentials); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyToken.getMessage(), e.getMessage()); } } @@ -175,7 +175,7 @@ public void testEmptyApikeyInCredentials() { Validations.validateCredentials(credentials); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyApikey.getMessage(), e.getMessage()); } } @@ -188,7 +188,7 @@ public void testInvalidApikeyInCredentials() { Validations.validateCredentials(credentials); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidApikey.getMessage(), e.getMessage()); } } @@ -202,7 +202,7 @@ public void testBothTokenAndPathInCredentials() { Validations.validateCredentials(credentials); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.MultipleTokenGenerationMeansPassed.getMessage(), e.getMessage()); } } @@ -214,7 +214,7 @@ public void testNothingPassedInCredentials() { Validations.validateCredentials(credentials); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.NoTokenGenerationMeansPassed.getMessage(), e.getMessage()); } } @@ -228,7 +228,7 @@ public void testEmptyRolesInCredentials() { Validations.validateCredentials(credentials); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyRoles.getMessage(), e.getMessage()); } } @@ -244,7 +244,7 @@ public void testEmptyRoleInRolesInCredentials() { Validations.validateCredentials(credentials); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyRoleInRoles.getMessage(), e.getMessage()); } } @@ -258,7 +258,7 @@ public void testEmptyContextInCredentials() { Validations.validateCredentials(credentials); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyContext.getMessage(), e.getMessage()); } } diff --git a/src/test/java/com/skyflow/config/VaultConfigTests.java b/src/test/java/com/skyflow/config/VaultConfigTests.java index 478f8cf0..1a5ca703 100644 --- a/src/test/java/com/skyflow/config/VaultConfigTests.java +++ b/src/test/java/com/skyflow/config/VaultConfigTests.java @@ -121,7 +121,7 @@ public void testNoVaultIdInVaultConfigInValidations() { Validations.validateVaultConfig(vaultConfig); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidVaultId.getMessage(), e.getMessage()); } } @@ -136,7 +136,7 @@ public void testEmptyVaultIdInVaultConfigInValidations() { Validations.validateVaultConfig(vaultConfig); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyVaultId.getMessage(), e.getMessage()); } } @@ -150,7 +150,7 @@ public void testNoClusterIdInVaultConfigInValidations() { Validations.validateVaultConfig(vaultConfig); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidClusterId.getMessage(), e.getMessage()); } } @@ -165,7 +165,7 @@ public void testEmptyClusterIdInVaultConfigInValidations() { Validations.validateVaultConfig(vaultConfig); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyClusterId.getMessage(), e.getMessage()); } } diff --git a/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java b/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java index 3993e476..52272933 100644 --- a/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java +++ b/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java @@ -62,7 +62,7 @@ public void testEmptyCredentialsFilePath() { bearerToken.getBearerToken(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); } } @@ -75,7 +75,7 @@ public void testInvalidFilePath() { bearerToken.getBearerToken(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); } } @@ -88,7 +88,7 @@ public void testInvalidCredentialsFile() { bearerToken.getBearerToken(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.FileInvalidJson.getMessage(), invalidJsonFilePath), e.getMessage() @@ -103,7 +103,7 @@ public void testEmptyCredentialsString() { bearerToken.getBearerToken(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); } } @@ -115,7 +115,7 @@ public void testInvalidCredentialsString() { bearerToken.getBearerToken(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); } } @@ -130,7 +130,7 @@ public void testNoPrivateKeyInCredentialsForCredentials() { bearerToken.getBearerToken(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.MissingPrivateKey.getMessage(), e.getMessage()); } } @@ -144,7 +144,7 @@ public void testNoClientIDInCredentialsForCredentials() { bearerToken.getBearerToken(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.MissingClientId.getMessage(), e.getMessage()); } } @@ -158,7 +158,7 @@ public void testNoKeyIDInCredentialsForCredentials() { bearerToken.getBearerToken(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.MissingKeyId.getMessage(), e.getMessage()); } } @@ -172,7 +172,7 @@ public void testNoTokenURIInCredentialsForCredentials() { bearerToken.getBearerToken(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.MissingTokenUri.getMessage(), e.getMessage()); } } @@ -186,7 +186,7 @@ public void testInvalidPrivateKeyInCredentialsForCredentials() { bearerToken.getBearerToken(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.JwtInvalidFormat.getMessage(), e.getMessage()); } } @@ -199,7 +199,7 @@ public void testInvalidKeySpecInCredentialsForCredentials() { bearerToken.getBearerToken(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidKeySpec.getMessage(), e.getMessage()); } } @@ -213,7 +213,7 @@ public void testInvalidTokenURIInCredentialsForCredentials() throws SkyflowExcep bearerToken.getBearerToken(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidTokenUri.getMessage(), e.getMessage()); } } diff --git a/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java index e5ce56b1..5e631995 100644 --- a/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java +++ b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java @@ -68,7 +68,7 @@ public void testEmptyCredentialsFilePath() { signedTokens.getSignedDataTokens(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); } } @@ -81,7 +81,7 @@ public void testInvalidFilePath() { signedTokens.getSignedDataTokens(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); } } @@ -94,7 +94,7 @@ public void testInvalidCredentialsFile() { signedTokens.getSignedDataTokens(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.FileInvalidJson.getMessage(), invalidJsonFilePath), e.getMessage() @@ -112,7 +112,7 @@ public void testEmptyCredentialsString() { } catch (SkyflowException e) { System.out.println("caught skyflow exception"); System.out.println(e); - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.InvalidCredentials.getMessage(), invalidJsonFilePath), e.getMessage() @@ -130,7 +130,7 @@ public void testInvalidCredentialsString() { signedTokens.getSignedDataTokens(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.CredentialsStringInvalidJson.getMessage(), invalidJsonFilePath), e.getMessage() @@ -147,7 +147,7 @@ public void testNoPrivateKeyInCredentials() { signedTokens.getSignedDataTokens(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.MissingPrivateKey.getMessage(), e.getMessage()); } } @@ -161,7 +161,7 @@ public void testNoClientIDInCredentials() { signedTokens.getSignedDataTokens(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.MissingClientId.getMessage(), e.getMessage()); } } @@ -175,7 +175,7 @@ public void testNoKeyIDInCredentials() { signedTokens.getSignedDataTokens(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.MissingKeyId.getMessage(), e.getMessage()); } } @@ -189,7 +189,7 @@ public void testInvalidPrivateKeyInCredentials() { signedTokens.getSignedDataTokens(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.JwtInvalidFormat.getMessage(), e.getMessage()); } } @@ -202,7 +202,7 @@ public void testInvalidKeySpecInCredentials() { signedTokens.getSignedDataTokens(); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidKeySpec.getMessage(), e.getMessage()); } } diff --git a/src/test/java/com/skyflow/utils/UtilsTests.java b/src/test/java/com/skyflow/utils/UtilsTests.java index 5a1b9de7..79817bc5 100644 --- a/src/test/java/com/skyflow/utils/UtilsTests.java +++ b/src/test/java/com/skyflow/utils/UtilsTests.java @@ -115,7 +115,7 @@ public void testGenerateBearerTokenWithCredentialsFile() { Utils.generateBearerToken(credentials); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); } } @@ -130,7 +130,7 @@ public void testGenerateBearerTokenWithCredentialsString() { Utils.generateBearerToken(credentials); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.CredentialsStringInvalidJson.getMessage(), e.getMessage()); } } diff --git a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java index db23e010..8d950279 100644 --- a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java +++ b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java @@ -76,7 +76,7 @@ public void testEmptyRequestHeadersInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyRequestHeaders.getMessage(), e.getMessage()); } } @@ -96,7 +96,7 @@ public void testNullRequestHeaderKeyInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidRequestHeaders.getMessage(), e.getMessage()); } } @@ -116,7 +116,7 @@ public void testEmptyRequestHeaderKeyInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidRequestHeaders.getMessage(), e.getMessage()); } } @@ -136,7 +136,7 @@ public void testNullRequestHeaderValueInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidRequestHeaders.getMessage(), e.getMessage()); } } @@ -156,7 +156,7 @@ public void testEmptyRequestHeaderValueInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidRequestHeaders.getMessage(), e.getMessage()); } } @@ -175,7 +175,7 @@ public void testEmptyPathParamsInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyPathParams.getMessage(), e.getMessage()); } } @@ -196,7 +196,7 @@ public void testNullPathParamKeyInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidPathParams.getMessage(), e.getMessage()); } } @@ -217,7 +217,7 @@ public void testEmptyPathParamKeyInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidPathParams.getMessage(), e.getMessage()); } } @@ -238,7 +238,7 @@ public void testNullPathParamValueInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidPathParams.getMessage(), e.getMessage()); } } @@ -259,7 +259,7 @@ public void testEmptyPathParamValueInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidPathParams.getMessage(), e.getMessage()); } } @@ -279,7 +279,7 @@ public void testEmptyQueryParamsInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyQueryParams.getMessage(), e.getMessage()); } } @@ -301,7 +301,7 @@ public void testNullQueryParamKeyInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidQueryParams.getMessage(), e.getMessage()); } } @@ -323,7 +323,7 @@ public void testEmptyQueryParamKeyInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidQueryParams.getMessage(), e.getMessage()); } } @@ -345,7 +345,7 @@ public void testNullQueryParamValueInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidQueryParams.getMessage(), e.getMessage()); } } @@ -367,7 +367,7 @@ public void testEmptyQueryParamValueInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InvalidQueryParams.getMessage(), e.getMessage()); } } @@ -388,7 +388,7 @@ public void testEmptyRequestBodyInInvokeConnectionRequestValidations() { Validations.validateInvokeConnectionRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyRequestBody.getMessage(), e.getMessage()); } } diff --git a/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java b/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java index 0b933b4a..036dfdcd 100644 --- a/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java +++ b/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java @@ -42,7 +42,7 @@ public void testInvalidRequestInInvokeConnectionMethod() { skyflowClient.connection().invoke(connectionRequest); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyRequestHeaders.getMessage(), e.getMessage()); } } diff --git a/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java index ecfca480..ca2e85d9 100644 --- a/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java +++ b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java @@ -52,7 +52,7 @@ public void testInvalidRequestInInsertMethod() { skyflowClient.vault().insert(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -68,7 +68,7 @@ public void testInvalidRequestInDetokenizeMethod() { skyflowClient.vault().detokenize(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.InvalidDataTokens.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -84,7 +84,7 @@ public void testInvalidRequestInGetMethod() { skyflowClient.vault().get(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -100,7 +100,7 @@ public void testInvalidRequestInUpdateMethod() { skyflowClient.vault().update(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -116,7 +116,7 @@ public void testInvalidRequestInDeleteMethod() { skyflowClient.vault().delete(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -132,7 +132,7 @@ public void testInvalidRequestInQueryMethod() { skyflowClient.vault().query(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.QueryKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -148,11 +148,15 @@ public void testInvalidRequestInTokenizeMethod() { skyflowClient.vault().tokenize(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.ColumnValuesKeyErrorTokenize.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); + Assert.assertNull(e.getRequestId()); + Assert.assertNull(e.getGrpcCode()); + Assert.assertNull(e.getHttpStatus()); + Assert.assertNull(e.getDetails()); } } diff --git a/src/test/java/com/skyflow/vault/data/DeleteTests.java b/src/test/java/com/skyflow/vault/data/DeleteTests.java index 5f2eefc7..8cb43880 100644 --- a/src/test/java/com/skyflow/vault/data/DeleteTests.java +++ b/src/test/java/com/skyflow/vault/data/DeleteTests.java @@ -84,7 +84,7 @@ public void testNoIdsInDeleteRequestValidations() { Validations.validateDeleteRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.IdsKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -100,7 +100,7 @@ public void testEmptyIdsInDeleteRequestValidations() { Validations.validateDeleteRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyIds.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -117,7 +117,7 @@ public void testEmptyIdInIdsInDeleteRequestValidations() { Validations.validateDeleteRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyIdInIds.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -134,7 +134,7 @@ public void testNoTableInDeleteRequestValidations() { Validations.validateDeleteRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -151,7 +151,7 @@ public void testEmptyTableInDeleteRequestValidations() { Validations.validateDeleteRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyTable.getMessage(), Constants.SDK_PREFIX), e.getMessage() diff --git a/src/test/java/com/skyflow/vault/data/GetTests.java b/src/test/java/com/skyflow/vault/data/GetTests.java index 140990a7..f9fa98d9 100644 --- a/src/test/java/com/skyflow/vault/data/GetTests.java +++ b/src/test/java/com/skyflow/vault/data/GetTests.java @@ -148,7 +148,7 @@ public void testNoTableInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -164,7 +164,7 @@ public void testEmptyTableInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyTable.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -179,7 +179,7 @@ public void testEmptyIdsInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyIds.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -196,7 +196,7 @@ public void testEmptyIdInIdsInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyIdInIds.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -212,7 +212,7 @@ public void testEmptyFieldsInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyFields.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -230,7 +230,7 @@ public void testEmptyFieldInFieldsInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyFieldInFields.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -245,7 +245,7 @@ public void testNoRedactionInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.RedactionKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -262,7 +262,7 @@ public void testReturnTokensWithRedactionInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.RedactionWithTokensNotSupported.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -277,7 +277,7 @@ public void testReturnTokensWithColumnNameInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.TokensGetColumnNotSupported.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -292,7 +292,7 @@ public void testReturnTokensWithColumnValuesInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.TokensGetColumnNotSupported.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -309,7 +309,7 @@ public void testEmptyOffsetInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyOffset.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -326,7 +326,7 @@ public void testEmptyLimitInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyLimit.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -341,7 +341,7 @@ public void testNoIdsOrColumnNameInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.UniqueColumnOrIdsKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -359,7 +359,7 @@ public void testBothIdsAndColumnNameInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.BothIdsAndColumnDetailsSpecified.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -377,7 +377,7 @@ public void testBothIdsAndColumnValuesInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.BothIdsAndColumnDetailsSpecified.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -394,7 +394,7 @@ public void testColumnNameWithoutColumnValuesInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.ColumnValuesKeyErrorGet.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -411,7 +411,7 @@ public void testColumnValuesWithoutColumnNameInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.ColumnNameKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -428,7 +428,7 @@ public void testEmptyColumnNameInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyColumnName.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -445,7 +445,7 @@ public void testEmptyColumnValuesInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyColumnValues.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -464,7 +464,7 @@ public void testEmptyValueInColumnValuesInGetRequestValidations() { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyValueInColumnValues.getMessage(), Constants.SDK_PREFIX), e.getMessage() diff --git a/src/test/java/com/skyflow/vault/data/InsertTests.java b/src/test/java/com/skyflow/vault/data/InsertTests.java index 50b1e5fc..87057d7c 100644 --- a/src/test/java/com/skyflow/vault/data/InsertTests.java +++ b/src/test/java/com/skyflow/vault/data/InsertTests.java @@ -117,7 +117,7 @@ public void testNoTableInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -132,7 +132,7 @@ public void testEmptyTableInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyTable.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -147,7 +147,7 @@ public void testNoValuesInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.ValuesKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -162,7 +162,7 @@ public void testEmptyValuesInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyValues.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -179,7 +179,7 @@ public void testEmptyKeyInValuesInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyKeyInValues.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -196,7 +196,7 @@ public void testEmptyValueInValuesInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyValueInValues.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -212,7 +212,7 @@ public void testEmptyUpsertInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyUpsert.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -230,7 +230,7 @@ public void testUpsertWithHomogenousInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.HomogenousNotSupportedWithUpsert.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -246,7 +246,7 @@ public void testTokensWithTokenStrictDisableInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.TokensPassedForByotDisable.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -264,7 +264,7 @@ public void testNoTokensWithTokenStrictEnableInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE.toString()), e.getMessage() @@ -282,7 +282,7 @@ public void testNoTokensWithTokenStrictEnableStrictInInsertRequestValidations() Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString()), e.getMessage() @@ -300,7 +300,7 @@ public void testEmptyTokensWithTokenStrictEnableInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyTokens.getMessage(), e.getMessage()); } } @@ -316,7 +316,7 @@ public void testInsufficientTokensWithTokenStrictEnableStrictInInsertRequestVali Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage(), e.getMessage()); } } @@ -333,7 +333,7 @@ public void testInsufficientTokensWithTokenStrictEnableStrictInInsertRequestVali Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage(), e.getMessage()); } } @@ -350,7 +350,7 @@ public void testTokenValueMismatchInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.MismatchOfFieldsAndTokens.getMessage(), e.getMessage()); } } @@ -367,7 +367,7 @@ public void testEmptyKeyInTokensInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyKeyInTokens.getMessage(), e.getMessage()); } } @@ -384,7 +384,7 @@ public void testEmptyValueInTokensInInsertRequestValidations() { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyValueInTokens.getMessage(), e.getMessage()); } } diff --git a/src/test/java/com/skyflow/vault/data/QueryTests.java b/src/test/java/com/skyflow/vault/data/QueryTests.java index a84c9113..82b8499a 100644 --- a/src/test/java/com/skyflow/vault/data/QueryTests.java +++ b/src/test/java/com/skyflow/vault/data/QueryTests.java @@ -77,7 +77,7 @@ public void testNoQueryInQueryRequestValidations() { Validations.validateQueryRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.QueryKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -92,7 +92,7 @@ public void testEmptyQueryInQueryRequestValidations() { Validations.validateQueryRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyQuery.getMessage(), Constants.SDK_PREFIX), e.getMessage() diff --git a/src/test/java/com/skyflow/vault/data/UpdateTests.java b/src/test/java/com/skyflow/vault/data/UpdateTests.java index 22417257..e6c41db9 100644 --- a/src/test/java/com/skyflow/vault/data/UpdateTests.java +++ b/src/test/java/com/skyflow/vault/data/UpdateTests.java @@ -98,7 +98,7 @@ public void testNoSkyflowIdInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.SkyflowIdKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -113,7 +113,7 @@ public void testEmptySkyflowIdInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptySkyflowId.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -128,7 +128,7 @@ public void testNoTableInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -143,7 +143,7 @@ public void testEmptyTableInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyTable.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -158,7 +158,7 @@ public void testNoValuesInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.ValuesKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -173,7 +173,7 @@ public void testEmptyValuesInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyValues.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -191,7 +191,7 @@ public void testEmptyKeyInValuesInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyKeyInValues.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -209,7 +209,7 @@ public void testEmptyValueInValuesInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyValueInValues.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -229,7 +229,7 @@ public void testTokensWithTokenStrictDisableInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.TokensPassedForByotDisable.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -248,7 +248,7 @@ public void testNoTokensWithTokenStrictEnableInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE.toString()), e.getMessage() @@ -267,7 +267,7 @@ public void testNoTokensWithTokenStrictEnableStrictInUpdateRequestValidations() Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString()), e.getMessage() @@ -286,7 +286,7 @@ public void testEmptyTokensWithTokenStrictEnableInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyTokens.getMessage(), e.getMessage()); } } @@ -303,7 +303,7 @@ public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestVali Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage(), e.getMessage()); } } @@ -321,7 +321,7 @@ public void testTokenValueMismatchInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.MismatchOfFieldsAndTokens.getMessage(), e.getMessage()); } } @@ -339,7 +339,7 @@ public void testEmptyKeyInTokensInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyKeyInTokens.getMessage(), e.getMessage()); } } @@ -357,7 +357,7 @@ public void testEmptyValueInTokensInUpdateRequestValidations() { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyValueInTokens.getMessage(), e.getMessage()); } } diff --git a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index d569cbc9..3fe57faa 100644 --- a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -53,7 +53,7 @@ public void testNoTokensInDetokenizeRequestValidations() { Validations.validateDetokenizeRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.InvalidDataTokens.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -70,7 +70,7 @@ public void testEmptyTokensInDetokenizeRequestValidations() { Validations.validateDetokenizeRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyDataTokens.getMessage(), Constants.SDK_PREFIX), e.getMessage() @@ -89,7 +89,7 @@ public void testEmptyTokenInTokensInDetokenizeRequestValidations() { Validations.validateDetokenizeRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( Utils.parameterizedString(ErrorMessage.EmptyTokenInDataTokens.getMessage(), Constants.SDK_PREFIX), e.getMessage() diff --git a/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java index 1f4360b2..850553f4 100644 --- a/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java @@ -76,7 +76,7 @@ public void testNoColumnValuesInTokenizeRequestValidations() { Validations.validateTokenizeRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.ColumnValuesKeyErrorTokenize.getMessage(), e.getMessage()); } } @@ -88,7 +88,7 @@ public void testEmptyColumnValuesInTokenizeRequestValidations() { Validations.validateTokenizeRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyColumnValues.getMessage(), e.getMessage()); } } @@ -102,7 +102,7 @@ public void testEmptyColumnValueInColumnValuesInTokenizeRequestValidations() { Validations.validateTokenizeRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyValueInColumnValues.getMessage(), e.getMessage()); } } @@ -116,7 +116,7 @@ public void testEmptyColumnGroupInColumnValuesInTokenizeRequestValidations() { Validations.validateTokenizeRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { - Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getCode()); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals(ErrorMessage.EmptyColumnGroupInColumnValue.getMessage(), e.getMessage()); } } From 9ec99b4b7b235f0cea6438e42598b4b7eb976eee Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 19 Nov 2024 18:38:53 +0530 Subject: [PATCH 050/126] SK-1623 Fix minor issues in Java SDK v2 --- .../java/com/skyflow/ConnectionClient.java | 4 +- src/main/java/com/skyflow/VaultClient.java | 4 +- .../java/com/skyflow/errors/ErrorMessage.java | 191 +++++++++--------- 3 files changed, 99 insertions(+), 100 deletions(-) diff --git a/src/main/java/com/skyflow/ConnectionClient.java b/src/main/java/com/skyflow/ConnectionClient.java index 40fd741a..72a70fef 100644 --- a/src/main/java/com/skyflow/ConnectionClient.java +++ b/src/main/java/com/skyflow/ConnectionClient.java @@ -24,7 +24,6 @@ protected ConnectionClient(ConnectionConfig connectionConfig, Credentials creden super(); this.connectionConfig = connectionConfig; this.commonCredentials = credentials; - prioritiseCredentials(); } protected ConnectionConfig getConnectionConfig() { @@ -41,11 +40,12 @@ protected void updateConnectionConfig(ConnectionConfig connectionConfig) { } protected void setBearerToken() throws SkyflowException { + prioritiseCredentials(); Validations.validateCredentials(this.finalCredentials); if (this.finalCredentials.getApiKey() != null) { setApiKey(); return; - } else if (token == null || Token.isExpired(token)) { + } else if (Token.isExpired(token)) { LogUtil.printInfoLog(InfoLogs.BEARER_TOKEN_EXPIRED.getLog()); token = Utils.generateBearerToken(this.finalCredentials); } else { diff --git a/src/main/java/com/skyflow/VaultClient.java b/src/main/java/com/skyflow/VaultClient.java index b1acbdad..55a16024 100644 --- a/src/main/java/com/skyflow/VaultClient.java +++ b/src/main/java/com/skyflow/VaultClient.java @@ -48,7 +48,6 @@ protected VaultClient(VaultConfig vaultConfig, Credentials credentials) { this.tokensApi = new TokensApi(this.apiClient); this.queryApi = new QueryApi(this.apiClient); updateVaultURL(); - prioritiseCredentials(); } protected RecordsApi getRecordsApi() { @@ -168,11 +167,12 @@ protected V1TokenizePayload getTokenizePayload(TokenizeRequest request) { } protected void setBearerToken() throws SkyflowException { + prioritiseCredentials(); Validations.validateCredentials(this.finalCredentials); if (this.finalCredentials.getApiKey() != null) { setApiKey(); return; - } else if (token == null || Token.isExpired(token)) { + } else if (Token.isExpired(token)) { LogUtil.printInfoLog(InfoLogs.BEARER_TOKEN_EXPIRED.getLog()); token = Utils.generateBearerToken(this.finalCredentials); } else { diff --git a/src/main/java/com/skyflow/errors/ErrorMessage.java b/src/main/java/com/skyflow/errors/ErrorMessage.java index f44427fb..c7ac207a 100644 --- a/src/main/java/com/skyflow/errors/ErrorMessage.java +++ b/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -1,132 +1,131 @@ package com.skyflow.errors; import com.skyflow.utils.Constants; -import com.skyflow.utils.Utils; public enum ErrorMessage { // client initialization - VaultIdAlreadyInConfigList("%s1 Validation error. VaultId is present in an existing config. Specify a new vaultId in config."), - VaultIdNotInConfigList("%s1 Validation error. VaultId is missing from the config. Specify the vaultIds from configs."), - ConnectionIdAlreadyInConfigList("%s1 Validation error. ConnectionId is present in an existing config. Specify a connectionId in config."), - ConnectionIdNotInConfigList("%s1 Validation error. ConnectionId is missing from the config. Specify the connectionIds from configs."), - EmptyCredentials("%s1 Validation error. Invalid credentials. Specify a valid credentials."), + VaultIdAlreadyInConfigList("%s0 Validation error. VaultId is present in an existing config. Specify a new vaultId in config."), + VaultIdNotInConfigList("%s0 Validation error. VaultId is missing from the config. Specify the vaultIds from configs."), + ConnectionIdAlreadyInConfigList("%s0 Validation error. ConnectionId is present in an existing config. Specify a connectionId in config."), + ConnectionIdNotInConfigList("%s0 Validation error. ConnectionId is missing from the config. Specify the connectionIds from configs."), + EmptyCredentials("%s0 Validation error. Invalid credentials. Specify a valid credentials."), // vault config - InvalidVaultId("%s1 Initialization failed. Invalid vault ID. Specify a valid vault ID."), - EmptyVaultId("%s1 Initialization failed. Invalid vault ID. Vault ID must not be empty."), - InvalidClusterId("%s1 Initialization failed. Invalid cluster ID. Specify cluster ID."), - EmptyClusterId("%s1 Initialization failed. Invalid cluster ID. Specify a valid cluster ID."), + InvalidVaultId("%s0 Initialization failed. Invalid vault ID. Specify a valid vault ID."), + EmptyVaultId("%s0 Initialization failed. Invalid vault ID. Vault ID must not be empty."), + InvalidClusterId("%s0 Initialization failed. Invalid cluster ID. Specify cluster ID."), + EmptyClusterId("%s0 Initialization failed. Invalid cluster ID. Specify a valid cluster ID."), // connection config - InvalidConnectionId("%s1 Initialization failed. Invalid connection ID. Specify a valid connection ID."), - EmptyConnectionId("%s1 Initialization failed. Invalid connection ID. Connection ID must not be empty."), - InvalidConnectionUrl("%s1 Initialization failed. Invalid connection URL. Specify a valid connection URL."), - EmptyConnectionUrl("%s1 Initialization failed. Invalid connection URL. Connection URL must not be empty."), - InvalidConnectionUrlFormat("%s1 Initialization failed. Connection URL is not a valid URL. Specify a valid connection URL."), + InvalidConnectionId("%s0 Initialization failed. Invalid connection ID. Specify a valid connection ID."), + EmptyConnectionId("%s0 Initialization failed. Invalid connection ID. Connection ID must not be empty."), + InvalidConnectionUrl("%s0 Initialization failed. Invalid connection URL. Specify a valid connection URL."), + EmptyConnectionUrl("%s0 Initialization failed. Invalid connection URL. Connection URL must not be empty."), + InvalidConnectionUrlFormat("%s0 Initialization failed. Connection URL is not a valid URL. Specify a valid connection URL."), // credentials - MultipleTokenGenerationMeansPassed("%s1 Initialization failed. Invalid credentials. Specify only one from 'path', 'credentialsString', 'token' or 'apiKey'."), - NoTokenGenerationMeansPassed("%s1 Initialization failed. Invalid credentials. Specify any one from 'path', 'credentialsString', 'token' or 'apiKey'."), - EmptyCredentialFilePath("%s1 Initialization failed. Invalid credentials. Credentials file path must not be empty."), - EmptyCredentialsString("%s1 Initialization failed. Invalid credentials. Credentials string must not be empty."), - EmptyToken("%s1 Initialization failed. Invalid credentials. Token mut not be empty."), - EmptyApikey("%s1 Initialization failed. Invalid credentials. Api key must not be empty."), - InvalidApikey("%s1 Initialization failed. Invalid credentials. Specify valid api key."), - EmptyRoles("%s1 Initialization failed. Invalid roles. Specify at least one role."), - EmptyRoleInRoles("%s1 Initialization failed. Invalid role. Specify a valid role."), - EmptyContext("%s1 Initialization failed. Invalid context. Specify a valid context."), + MultipleTokenGenerationMeansPassed("%s0 Initialization failed. Invalid credentials. Specify only one from 'path', 'credentialsString', 'token' or 'apiKey'."), + NoTokenGenerationMeansPassed("%s0 Initialization failed. Invalid credentials. Specify any one from 'path', 'credentialsString', 'token' or 'apiKey'."), + EmptyCredentialFilePath("%s0 Initialization failed. Invalid credentials. Credentials file path must not be empty."), + EmptyCredentialsString("%s0 Initialization failed. Invalid credentials. Credentials string must not be empty."), + EmptyToken("%s0 Initialization failed. Invalid credentials. Token mut not be empty."), + EmptyApikey("%s0 Initialization failed. Invalid credentials. Api key must not be empty."), + InvalidApikey("%s0 Initialization failed. Invalid credentials. Specify valid api key."), + EmptyRoles("%s0 Initialization failed. Invalid roles. Specify at least one role."), + EmptyRoleInRoles("%s0 Initialization failed. Invalid role. Specify a valid role."), + EmptyContext("%s0 Initialization failed. Invalid context. Specify a valid context."), // bearer token generation - FileNotFound("%s1 Initialization failed. Credential file not found at %s2. Verify the file path."), - FileInvalidJson("%s1 Initialization failed. File at %s2 is not in valid JSON format. Verify the file contents."), - CredentialsStringInvalidJson("%s1 Initialization failed. Credentials string is not in valid JSON format. Verify the credentials string contents."), - InvalidCredentials("%s1 Initialization failed. Invalid credentials provided. Specify valid credentials."), - MissingPrivateKey("%s1 Initialization failed. Unable to read private key in credentials. Verify your private key."), - MissingClientId("%s1 Initialization failed. Unable to read client ID in credentials. Verify your client ID."), - MissingKeyId("%s1 Initialization failed. Unable to read key ID in credentials. Verify your key ID."), - MissingTokenUri("%s1 Initialization failed. Unable to read token URI in credentials. Verify your token URI."), - InvalidTokenUri("%s1 Initialization failed. Token URI in not a valid URL in credentials. Verify your token URI."), - JwtInvalidFormat("%s1 Initialization failed. Invalid private key format. Verify your credentials."), - InvalidAlgorithm("%s1 Initialization failed. Invalid algorithm to parse private key. Specify valid algorithm."), - InvalidKeySpec("%s1 Initialization failed. Unable to parse RSA private key. Verify your credentials."), - JwtDecodeError("%s1 Validation error. Invalid access token. Verify your credentials."), - MissingAccessToken("%s1 Validation error. Access token not present in the response from bearer token generation. Verify your credentials."), - MissingTokenType("%s1 Validation error. Token type not present in the response from bearer token generation. Verify your credentials."), + FileNotFound("%s0 Initialization failed. Credential file not found at %s1. Verify the file path."), + FileInvalidJson("%s0 Initialization failed. File at %s1 is not in valid JSON format. Verify the file contents."), + CredentialsStringInvalidJson("%s0 Initialization failed. Credentials string is not in valid JSON format. Verify the credentials string contents."), + InvalidCredentials("%s0 Initialization failed. Invalid credentials provided. Specify valid credentials."), + MissingPrivateKey("%s0 Initialization failed. Unable to read private key in credentials. Verify your private key."), + MissingClientId("%s0 Initialization failed. Unable to read client ID in credentials. Verify your client ID."), + MissingKeyId("%s0 Initialization failed. Unable to read key ID in credentials. Verify your key ID."), + MissingTokenUri("%s0 Initialization failed. Unable to read token URI in credentials. Verify your token URI."), + InvalidTokenUri("%s0 Initialization failed. Token URI in not a valid URL in credentials. Verify your token URI."), + JwtInvalidFormat("%s0 Initialization failed. Invalid private key format. Verify your credentials."), + InvalidAlgorithm("%s0 Initialization failed. Invalid algorithm to parse private key. Specify valid algorithm."), + InvalidKeySpec("%s0 Initialization failed. Unable to parse RSA private key. Verify your credentials."), + JwtDecodeError("%s0 Validation error. Invalid access token. Verify your credentials."), + MissingAccessToken("%s0 Validation error. Access token not present in the response from bearer token generation. Verify your credentials."), + MissingTokenType("%s0 Validation error. Token type not present in the response from bearer token generation. Verify your credentials."), // insert - TableKeyError("%s1 Validation error. 'table' key is missing from the payload. Specify a 'table' key."), - EmptyTable("%s1 Validation error. 'table' can't be empty. Specify a table."), - ValuesKeyError("%s1 Validation error. 'values' key is missing from the payload. Specify a 'values' key."), - EmptyValues("%s1 Validation error. 'values' can't be empty. Specify values."), - EmptyKeyInValues("%s1 Validation error. Invalid key in values. Specify a valid key."), - EmptyValueInValues("%s1 Validation error. Invalid value in values. Specify a valid value."), - TokensKeyError("%s1 Validation error. 'tokens' key is missing from the payload. Specify a 'tokens' key."), - EmptyTokens("%s1 Validation error. The 'tokens' field is empty. Specify tokens for one or more fields."), - EmptyKeyInTokens("%s1 Validation error. Invalid key tokens. Specify a valid key."), - EmptyValueInTokens("%s1 Validation error. Invalid value in tokens. Specify a valid value."), - EmptyUpsert("%s1 Validation error. 'upsert' key can't be empty. Specify an upsert column."), - HomogenousNotSupportedWithUpsert("%s1 Validation error. 'homogenous' is not supported with 'upsert'. Specify either 'homogenous' or 'upsert'."), - TokensPassedForByotDisable("%s1 Validation error. 'tokenStrict' wasn't specified. Set 'tokenStrict' to 'ENABLE' to insert tokens."), - NoTokensWithByot("%s1 Validation error. Tokens weren't specified for records while 'tokenStrict' was %s2. Specify tokens."), - MismatchOfFieldsAndTokens("%s1 Validation error. 'fields' and 'tokens' have different columns names. Verify that 'fields' and 'tokens' columns match."), - InsufficientTokensPassedForByotEnableStrict("%s1 Validation error. 'tokenStrict' is set to 'ENABLE_STRICT', but some fields are missing tokens. Specify tokens for all fields."), - BatchInsertPartialSuccess("%s1 Insert operation completed with partial success."), - BatchInsertFailure("%s1 Insert operation failed."), + TableKeyError("%s0 Validation error. 'table' key is missing from the payload. Specify a 'table' key."), + EmptyTable("%s0 Validation error. 'table' can't be empty. Specify a table."), + ValuesKeyError("%s0 Validation error. 'values' key is missing from the payload. Specify a 'values' key."), + EmptyValues("%s0 Validation error. 'values' can't be empty. Specify values."), + EmptyKeyInValues("%s0 Validation error. Invalid key in values. Specify a valid key."), + EmptyValueInValues("%s0 Validation error. Invalid value in values. Specify a valid value."), + TokensKeyError("%s0 Validation error. 'tokens' key is missing from the payload. Specify a 'tokens' key."), + EmptyTokens("%s0 Validation error. The 'tokens' field is empty. Specify tokens for one or more fields."), + EmptyKeyInTokens("%s0 Validation error. Invalid key tokens. Specify a valid key."), + EmptyValueInTokens("%s0 Validation error. Invalid value in tokens. Specify a valid value."), + EmptyUpsert("%s0 Validation error. 'upsert' key can't be empty. Specify an upsert column."), + HomogenousNotSupportedWithUpsert("%s0 Validation error. 'homogenous' is not supported with 'upsert'. Specify either 'homogenous' or 'upsert'."), + TokensPassedForByotDisable("%s0 Validation error. 'tokenStrict' wasn't specified. Set 'tokenStrict' to 'ENABLE' to insert tokens."), + NoTokensWithByot("%s0 Validation error. Tokens weren't specified for records while 'tokenStrict' was %s1. Specify tokens."), + MismatchOfFieldsAndTokens("%s0 Validation error. 'fields' and 'tokens' have different columns names. Verify that 'fields' and 'tokens' columns match."), + InsufficientTokensPassedForByotEnableStrict("%s0 Validation error. 'tokenStrict' is set to 'ENABLE_STRICT', but some fields are missing tokens. Specify tokens for all fields."), + BatchInsertPartialSuccess("%s0 Insert operation completed with partial success."), + BatchInsertFailure("%s0 Insert operation failed."), // detokenize - InvalidDataTokens("%s1 Validation error. Invalid data tokens. Specify valid data tokens."), - EmptyDataTokens("%s1 Validation error. Invalid data tokens. Specify at least one data token."), - EmptyTokenInDataTokens("%s1 Validation error. Invalid data tokens. Specify a valid data token."), + InvalidDataTokens("%s0 Validation error. Invalid data tokens. Specify valid data tokens."), + EmptyDataTokens("%s0 Validation error. Invalid data tokens. Specify at least one data token."), + EmptyTokenInDataTokens("%s0 Validation error. Invalid data tokens. Specify a valid data token."), // get interface - IdsKeyError("%s1 Validation error. 'ids' key is missing from the payload. Specify an 'ids' key."), - EmptyIds("%s1 Validation error. 'ids' can't be empty. Specify at least one id."), - EmptyIdInIds("%s1 Validation error. Invalid id in 'ids'. Specify a valid id."), - EmptyFields("%s1 Validation error. Fields are empty in get payload. Specify at least one field."), - EmptyFieldInFields("%s1 Validation error. Invalid field in 'fields'. Specify a valid field."), - RedactionKeyError("%s1 Validation error. 'redaction' key is missing from the payload. Specify a 'redaction' key."), - RedactionWithTokensNotSupported("%s1 Validation error. 'redaction' can't be used when 'returnTokens' is specified. Remove 'redaction' from payload if 'returnTokens' is specified."), - TokensGetColumnNotSupported("%s1 Validation error. Column name and/or column values can't be used when 'returnTokens' is specified. Remove unique column values or 'returnTokens' from the payload."), - EmptyOffset("%s1 Validation error. 'offset' can't be empty. Specify an offset."), - EmptyLimit("%s1 Validation error. 'limit' can't be empty. Specify a limit."), - UniqueColumnOrIdsKeyError("%s1 Validation error. 'ids' or 'columnName' key is missing from the payload. Specify the ids or unique 'columnName' in payload."), - BothIdsAndColumnDetailsSpecified("%s1 Validation error. Both Skyflow IDs and column details can't be specified. Either specify Skyflow IDs or unique column details."), - ColumnNameKeyError("%s1 Validation error. 'columnName' isn't specified whereas 'columnValues' are specified. Either add 'columnName' or remove 'columnValues'."), - EmptyColumnName("%s1 Validation error. 'columnName' can't be empty. Specify a column name."), - ColumnValuesKeyErrorGet("%s1 Validation error. 'columnValues' aren't specified whereas 'columnName' is specified. Either add 'columnValues' or remove 'columnName'."), - EmptyColumnValues("%s1 Validation error. 'columnValues' can't be empty. Specify at least one column value"), - EmptyValueInColumnValues("%s1 Validation error. Invalid value in column values. Specify a valid column value."), - - TokenKeyError("%s1 Validation error. 'token' key is missing from the payload. Specify a 'token' key."), - PartialSuccess("%s1 Validation error. Check 'SkyflowError.data' for details."), + IdsKeyError("%s0 Validation error. 'ids' key is missing from the payload. Specify an 'ids' key."), + EmptyIds("%s0 Validation error. 'ids' can't be empty. Specify at least one id."), + EmptyIdInIds("%s0 Validation error. Invalid id in 'ids'. Specify a valid id."), + EmptyFields("%s0 Validation error. Fields are empty in get payload. Specify at least one field."), + EmptyFieldInFields("%s0 Validation error. Invalid field in 'fields'. Specify a valid field."), + RedactionKeyError("%s0 Validation error. 'redaction' key is missing from the payload. Specify a 'redaction' key."), + RedactionWithTokensNotSupported("%s0 Validation error. 'redaction' can't be used when 'returnTokens' is specified. Remove 'redaction' from payload if 'returnTokens' is specified."), + TokensGetColumnNotSupported("%s0 Validation error. Column name and/or column values can't be used when 'returnTokens' is specified. Remove unique column values or 'returnTokens' from the payload."), + EmptyOffset("%s0 Validation error. 'offset' can't be empty. Specify an offset."), + EmptyLimit("%s0 Validation error. 'limit' can't be empty. Specify a limit."), + UniqueColumnOrIdsKeyError("%s0 Validation error. 'ids' or 'columnName' key is missing from the payload. Specify the ids or unique 'columnName' in payload."), + BothIdsAndColumnDetailsSpecified("%s0 Validation error. Both Skyflow IDs and column details can't be specified. Either specify Skyflow IDs or unique column details."), + ColumnNameKeyError("%s0 Validation error. 'columnName' isn't specified whereas 'columnValues' are specified. Either add 'columnName' or remove 'columnValues'."), + EmptyColumnName("%s0 Validation error. 'columnName' can't be empty. Specify a column name."), + ColumnValuesKeyErrorGet("%s0 Validation error. 'columnValues' aren't specified whereas 'columnName' is specified. Either add 'columnValues' or remove 'columnName'."), + EmptyColumnValues("%s0 Validation error. 'columnValues' can't be empty. Specify at least one column value"), + EmptyValueInColumnValues("%s0 Validation error. Invalid value in column values. Specify a valid column value."), + + TokenKeyError("%s0 Validation error. 'token' key is missing from the payload. Specify a 'token' key."), + PartialSuccess("%s0 Validation error. Check 'SkyflowError.data' for details."), // update - SkyflowIdKeyError("%s1 Validation error. 'id' key is missing from the payload. Specify an 'id' key."), - EmptySkyflowId("%s1 Validation error. 'id' can't be empty. Specify an id."), + SkyflowIdKeyError("%s0 Validation error. 'id' key is missing from the payload. Specify an 'id' key."), + EmptySkyflowId("%s0 Validation error. 'id' can't be empty. Specify an id."), // query - QueryKeyError("%s1 Validation error. 'query' key is missing from the payload. Specify a 'query' key."), - EmptyQuery("%s1 Validation error. 'query' can't be empty. Specify a query"), + QueryKeyError("%s0 Validation error. 'query' key is missing from the payload. Specify a 'query' key."), + EmptyQuery("%s0 Validation error. 'query' can't be empty. Specify a query"), // tokenize - ColumnValuesKeyErrorTokenize("%s1 Validation error. 'columnValues' key is missing from the payload. Specify a 'columnValues' key."), - EmptyColumnGroupInColumnValue("%s1 Validation error. Invalid column group in column value. Specify a valid column group."), + ColumnValuesKeyErrorTokenize("%s0 Validation error. 'columnValues' key is missing from the payload. Specify a 'columnValues' key."), + EmptyColumnGroupInColumnValue("%s0 Validation error. Invalid column group in column value. Specify a valid column group."), // connection - InvalidRequestHeaders("%s1 Validation error. Request headers aren't valid. Specify valid request headers."), - EmptyRequestHeaders("%s1 Validation error. Request headers are empty. Specify valid ."), - InvalidPathParams("%s1 Validation error. Path parameters aren't valid. Specify valid path parameters."), - EmptyPathParams("%s1 Validation error. Path parameters are empty. Specify valid path parameters."), - InvalidQueryParams("%s1 Validation error. Query parameters aren't valid. Specify valid query parameters."), - EmptyQueryParams("%s1 Validation error. Query parameters are empty. Specify valid query parameters."), - InvalidRequestBody("%s1 Validation error. Invalid request body. Specify the request body as an object."), - EmptyRequestBody("%s1 Validation error. Request body can't be empty. Specify a valid request body."), + InvalidRequestHeaders("%s0 Validation error. Request headers aren't valid. Specify valid request headers."), + EmptyRequestHeaders("%s0 Validation error. Request headers are empty. Specify valid ."), + InvalidPathParams("%s0 Validation error. Path parameters aren't valid. Specify valid path parameters."), + EmptyPathParams("%s0 Validation error. Path parameters are empty. Specify valid path parameters."), + InvalidQueryParams("%s0 Validation error. Query parameters aren't valid. Specify valid query parameters."), + EmptyQueryParams("%s0 Validation error. Query parameters are empty. Specify valid query parameters."), + InvalidRequestBody("%s0 Validation error. Invalid request body. Specify the request body as an object."), + EmptyRequestBody("%s0 Validation error. Request body can't be empty. Specify a valid request body."), ; private final String message; ErrorMessage(String message) { - this.message = Utils.parameterizedString(message, Constants.SDK_PREFIX); + this.message = message.replace("%s0", Constants.SDK_PREFIX); } public String getMessage() { From b2b06c1936b78acffc0e5607a3297948eb7a0acb Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 19 Nov 2024 19:15:29 +0530 Subject: [PATCH 051/126] SK-1685 Add samples for Java SDK v2 - Added samples for vault API interfaces - Added sample for invoke connection interface --- ...rerTokenGenerationUsingThreadsExample.java | 48 ----------- ...arerTokenWithContextGenerationExample.java | 46 ----------- .../main/java/com/example/DeleteExample.java | 72 ----------------- .../java/com/example/DetokenizeExample.java | 71 ---------------- .../main/java/com/example/GetByIdExample.java | 66 --------------- .../src/main/java/com/example/GetExample.java | 74 ----------------- .../java/com/example/InsertBulkExample.java | 58 ------------- .../example/InsertBulkWithUpsertExample.java | 69 ---------------- .../main/java/com/example/InsertExample.java | 66 --------------- .../InsertWithContinueOnErrorExample.java | 69 ---------------- .../com/example/InsertWithUpsertExample.java | 71 ---------------- .../com/example/InvokeConnectionExample.java | 65 --------------- .../main/java/com/example/QueryExample.java | 57 ------------- .../example/ScopedTokenGenerationExample.java | 28 ------- .../example/SignedTokenGenerationExample.java | 53 ------------ .../com/example/TokenGenerationExample.java | 40 --------- .../main/java/com/example/UpdateExample.java | 59 -------------- .../connection/InvokeConnectionExample.java | 68 ++++++++++++++++ .../java/com/example/vault/DeleteExample.java | 52 ++++++++++++ .../com/example/vault/DetokenizeExample.java | 59 ++++++++++++++ .../java/com/example/vault/GetExample.java | 58 +++++++++++++ .../java/com/example/vault/InsertExample.java | 81 +++++++++++++++++++ .../java/com/example/vault/QueryExample.java | 49 +++++++++++ .../com/example/vault/TokenizeExample.java | 60 ++++++++++++++ .../java/com/example/vault/UpdateExample.java | 73 +++++++++++++++++ 25 files changed, 500 insertions(+), 1012 deletions(-) delete mode 100644 samples/src/main/java/com/example/BearerTokenGenerationUsingThreadsExample.java delete mode 100644 samples/src/main/java/com/example/BearerTokenWithContextGenerationExample.java delete mode 100644 samples/src/main/java/com/example/DeleteExample.java delete mode 100644 samples/src/main/java/com/example/DetokenizeExample.java delete mode 100644 samples/src/main/java/com/example/GetByIdExample.java delete mode 100644 samples/src/main/java/com/example/GetExample.java delete mode 100644 samples/src/main/java/com/example/InsertBulkExample.java delete mode 100644 samples/src/main/java/com/example/InsertBulkWithUpsertExample.java delete mode 100644 samples/src/main/java/com/example/InsertExample.java delete mode 100644 samples/src/main/java/com/example/InsertWithContinueOnErrorExample.java delete mode 100644 samples/src/main/java/com/example/InsertWithUpsertExample.java delete mode 100644 samples/src/main/java/com/example/InvokeConnectionExample.java delete mode 100644 samples/src/main/java/com/example/QueryExample.java delete mode 100644 samples/src/main/java/com/example/ScopedTokenGenerationExample.java delete mode 100644 samples/src/main/java/com/example/SignedTokenGenerationExample.java delete mode 100644 samples/src/main/java/com/example/TokenGenerationExample.java delete mode 100644 samples/src/main/java/com/example/UpdateExample.java create mode 100644 samples/src/main/java/com/example/connection/InvokeConnectionExample.java create mode 100644 samples/src/main/java/com/example/vault/DeleteExample.java create mode 100644 samples/src/main/java/com/example/vault/DetokenizeExample.java create mode 100644 samples/src/main/java/com/example/vault/GetExample.java create mode 100644 samples/src/main/java/com/example/vault/InsertExample.java create mode 100644 samples/src/main/java/com/example/vault/QueryExample.java create mode 100644 samples/src/main/java/com/example/vault/TokenizeExample.java create mode 100644 samples/src/main/java/com/example/vault/UpdateExample.java diff --git a/samples/src/main/java/com/example/BearerTokenGenerationUsingThreadsExample.java b/samples/src/main/java/com/example/BearerTokenGenerationUsingThreadsExample.java deleted file mode 100644 index 718aa21e..00000000 --- a/samples/src/main/java/com/example/BearerTokenGenerationUsingThreadsExample.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.BearerToken; - -import java.io.File; - -public class BearerTokenGenerationUsingThreadsExample { - public static void main(String args[]) { - - String bearerToken = null; - - // Generate BearerToken with context by specifying credentials.json file path - try { - String filePath = ""; - final BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(filePath)) - .setCtx("abc") - .build(); - - Thread t = new Thread(new Runnable() { - @Override - public void run() { - - for (int i = 0; i < 5; i++) { - try { - System.out.println(token.getBearerToken()); - } catch (SkyflowException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException(e); - - } - - } - } - }); - - t.start(); - - } catch (Exception e) { - e.printStackTrace(); - } - - } -} diff --git a/samples/src/main/java/com/example/BearerTokenWithContextGenerationExample.java b/samples/src/main/java/com/example/BearerTokenWithContextGenerationExample.java deleted file mode 100644 index 668b7c81..00000000 --- a/samples/src/main/java/com/example/BearerTokenWithContextGenerationExample.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.BearerToken; - -import java.io.File; - -public class BearerTokenWithContextGenerationExample { - public static void main(String args[]) { - - String bearerToken = null; - - // Generate BearerToken with context by specifying credentials.json file path - try { - String filePath = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(filePath)) - .setCtx("abc") - .build(); - - bearerToken = token.getBearerToken(); - System.out.println(bearerToken); - } catch (Exception e) { - e.printStackTrace(); - } - - // Generate BearerToken with context by specifying credentials.json as string - try { - String fileContents = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(fileContents) - .setCtx("abc") - .build(); - - bearerToken = token.getBearerToken(); - System.out.println(bearerToken); - - } catch (SkyflowException e) { - e.printStackTrace(); - } - - } -} diff --git a/samples/src/main/java/com/example/DeleteExample.java b/samples/src/main/java/com/example/DeleteExample.java deleted file mode 100644 index 9ee0fc28..00000000 --- a/samples/src/main/java/com/example/DeleteExample.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - Copyright (c) 2023 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.ResponseToken; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - - -public class DeleteExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration( - "", - "", - new DemoTokenProvider() - ); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - - record.put("id", ""); - record.put("table", ""); - recordsArray.add(record); - JSONObject record2 = new JSONObject(); - - record2.put("id", ""); - record2.put("table", ""); - recordsArray.add(record2); - - records.put("records", recordsArray); - - JSONObject response = skyflowClient.delete(records); - System.out.println(response); - } catch (SkyflowException e) { - e.printStackTrace(); - System.out.println("error" + e.getData()); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if (Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/DetokenizeExample.java b/samples/src/main/java/com/example/DetokenizeExample.java deleted file mode 100644 index acc29287..00000000 --- a/samples/src/main/java/com/example/DetokenizeExample.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.RedactionType; -import com.skyflow.entities.ResponseToken; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - - -public class DetokenizeExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration( - "", - "", - new DemoTokenProvider() - ); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record1 = new JSONObject(); - record1.put("token", ""); - record1.put("redaction", RedactionType.MASKED.toString()); - - JSONObject record2 = new JSONObject(); - record2.put("token", ""); // default Redaction "PLAIN_TEXT" will be applied for record2 - - recordsArray.add(record1); - recordsArray.add(record2); - records.put("records", recordsArray); - - JSONObject response = skyflowClient.detokenize(records); - System.out.println(response); - } catch (SkyflowException e) { - e.printStackTrace(); - System.out.println(e.getData()); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/GetByIdExample.java b/samples/src/main/java/com/example/GetByIdExample.java deleted file mode 100644 index b3576fb3..00000000 --- a/samples/src/main/java/com/example/GetByIdExample.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.RedactionType; -import com.skyflow.entities.ResponseToken; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - - -public class GetByIdExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - JSONArray ids = new JSONArray(); - ids.add(""); - - record.put("ids", ids); - record.put("table", ""); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - recordsArray.add(record); - records.put("records", recordsArray); - - JSONObject response = skyflowClient.getById(records); - } catch (SkyflowException e) { - e.printStackTrace(); - System.out.println(e.getData()); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/GetExample.java b/samples/src/main/java/com/example/GetExample.java deleted file mode 100644 index 76cf826a..00000000 --- a/samples/src/main/java/com/example/GetExample.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.example; - -import com.skyflow.entities.RedactionType; -import com.skyflow.entities.ResponseToken; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -public class GetExample { - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject firstRecord = new JSONObject(); - - JSONArray ids = new JSONArray(); - ids.add(""); - - firstRecord.put("ids", ids); - firstRecord.put("table", ""); - firstRecord.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - JSONObject secondRecord = new JSONObject(); - - JSONArray valuesArray = new JSONArray(); - valuesArray.add(""); - - secondRecord.put("table", ""); - secondRecord.put("columnName", ""); - secondRecord.put("columnValues", valuesArray); - secondRecord.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - recordsArray.add(firstRecord); - recordsArray.add(secondRecord); - records.put("records", recordsArray); - - JSONObject response = skyflowClient.get(records); - } catch (SkyflowException e) { - e.printStackTrace(); - System.out.println(e.getData()); - } - - } - - static class DemoTokenProvider implements TokenProvider { - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if (Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} \ No newline at end of file diff --git a/samples/src/main/java/com/example/InsertBulkExample.java b/samples/src/main/java/com/example/InsertBulkExample.java deleted file mode 100644 index bb191c7c..00000000 --- a/samples/src/main/java/com/example/InsertBulkExample.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.example; - -import com.skyflow.entities.*; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -public class InsertBulkExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", ""); - - JSONObject fields = new JSONObject(); - fields.put("", ""); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - JSONObject res = skyflowClient.insertBulk(records); - - System.out.println(res); - } catch (SkyflowException e) { - e.printStackTrace(); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} \ No newline at end of file diff --git a/samples/src/main/java/com/example/InsertBulkWithUpsertExample.java b/samples/src/main/java/com/example/InsertBulkWithUpsertExample.java deleted file mode 100644 index 57272e15..00000000 --- a/samples/src/main/java/com/example/InsertBulkWithUpsertExample.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.example; - -import com.skyflow.entities.*; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - - -public class InsertBulkWithUpsertExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", ""); - - JSONObject fields = new JSONObject(); - fields.put(""); - - record.put("fields", fields); - recordsArray.add(record); - - records.put("records", recordsArray); - - // create an upsert option and insert in UpsertOptions array. - UpsertOption[] upsertOptions = new UpsertOption[1]; - upsertOptions[0] = new UpsertOption("", ""); - - // pass upsert options in insert method options. - InsertBulkOptions insertOptions = new InsertBulkOptions(true, upsertOptions); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - - System.out.println(res); - } catch (SkyflowException e) { - e.printStackTrace(); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if (Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/InsertExample.java b/samples/src/main/java/com/example/InsertExample.java deleted file mode 100644 index faada157..00000000 --- a/samples/src/main/java/com/example/InsertExample.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.InsertOptions; -import com.skyflow.entities.ResponseToken; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -public class InsertExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", ""); - - JSONObject fields = new JSONObject(); - fields.put("", ""); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(); - JSONObject res = skyflowClient.insert(records, insertOptions); - - System.out.println(res); - } catch (SkyflowException e) { - e.printStackTrace(); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/InsertWithContinueOnErrorExample.java b/samples/src/main/java/com/example/InsertWithContinueOnErrorExample.java deleted file mode 100644 index 21e7df2f..00000000 --- a/samples/src/main/java/com/example/InsertWithContinueOnErrorExample.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - Copyright (c) 2024 Skyflow, Inc. -*/ -import com.skyflow.entities.*; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -public class InsertWithContinueOnErrorExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration( - "", - "", - new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record1 = new JSONObject(); - record1.put("table", ""); - JSONObject fields = new JSONObject(); - fields.put("", ""); - record1.put("fields", fields); - - JSONObject record2 = new JSONObject(); - record2.put("table", ""); - JSONObject fields2 = new JSONObject(); - fields2.put("", ""); - record2.put("fields", fields2); - - recordsArray.add(record1); - recordsArray.add(record2); - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(true,true); - JSONObject insertResponse = skyflowClient.insert(records, insertOptions); - System.out.println(insertResponse); - } catch (SkyflowException e) { - System.out.println(e); - e.printStackTrace(); - } - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if (Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/InsertWithUpsertExample.java b/samples/src/main/java/com/example/InsertWithUpsertExample.java deleted file mode 100644 index 3ae13357..00000000 --- a/samples/src/main/java/com/example/InsertWithUpsertExample.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.*; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -public class InsertWithUpsertExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", ""); - - JSONObject fields = new JSONObject(); - fields.put(""); - - record.put("fields", fields); - recordsArray.add(record); - - records.put("records", recordsArray); - - // create an upsert option and insert in UpsertOptions array. - UpsertOption[] upsertOptions = new UpsertOption[1]; - upsertOptions[0] = new UpsertOption("", ""); - - // pass upsert options in insert method options. - InsertOptions insertOptions = new InsertOptions(true, upsertOptions); - JSONObject res = skyflowClient.insert(records, insertOptions); - - System.out.println(res); - } catch (SkyflowException e) { - e.printStackTrace(); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if (Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/InvokeConnectionExample.java b/samples/src/main/java/com/example/InvokeConnectionExample.java deleted file mode 100644 index 8f5eac28..00000000 --- a/samples/src/main/java/com/example/InvokeConnectionExample.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -import com.skyflow.entities.*; -import com.skyflow.vault.Skyflow; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -public class InvokeConnectionExample { - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } - - public static void main(String[] args) { - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject testConfig = new JSONObject(); - testConfig.put("connectionURL", ""); - testConfig.put("methodName", RequestMethod.POST); - - JSONObject pathParamsJson = new JSONObject(); - pathParamsJson.put("", ""); - testConfig.put("pathParams", pathParamsJson); - - JSONObject queryParamsJson = new JSONObject(); - queryParamsJson.put("", ""); - testConfig.put("queryParams", queryParamsJson); - - JSONObject requestHeadersJson = new JSONObject(); - requestHeadersJson.put("", ""); - testConfig.put("requestHeader", requestHeadersJson); - - JSONObject requestBodyJson = new JSONObject(); - requestBodyJson.put("", ""); - testConfig.put("requestBody", requestBodyJson); - - JSONObject gatewayResponse = skyflowClient.invokeConnection(testConfig); - System.out.println(gatewayResponse); - - } catch (SkyflowException exception) { - exception.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/java/com/example/QueryExample.java b/samples/src/main/java/com/example/QueryExample.java deleted file mode 100644 index 31d577c7..00000000 --- a/samples/src/main/java/com/example/QueryExample.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.ResponseToken; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONObject; - -public class QueryExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject queryInput = new JSONObject(); - - queryInput.put("query", ""); - - JSONObject res = skyflowClient.query(queryInput); - - System.out.println(res); - } catch (SkyflowException e) { - System.out.println(e.getData()); - e.printStackTrace(); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} \ No newline at end of file diff --git a/samples/src/main/java/com/example/ScopedTokenGenerationExample.java b/samples/src/main/java/com/example/ScopedTokenGenerationExample.java deleted file mode 100644 index ed4dda5f..00000000 --- a/samples/src/main/java/com/example/ScopedTokenGenerationExample.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.serviceaccount.util.BearerToken; -import java.io.File; - -public class ScopedTokenGenerationExample { - public static void main(String args[]) { - - String scopedToken = null; - - // Generate Scoped Token by specifying credentials.json file path - try { - String filePath = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(filePath)) - .setRoles(new String[]{"roleID"}) - .build(); - - scopedToken = token.getBearerToken(); - System.out.println(scopedToken); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/samples/src/main/java/com/example/SignedTokenGenerationExample.java b/samples/src/main/java/com/example/SignedTokenGenerationExample.java deleted file mode 100644 index 1fde4236..00000000 --- a/samples/src/main/java/com/example/SignedTokenGenerationExample.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.SignedDataTokenResponse; -import com.skyflow.serviceaccount.util.SignedDataTokens; - -import java.io.File; -import java.util.List; - -public class SignedTokenGenerationExample { - public static void main(String args[]) { - - List signedTokenValue; - - // Generate Signed data token with context by specifying credentials.json file path - try { - String filePath = ""; - String context = "abc"; - SignedDataTokens signedToken = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(new File(filePath)) - .setCtx(context) - .setTimeToLive(30) // in seconds - .setDataTokens(new String[]{"dataToken1"}).build(); - - signedTokenValue = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValue); - } catch (Exception e) { - e.printStackTrace(); - } - - // Generate Signed data token with context by specifying credentials.json as string - try { - String fileContents = ""; - String context = "abc"; - SignedDataTokens signedToken = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(fileContents) - .setCtx(context) - .setTimeToLive(30) // in seconds - .setDataTokens(new String[]{"dataToken1"}).build(); - - signedTokenValue = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValue); - - } catch (SkyflowException e) { - e.printStackTrace(); - } - - - } -} diff --git a/samples/src/main/java/com/example/TokenGenerationExample.java b/samples/src/main/java/com/example/TokenGenerationExample.java deleted file mode 100644 index b4de6b87..00000000 --- a/samples/src/main/java/com/example/TokenGenerationExample.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.ResponseToken; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; - -public class TokenGenerationExample { - public static void main(String args[]) { - - String bearerToken = null; - - // Generate BearerToken by specifying credentials.json file path - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - ResponseToken res = Token.generateBearerToken(filePath); - bearerToken = res.getAccessToken(); - } - System.out.println(bearerToken); - } catch (Exception e) { - e.printStackTrace(); - } - - // Generate BearerToken by specifying credentials.json as string - try { - String fileContents = ""; - if(Token.isExpired(bearerToken)) { - ResponseToken res = Token.generateBearerTokenFromCreds(fileContents); - bearerToken = res.getAccessToken(); - } - System.out.println(bearerToken); - } catch (SkyflowException e) { - e.printStackTrace(); - } - - } -} diff --git a/samples/src/main/java/com/example/UpdateExample.java b/samples/src/main/java/com/example/UpdateExample.java deleted file mode 100644 index 5e67d7ec..00000000 --- a/samples/src/main/java/com/example/UpdateExample.java +++ /dev/null @@ -1,59 +0,0 @@ -import com.skyflow.entities.*; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -public class UpdateExample { - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - record.put("table", ""); - record.put("id", ""); - - JSONObject fields = new JSONObject(); - fields.put("", ""); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - UpdateOptions updateOptions = new UpdateOptions(true); - JSONObject res = skyflowClient.update(records, updateOptions); - - } - catch (SkyflowException e) { - System.out.println(e.getData()); - e.printStackTrace(); - } - } - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} - diff --git a/samples/src/main/java/com/example/connection/InvokeConnectionExample.java b/samples/src/main/java/com/example/connection/InvokeConnectionExample.java new file mode 100644 index 00000000..1c1ee12f --- /dev/null +++ b/samples/src/main/java/com/example/connection/InvokeConnectionExample.java @@ -0,0 +1,68 @@ +package com.example.connection; + +import com.skyflow.Skyflow; +import com.skyflow.config.ConnectionConfig; +import com.skyflow.config.Credentials; +import com.skyflow.enums.LogLevel; +import com.skyflow.enums.RequestMethod; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.connection.InvokeConnectionRequest; +import com.skyflow.vault.connection.InvokeConnectionResponse; + +import java.util.HashMap; +import java.util.Map; + +public class InvokeConnectionExample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); + + ConnectionConfig connectionConfig1 = new ConnectionConfig(); + connectionConfig1.setConnectionId(""); + connectionConfig1.setConnectionUrl(""); + connectionConfig1.setCredentials(credentials); + + ConnectionConfig connectionConfig2 = new ConnectionConfig(); + connectionConfig2.setConnectionId(""); + connectionConfig2.setConnectionUrl(""); + + Credentials skyflowCredentials = new Credentials(); + credentials.setPath(""); + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addConnectionConfig(connectionConfig1) + .addConnectionConfig(connectionConfig2) + .addSkyflowCredentials(skyflowCredentials) + .build(); + + Map requestBody = new HashMap<>(); + requestBody.put("", ""); + requestBody.put("", ""); + Map requestHeaders = new HashMap<>(); + requestHeaders.put("", ""); + requestHeaders.put("", ""); + InvokeConnectionRequest invokeConnectionRequest1 = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestBody(requestBody) + .requestHeaders(requestHeaders) + .build(); + InvokeConnectionResponse invokeConnectionResponse1 = skyflowClient.connection().invoke(invokeConnectionRequest1); + System.out.println(invokeConnectionResponse1); + + Map pathParams = new HashMap<>(); + pathParams.put("", ""); + pathParams.put("", ""); + Map queryParams = new HashMap<>(); + queryParams.put("", ""); + queryParams.put("", ""); + InvokeConnectionRequest invokeConnectionRequest2 = InvokeConnectionRequest.builder() + .methodName(RequestMethod.GET) + .pathParams(pathParams) + .queryParams(queryParams) + .build(); + InvokeConnectionResponse invokeConnectionResponse2 = skyflowClient + .connection("").invoke(invokeConnectionRequest2); + System.out.println(invokeConnectionResponse2); + } +} diff --git a/samples/src/main/java/com/example/vault/DeleteExample.java b/samples/src/main/java/com/example/vault/DeleteExample.java new file mode 100644 index 00000000..fa00e015 --- /dev/null +++ b/samples/src/main/java/com/example/vault/DeleteExample.java @@ -0,0 +1,52 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.DeleteRequest; +import com.skyflow.vault.data.DeleteResponse; + +import java.util.ArrayList; + +public class DeleteExample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); + + VaultConfig blitzConfig = new VaultConfig(); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); + blitzConfig.setEnv(Env.DEV); + blitzConfig.setCredentials(credentials); + + VaultConfig stageConfig = new VaultConfig(); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); + stageConfig.setEnv(Env.STAGE); + + Credentials skyflowCredentials = new Credentials(); + credentials.setPath(""); + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addVaultConfig(blitzConfig) + .addVaultConfig(stageConfig) + .addSkyflowCredentials(skyflowCredentials) + .build(); + + ArrayList ids1 = new ArrayList<>(); + ids1.add(""); + DeleteRequest deleteRequest1 = DeleteRequest.builder().ids(ids1).table("").build(); + DeleteResponse deleteResponse1 = skyflowClient.vault().delete(deleteRequest1); + System.out.println(deleteResponse1); + + ArrayList ids2 = new ArrayList<>(); + ids2.add(""); + DeleteRequest deleteRequest2 = DeleteRequest.builder().ids(ids2).table("").build(); + DeleteResponse deleteResponse2 = skyflowClient.vault("").delete(deleteRequest2); + System.out.println(deleteResponse2); + } +} diff --git a/samples/src/main/java/com/example/vault/DetokenizeExample.java b/samples/src/main/java/com/example/vault/DetokenizeExample.java new file mode 100644 index 00000000..4fde3fe7 --- /dev/null +++ b/samples/src/main/java/com/example/vault/DetokenizeExample.java @@ -0,0 +1,59 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.GetRequest; +import com.skyflow.vault.data.GetResponse; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.DetokenizeResponse; + +import java.util.ArrayList; + +public class DetokenizeExample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); + + VaultConfig blitzConfig = new VaultConfig(); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); + blitzConfig.setEnv(Env.DEV); + blitzConfig.setCredentials(credentials); + + VaultConfig stageConfig = new VaultConfig(); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); + stageConfig.setEnv(Env.STAGE); + + Credentials skyflowCredentials = new Credentials(); + credentials.setPath(""); + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addVaultConfig(blitzConfig) + .addVaultConfig(stageConfig) + .addSkyflowCredentials(skyflowCredentials) + .build(); + + ArrayList tokens1 = new ArrayList<>(); + tokens1.add(""); + tokens1.add(""); + DetokenizeRequest detokenizeRequest1 = DetokenizeRequest.builder().tokens(tokens1).continueOnError(true).build(); + DetokenizeResponse detokenizeResponse1 = skyflowClient.vault().detokenize(detokenizeRequest1); + System.out.println(detokenizeResponse1); + + ArrayList tokens2 = new ArrayList<>(); + tokens2.add(""); + tokens2.add(""); + + DetokenizeRequest detokenizeRequest2 = DetokenizeRequest.builder() + .tokens(tokens2).continueOnError(false).redactionType(RedactionType.DEFAULT).build(); + DetokenizeResponse detokenizeResponse2 = skyflowClient.vault("").detokenize(detokenizeRequest2); + System.out.println(detokenizeResponse2); + } +} diff --git a/samples/src/main/java/com/example/vault/GetExample.java b/samples/src/main/java/com/example/vault/GetExample.java new file mode 100644 index 00000000..afcb0021 --- /dev/null +++ b/samples/src/main/java/com/example/vault/GetExample.java @@ -0,0 +1,58 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.GetRequest; +import com.skyflow.vault.data.GetResponse; + +import java.util.ArrayList; + +public class GetExample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); + + VaultConfig blitzConfig = new VaultConfig(); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); + blitzConfig.setEnv(Env.DEV); + blitzConfig.setCredentials(credentials); + + VaultConfig stageConfig = new VaultConfig(); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); + stageConfig.setEnv(Env.STAGE); + + Credentials skyflowCredentials = new Credentials(); + credentials.setPath(""); + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addVaultConfig(blitzConfig) + .addVaultConfig(stageConfig) + .addSkyflowCredentials(skyflowCredentials) + .build(); + + ArrayList ids = new ArrayList<>(); + ids.add(""); + GetRequest getByIdRequest = GetRequest.builder().returnTokens(true).ids(ids).table("").build(); + GetResponse getByIdResponse = skyflowClient.vault().get(getByIdRequest); + System.out.println(getByIdResponse); + + ArrayList columnValues = new ArrayList<>(); + columnValues.add(""); + GetRequest getByColumnRequest = GetRequest.builder() + .table("") + .columnName("") + .columnValues(columnValues) + .redactionType(RedactionType.PLAIN_TEXT) + .build(); + GetResponse getByColumnResponse = skyflowClient.vault("").get(getByColumnRequest); + System.out.println(getByColumnResponse); + } +} diff --git a/samples/src/main/java/com/example/vault/InsertExample.java b/samples/src/main/java/com/example/vault/InsertExample.java new file mode 100644 index 00000000..d0bdec24 --- /dev/null +++ b/samples/src/main/java/com/example/vault/InsertExample.java @@ -0,0 +1,81 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Byot; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.InsertResponse; + +import java.util.ArrayList; +import java.util.HashMap; + +public class InsertExample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); + + VaultConfig blitzConfig = new VaultConfig(); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); + blitzConfig.setEnv(Env.DEV); + blitzConfig.setCredentials(credentials); + + VaultConfig stageConfig = new VaultConfig(); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); + stageConfig.setEnv(Env.STAGE); + + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setPath(""); + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addVaultConfig(blitzConfig) + .addVaultConfig(stageConfig) + .addSkyflowCredentials(skyflowCredentials) + .build(); + + ArrayList> values1 = new ArrayList<>(); + HashMap value1 = new HashMap<>(); + value1.put("", ""); + value1.put("", ""); + values1.add(value1); + + ArrayList> tokens = new ArrayList<>(); + HashMap token = new HashMap<>(); + token.put("", ""); + tokens.add(token); + + InsertRequest insertRequest = InsertRequest.builder() + .table("") + .continueOnError(true) + .tokenStrict(Byot.ENABLE) + .values(values1) + .tokens(tokens) + .returnTokens(true) + .build(); + InsertResponse insertResponse = skyflowClient.vault().insert(insertRequest); + System.out.println(insertResponse); + + ArrayList> values2 = new ArrayList<>(); + HashMap value2 = new HashMap<>(); + value2.put("", ""); + value2.put("", ""); + values2.add(value2); + + InsertRequest upsertRequest = InsertRequest.builder() + .table("") + .continueOnError(false) + .tokenStrict(Byot.DISABLE) + .values(values2) + .returnTokens(false) + .upsert("") + .build(); + InsertResponse upsertResponse = skyflowClient.vault("").insert(upsertRequest); + System.out.println(upsertResponse); + } +} diff --git a/samples/src/main/java/com/example/vault/QueryExample.java b/samples/src/main/java/com/example/vault/QueryExample.java new file mode 100644 index 00000000..98805b93 --- /dev/null +++ b/samples/src/main/java/com/example/vault/QueryExample.java @@ -0,0 +1,49 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.QueryRequest; +import com.skyflow.vault.data.QueryResponse; + +public class QueryExample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); + + VaultConfig blitzConfig = new VaultConfig(); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); + blitzConfig.setEnv(Env.DEV); + blitzConfig.setCredentials(credentials); + + VaultConfig stageConfig = new VaultConfig(); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); + stageConfig.setEnv(Env.STAGE); + + Credentials skyflowCredentials = new Credentials(); + credentials.setPath(""); + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addVaultConfig(blitzConfig) + .addVaultConfig(stageConfig) + .addSkyflowCredentials(skyflowCredentials) + .build(); + + String query1 = ""; + QueryRequest queryRequest1 = QueryRequest.builder().query(query1).build(); + QueryResponse queryResponse1 = skyflowClient.vault().query(queryRequest1); + System.out.println(queryResponse1); + + String query2 = ""; + QueryRequest queryRequest2 = QueryRequest.builder().query(query2).build(); + QueryResponse queryResponse2 = skyflowClient.vault("").query(queryRequest2); + System.out.println(queryResponse2); + + } +} diff --git a/samples/src/main/java/com/example/vault/TokenizeExample.java b/samples/src/main/java/com/example/vault/TokenizeExample.java new file mode 100644 index 00000000..ef6881b6 --- /dev/null +++ b/samples/src/main/java/com/example/vault/TokenizeExample.java @@ -0,0 +1,60 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.ColumnValue; +import com.skyflow.vault.tokens.TokenizeRequest; +import com.skyflow.vault.tokens.TokenizeResponse; + +import java.util.ArrayList; +import java.util.List; + +public class TokenizeExample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); + + VaultConfig blitzConfig = new VaultConfig(); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); + blitzConfig.setEnv(Env.DEV); + blitzConfig.setCredentials(credentials); + + VaultConfig stageConfig = new VaultConfig(); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); + stageConfig.setEnv(Env.STAGE); + + Credentials skyflowCredentials = new Credentials(); + credentials.setPath(""); + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addVaultConfig(blitzConfig) + .addVaultConfig(stageConfig) + .addSkyflowCredentials(skyflowCredentials) + .build(); + + List columnValues1 = new ArrayList<>(); + ColumnValue value1 = ColumnValue.builder().value("").columnGroup("").build(); + ColumnValue value2 = ColumnValue.builder().value("").columnGroup("").build(); + columnValues1.add(value1); + columnValues1.add(value2); + TokenizeRequest tokenizeRequest1 = TokenizeRequest.builder().values(columnValues1).build(); + TokenizeResponse tokenizeResponse1 = skyflowClient.vault().tokenize(tokenizeRequest1); + System.out.println(tokenizeResponse1); + + List columnValues2 = new ArrayList<>(); + ColumnValue value3 = ColumnValue.builder().value("").columnGroup("").build(); + ColumnValue value4 = ColumnValue.builder().value("").columnGroup("").build(); + columnValues2.add(value3); + columnValues2.add(value4); + TokenizeRequest tokenizeRequest2 = TokenizeRequest.builder().values(columnValues2).build(); + TokenizeResponse tokenizeResponse2 = skyflowClient.vault("").tokenize(tokenizeRequest2); + System.out.println(tokenizeResponse2); + } +} diff --git a/samples/src/main/java/com/example/vault/UpdateExample.java b/samples/src/main/java/com/example/vault/UpdateExample.java new file mode 100644 index 00000000..7dd18570 --- /dev/null +++ b/samples/src/main/java/com/example/vault/UpdateExample.java @@ -0,0 +1,73 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Byot; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.UpdateRequest; +import com.skyflow.vault.data.UpdateResponse; + +import java.util.HashMap; + +public class UpdateExample { + public static void main(String[] args) throws SkyflowException { + Credentials credentials = new Credentials(); + credentials.setPath(""); + + VaultConfig blitzConfig = new VaultConfig(); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); + blitzConfig.setEnv(Env.DEV); + blitzConfig.setCredentials(credentials); + + VaultConfig stageConfig = new VaultConfig(); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); + stageConfig.setEnv(Env.STAGE); + + Credentials skyflowCredentials = new Credentials(); + credentials.setPath(""); + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addVaultConfig(blitzConfig) + .addVaultConfig(stageConfig) + .addSkyflowCredentials(skyflowCredentials) + .build(); + + HashMap values1 = new HashMap<>(); + values1.put("", ""); + values1.put("", ""); + + HashMap tokens = new HashMap<>(); + tokens.put("", ""); + + UpdateRequest updateRequest1 = UpdateRequest.builder() + .id("") + .tokenStrict(Byot.ENABLE) + .values(values1) + .tokens(tokens) + .returnTokens(true) + .build(); + UpdateResponse updateResponse1 = skyflowClient.vault().update(updateRequest1); + System.out.println(updateResponse1); + + HashMap values2 = new HashMap<>(); + values2.put("", ""); + values2.put("", ""); + + UpdateRequest updateRequest2 = UpdateRequest.builder() + .id("") + .tokenStrict(Byot.DISABLE) + .values(values2) + .returnTokens(false) + .build(); + UpdateResponse updateResponse2 = skyflowClient.vault("").update(updateRequest2); + System.out.println(updateResponse2); + } +} From a1d64ce3d58e21e05ebd328623c0786a50f385ea Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 19 Nov 2024 19:43:03 +0530 Subject: [PATCH 052/126] SK-1685 Add samples for Bearer token utilities --- .../BearerTokenGenerationExample.java | 37 ++++++++++++ ...rerTokenGenerationUsingThreadsExample.java | 60 +++++++++++++++++++ ...arerTokenGenerationWithContextExample.java | 40 +++++++++++++ .../ScopedTokenGenerationExample.java | 45 ++++++++++++++ .../SignedTokenGenerationExample.java | 55 +++++++++++++++++ .../java/com/example/vault/DeleteExample.java | 12 ++-- .../com/example/vault/DetokenizeExample.java | 14 ++--- .../java/com/example/vault/GetExample.java | 12 ++-- .../java/com/example/vault/InsertExample.java | 12 ++-- .../java/com/example/vault/QueryExample.java | 12 ++-- .../com/example/vault/TokenizeExample.java | 12 ++-- .../java/com/example/vault/UpdateExample.java | 12 ++-- 12 files changed, 279 insertions(+), 44 deletions(-) create mode 100644 samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java create mode 100644 samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java create mode 100644 samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java create mode 100644 samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java create mode 100644 samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java new file mode 100644 index 00000000..ae1bce1b --- /dev/null +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java @@ -0,0 +1,37 @@ +package com.example.serviceaccount; + +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.BearerToken; +import com.skyflow.serviceaccount.util.Token; + +import java.io.File; + +public class BearerTokenGenerationExample { + public static void main(String[] args) { + String token = null; + + // Generate BearerToken by specifying credentials.json file path + try { + String filePath = ""; + if (Token.isExpired(token)) { + BearerToken bearerToken = BearerToken.builder().setCredentials(new File(filePath)).build(); + token = bearerToken.getBearerToken(); + } + System.out.println(token); + } catch (Exception e) { + e.printStackTrace(); + } + + // Generate BearerToken by specifying credentials.json as string + try { + String fileContents = ""; + if (Token.isExpired(token)) { + BearerToken bearerToken = BearerToken.builder().setCredentials(fileContents).build(); + token = bearerToken.getBearerToken(); + } + System.out.println(token); + } catch (SkyflowException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java new file mode 100644 index 00000000..1d750ade --- /dev/null +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java @@ -0,0 +1,60 @@ +package com.example.serviceaccount; + +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.BearerToken; + +import java.io.File; + +public class BearerTokenGenerationUsingThreadsExample { + public static void main(String[] args) { + // Generate BearerToken with context by specifying credentials.json file path + try { + String filePath = ""; + final BearerToken bearerToken = new BearerToken.BearerTokenBuilder() + .setCredentials(new File(filePath)) + .setCtx("abc") + .build(); + + Thread t = new Thread(() -> { + for (int i = 0; i < 5; i++) { + try { + System.out.println(bearerToken.getBearerToken()); + } catch (SkyflowException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + + } + + } + }); + t.start(); + } catch (Exception e) { + e.printStackTrace(); + } + + // Generate BearerToken with context by specifying credentials.json as string + try { + String fileContents = ""; + final BearerToken bearerToken = new BearerToken.BearerTokenBuilder() + .setCredentials(fileContents) + .setCtx("abc") + .build(); + + Thread t = new Thread(() -> { + for (int i = 0; i < 5; i++) { + try { + System.out.println(bearerToken.getBearerToken()); + } catch (SkyflowException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + + } + + } + }); + t.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java new file mode 100644 index 00000000..69e6ff14 --- /dev/null +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java @@ -0,0 +1,40 @@ +package com.example.serviceaccount; + +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.BearerToken; + +import java.io.File; + +public class BearerTokenGenerationWithContextExample { + public static void main(String[] args) { + String bearerToken = null; + + // Generate BearerToken with context by specifying credentials.json file path + try { + String filePath = ""; + BearerToken token = new BearerToken.BearerTokenBuilder() + .setCredentials(new File(filePath)) + .setCtx("abc") + .build(); + + bearerToken = token.getBearerToken(); + System.out.println(bearerToken); + } catch (Exception e) { + e.printStackTrace(); + } + + // Generate BearerToken with context by specifying credentials.json as string + try { + String fileContents = ""; + BearerToken token = new BearerToken.BearerTokenBuilder() + .setCredentials(fileContents) + .setCtx("abc") + .build(); + + bearerToken = token.getBearerToken(); + System.out.println(bearerToken); + } catch (SkyflowException e) { + e.printStackTrace(); + } + } +} diff --git a/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java b/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java new file mode 100644 index 00000000..b8dfbc53 --- /dev/null +++ b/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java @@ -0,0 +1,45 @@ +package com.example.serviceaccount; + +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.BearerToken; + +import java.io.File; +import java.util.ArrayList; + +public class ScopedTokenGenerationExample { + public static void main(String[] args) { + String scopedToken = null; + + // Generate Scoped Token by specifying credentials.json file path + try { + ArrayList roles = new ArrayList<>(); + roles.add("YOUR_ROLE_ID"); + String filePath = ""; + BearerToken bearerToken = new BearerToken.BearerTokenBuilder() + .setCredentials(new File(filePath)) + .setRoles(roles) + .build(); + + scopedToken = bearerToken.getBearerToken(); + System.out.println(scopedToken); + } catch (Exception e) { + e.printStackTrace(); + } + + // Generate BearerToken with context by specifying credentials.json as string + try { + ArrayList roles = new ArrayList<>(); + roles.add("YOUR_ROLE_ID"); + String fileContents = ""; + BearerToken bearerToken = new BearerToken.BearerTokenBuilder() + .setCredentials(fileContents) + .setRoles(roles) + .build(); + + scopedToken = bearerToken.getBearerToken(); + System.out.println(scopedToken); + } catch (SkyflowException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java b/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java new file mode 100644 index 00000000..7f030838 --- /dev/null +++ b/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java @@ -0,0 +1,55 @@ +package com.example.serviceaccount; + +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.SignedDataTokenResponse; +import com.skyflow.serviceaccount.util.SignedDataTokens; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +public class SignedTokenGenerationExample { + public static void main(String[] args) { + List signedTokenValues; + + // Generate Signed data token with context by specifying credentials.json file path + try { + String filePath = ""; + String context = "abc"; + ArrayList dataTokens = new ArrayList<>(); + dataTokens.add("YOUR_DATA_TOKEN_1"); + SignedDataTokens signedToken = new SignedDataTokens.SignedDataTokensBuilder() + .setCredentials(new File(filePath)) + .setCtx(context) + .setTimeToLive(30) // in seconds + .setDataTokens(dataTokens) + .build(); + + signedTokenValues = signedToken.getSignedDataTokens(); + System.out.println(signedTokenValues); + } catch (Exception e) { + e.printStackTrace(); + } + + // Generate Signed data token with context by specifying credentials.json as string + try { + String fileContents = ""; + String context = "abc"; + ArrayList dataTokens = new ArrayList<>(); + dataTokens.add("YOUR_DATA_TOKEN_1"); + SignedDataTokens signedToken = new SignedDataTokens.SignedDataTokensBuilder() + .setCredentials(fileContents) + .setCtx(context) + .setTimeToLive(30) // in seconds + .setDataTokens(dataTokens) + .build(); + + signedTokenValues = signedToken.getSignedDataTokens(); + System.out.println(signedTokenValues); + + } catch (SkyflowException e) { + e.printStackTrace(); + } + } +} + diff --git a/samples/src/main/java/com/example/vault/DeleteExample.java b/samples/src/main/java/com/example/vault/DeleteExample.java index fa00e015..17887204 100644 --- a/samples/src/main/java/com/example/vault/DeleteExample.java +++ b/samples/src/main/java/com/example/vault/DeleteExample.java @@ -14,21 +14,21 @@ public class DeleteExample { public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); blitzConfig.setEnv(Env.DEV); blitzConfig.setCredentials(credentials); VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) diff --git a/samples/src/main/java/com/example/vault/DetokenizeExample.java b/samples/src/main/java/com/example/vault/DetokenizeExample.java index 4fde3fe7..f026e43e 100644 --- a/samples/src/main/java/com/example/vault/DetokenizeExample.java +++ b/samples/src/main/java/com/example/vault/DetokenizeExample.java @@ -7,8 +7,6 @@ import com.skyflow.enums.LogLevel; import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.data.GetRequest; -import com.skyflow.vault.data.GetResponse; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.DetokenizeResponse; @@ -17,21 +15,21 @@ public class DetokenizeExample { public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); blitzConfig.setEnv(Env.DEV); blitzConfig.setCredentials(credentials); VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) diff --git a/samples/src/main/java/com/example/vault/GetExample.java b/samples/src/main/java/com/example/vault/GetExample.java index afcb0021..357c3516 100644 --- a/samples/src/main/java/com/example/vault/GetExample.java +++ b/samples/src/main/java/com/example/vault/GetExample.java @@ -15,21 +15,21 @@ public class GetExample { public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); blitzConfig.setEnv(Env.DEV); blitzConfig.setCredentials(credentials); VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) diff --git a/samples/src/main/java/com/example/vault/InsertExample.java b/samples/src/main/java/com/example/vault/InsertExample.java index d0bdec24..21d9260b 100644 --- a/samples/src/main/java/com/example/vault/InsertExample.java +++ b/samples/src/main/java/com/example/vault/InsertExample.java @@ -16,21 +16,21 @@ public class InsertExample { public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); blitzConfig.setEnv(Env.DEV); blitzConfig.setCredentials(credentials); VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); + credentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) diff --git a/samples/src/main/java/com/example/vault/QueryExample.java b/samples/src/main/java/com/example/vault/QueryExample.java index 98805b93..c80a2443 100644 --- a/samples/src/main/java/com/example/vault/QueryExample.java +++ b/samples/src/main/java/com/example/vault/QueryExample.java @@ -12,21 +12,21 @@ public class QueryExample { public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); blitzConfig.setEnv(Env.DEV); blitzConfig.setCredentials(credentials); VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) diff --git a/samples/src/main/java/com/example/vault/TokenizeExample.java b/samples/src/main/java/com/example/vault/TokenizeExample.java index ef6881b6..f7677670 100644 --- a/samples/src/main/java/com/example/vault/TokenizeExample.java +++ b/samples/src/main/java/com/example/vault/TokenizeExample.java @@ -16,21 +16,21 @@ public class TokenizeExample { public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); blitzConfig.setEnv(Env.DEV); blitzConfig.setCredentials(credentials); VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) diff --git a/samples/src/main/java/com/example/vault/UpdateExample.java b/samples/src/main/java/com/example/vault/UpdateExample.java index 7dd18570..b782d80d 100644 --- a/samples/src/main/java/com/example/vault/UpdateExample.java +++ b/samples/src/main/java/com/example/vault/UpdateExample.java @@ -15,21 +15,21 @@ public class UpdateExample { public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); + blitzConfig.setVaultId(""); + blitzConfig.setClusterId(""); blitzConfig.setEnv(Env.DEV); blitzConfig.setCredentials(credentials); VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); + stageConfig.setVaultId(""); + stageConfig.setClusterId(""); stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) From 6a9e5838fb3ca97414bb6dc6228a188400c053e0 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 20 Nov 2024 15:13:11 +0530 Subject: [PATCH 053/126] SK-1623 Fix minor issues in Javs SDK v2 --- pom.xml | 11 ++--- src/main/java/com/skyflow/VaultClient.java | 4 +- .../java/com/skyflow/errors/ErrorMessage.java | 2 +- .../connection/InvokeConnectionRequest.java | 3 -- .../controller/ConnectionController.java | 3 +- .../skyflow/vault/data/UpdateResponse.java | 6 ++- .../vault/tokens/DetokenizeResponse.java | 2 +- .../vault/tokens/TokenizeResponse.java | 13 +++++- .../util/SignedDataTokensTests.java | 13 ++++++ .../controller/ConnectionControllerTests.java | 7 +++- .../com/skyflow/vault/data/UpdateTests.java | 2 +- .../skyflow/vault/tokens/DetokenizeTests.java | 42 +++++++++++++++++++ .../skyflow/vault/tokens/TokenizeTests.java | 16 +++++++ 13 files changed, 104 insertions(+), 20 deletions(-) diff --git a/pom.xml b/pom.xml index ea4cbd29..1dc1b785 100644 --- a/pom.xml +++ b/pom.xml @@ -186,11 +186,6 @@ org.jacoco jacoco-maven-plugin 0.8.7 - - - **/example/* - - prepare-agent @@ -206,6 +201,12 @@ + + + **/example/* + **/generated/** + + org.apache.maven.plugins diff --git a/src/main/java/com/skyflow/VaultClient.java b/src/main/java/com/skyflow/VaultClient.java index 55a16024..08c161de 100644 --- a/src/main/java/com/skyflow/VaultClient.java +++ b/src/main/java/com/skyflow/VaultClient.java @@ -105,7 +105,7 @@ protected RecordServiceInsertRecordBody getBulkInsertRequestBody(InsertRequest r for (int index = 0; index < values.size(); index++) { V1FieldRecords record = new V1FieldRecords(); record.setFields(values.get(index)); - if (tokens != null) { + if (tokens != null && index < tokens.size()) { record.setTokens(tokens.get(index)); } records.add(record); @@ -130,7 +130,7 @@ protected RecordServiceBatchOperationBody getBatchInsertRequestBody(InsertReques record.setUpsert(request.getUpsert()); record.setTokenization(request.getReturnTokens()); record.setFields(values.get(index)); - if (tokens != null) { + if (tokens != null && index < tokens.size()) { record.setTokens(tokens.get(index)); } records.add(record); diff --git a/src/main/java/com/skyflow/errors/ErrorMessage.java b/src/main/java/com/skyflow/errors/ErrorMessage.java index c7ac207a..31648fb8 100644 --- a/src/main/java/com/skyflow/errors/ErrorMessage.java +++ b/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -113,7 +113,7 @@ public enum ErrorMessage { // connection InvalidRequestHeaders("%s0 Validation error. Request headers aren't valid. Specify valid request headers."), - EmptyRequestHeaders("%s0 Validation error. Request headers are empty. Specify valid ."), + EmptyRequestHeaders("%s0 Validation error. Request headers are empty. Specify valid request headers."), InvalidPathParams("%s0 Validation error. Path parameters aren't valid. Specify valid path parameters."), EmptyPathParams("%s0 Validation error. Path parameters are empty. Specify valid path parameters."), InvalidQueryParams("%s0 Validation error. Query parameters aren't valid. Specify valid query parameters."), diff --git a/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java b/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java index 5edf4f4f..c64bedf4 100644 --- a/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java +++ b/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java @@ -46,9 +46,6 @@ public static final class InvokeConnectionRequestBuilder { private InvokeConnectionRequestBuilder() { this.methodName = RequestMethod.POST; - this.pathParams = new HashMap<>(); - this.queryParams = new HashMap<>(); - this.requestHeaders = new HashMap<>(); this.requestBody = new Object(); } diff --git a/src/main/java/com/skyflow/vault/controller/ConnectionController.java b/src/main/java/com/skyflow/vault/controller/ConnectionController.java index 7ae03a2a..890ef530 100644 --- a/src/main/java/com/skyflow/vault/controller/ConnectionController.java +++ b/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -40,7 +40,8 @@ public InvokeConnectionResponse invoke(InvokeConnectionRequest invokeConnectionR String filledURL = Utils.constructConnectionURL(super.getConnectionConfig(), invokeConnectionRequest); Map headers = new HashMap<>(); - if (invokeConnectionRequest.getRequestHeaders().containsKey("requestHeader")) { + Map requestHeaders = invokeConnectionRequest.getRequestHeaders(); + if (requestHeaders != null && requestHeaders.containsKey("requestHeader")) { headers = Utils.constructConnectionHeadersMap(invokeConnectionRequest.getRequestHeaders()); } if (!headers.containsKey("x-skyflow-authorization")) { diff --git a/src/main/java/com/skyflow/vault/data/UpdateResponse.java b/src/main/java/com/skyflow/vault/data/UpdateResponse.java index 0f860b22..2ca52365 100644 --- a/src/main/java/com/skyflow/vault/data/UpdateResponse.java +++ b/src/main/java/com/skyflow/vault/data/UpdateResponse.java @@ -22,8 +22,10 @@ public HashMap getTokens() { @Override public String toString() { StringBuilder response = new StringBuilder("{"); - response.append("\n\t\"skyflowId\": ").append(skyflowId); - response.append("\n\t\"tokens\": ").append(formatRecords(tokens)); + response.append("\n\t\"skyflowId\": \"").append(skyflowId).append("\""); + if (!tokens.isEmpty()) { + response.append("\n\t\"tokens\": ").append(formatRecords(tokens)); + } response.append("\n}"); return response.toString(); } diff --git a/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java index beb51700..0c136e1a 100644 --- a/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java @@ -23,7 +23,7 @@ public ArrayList getErrors() { public String toString() { StringBuilder response = new StringBuilder("{"); response.append("\n\t").append("\"detokenizedFields\": ").append(toIndentedString(detokenizedFields)); - response.append("\n\t").append("\"errors\": \"").append(toIndentedString(errorRecords)); + response.append("\n\t").append("\"errors\": ").append(toIndentedString(errorRecords)); response.append("\n}"); return response.toString(); } diff --git a/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java b/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java index 8f62631b..a82d081a 100644 --- a/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java +++ b/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java @@ -3,11 +3,20 @@ import java.util.List; public class TokenizeResponse { - - private List tokens; + private final List tokens; public TokenizeResponse(List tokens) { this.tokens = tokens; } + public List getTokens() { + return tokens; + } + + @Override + public String toString() { + StringBuilder response = new StringBuilder("{"); + response.append("\n\t\"tokens\": ").append(tokens); + return response.append("\n}").toString(); + } } diff --git a/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java index 5e631995..50b97e11 100644 --- a/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java +++ b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java @@ -206,4 +206,17 @@ public void testInvalidKeySpecInCredentials() { Assert.assertEquals(ErrorMessage.InvalidKeySpec.getMessage(), e.getMessage()); } } + + @Test + public void testSignedDataTokenResponse() { + try { + String signedToken = "test_signed_data_token"; + SignedDataTokenResponse response = new SignedDataTokenResponse(dataToken, signedToken); + String responseString = "{\n\t\"dataToken\":\"" + dataToken + "\"," + + "\n\t\"signedDataToken\":\"signed_token_" + signedToken + "\",\n}"; + Assert.assertEquals(responseString, response.toString()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } } diff --git a/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java b/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java index 036dfdcd..102eb9d7 100644 --- a/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java +++ b/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java @@ -12,6 +12,8 @@ import org.junit.BeforeClass; import org.junit.Test; +import java.util.HashMap; + public class ConnectionControllerTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; @@ -37,13 +39,14 @@ public static void setup() { @Test public void testInvalidRequestInInvokeConnectionMethod() { try { - InvokeConnectionRequest connectionRequest = InvokeConnectionRequest.builder().build(); + HashMap requestBody = new HashMap<>(); + InvokeConnectionRequest connectionRequest = InvokeConnectionRequest.builder().requestBody(requestBody).build(); Skyflow skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addConnectionConfig(connectionConfig).build(); skyflowClient.connection().invoke(connectionRequest); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.EmptyRequestHeaders.getMessage(), e.getMessage()); + Assert.assertEquals(ErrorMessage.EmptyRequestBody.getMessage(), e.getMessage()); } } } diff --git a/src/test/java/com/skyflow/vault/data/UpdateTests.java b/src/test/java/com/skyflow/vault/data/UpdateTests.java index e6c41db9..b82a0734 100644 --- a/src/test/java/com/skyflow/vault/data/UpdateTests.java +++ b/src/test/java/com/skyflow/vault/data/UpdateTests.java @@ -370,7 +370,7 @@ public void testUpdateResponse() { tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("test_column_2", "test_token_2"); UpdateResponse response = new UpdateResponse(skyflowID, tokenMap); - String responseString = "{\n\t\"skyflowId\": " + skyflowID + "\n\t\"tokens\": " + String responseString = "{\n\t\"skyflowId\": \"" + skyflowID + "\"\n\t\"tokens\": " + "{\n\t\t\"test_column_1\": \"test_token_1\"," + "\n\t\t\"test_column_2\": \"test_token_2\",\n\t}\n}"; Assert.assertEquals(skyflowID, response.getSkyflowId()); diff --git a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index 3fe57faa..6c49bc8c 100644 --- a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -4,6 +4,8 @@ import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.models.DetokenizeRecordResponseValueType; +import com.skyflow.generated.rest.models.V1DetokenizeRecordResponse; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; @@ -112,4 +114,44 @@ public void testRedactionAndContinueOnErrorInDetokenizeRequestValidations() { Assert.fail(INVALID_EXCEPTION_THROWN); } } + + @Test + public void testDetokenizeResponse() { + try { + V1DetokenizeRecordResponse record1 = new V1DetokenizeRecordResponse(); + record1.setToken("1234-5678-9012-3456"); + record1.setValue("4111111111111111"); + record1.setValueType(DetokenizeRecordResponseValueType.STRING); + DetokenizeRecordResponse field = new DetokenizeRecordResponse(record1); + + V1DetokenizeRecordResponse record2 = new V1DetokenizeRecordResponse(); + record2.setToken("3456-7890-1234-5678"); + record2.setError("Invalid token"); + DetokenizeRecordResponse error = new DetokenizeRecordResponse(record2); + + ArrayList fields = new ArrayList<>(); + fields.add(field); + fields.add(field); + + ArrayList errors = new ArrayList<>(); + errors.add(error); + errors.add(error); + + DetokenizeResponse response = new DetokenizeResponse(fields, errors); + String responseString = "{\n\t\"detokenizedFields\": [{" + + "\n\t\t\"token\": \"1234-5678-9012-3456\",\n\t\t\"value\": \"4111111111111111\",\n\t\t\"type\": \"STRING\",\n\t}, " + + "{\n\t\t\"token\": \"1234-5678-9012-3456\",\n\t\t\"value\": \"4111111111111111\",\n\t\t\"type\": \"STRING\",\n\t}]" + + "\n\t\"errors\": [{\n\t\t\"token\": \"3456-7890-1234-5678\",\n\t\t\"error\": \"Invalid token\",\n\t}, " + + "{\n\t\t\"token\": \"3456-7890-1234-5678\",\n\t\t\"error\": \"Invalid token\",\n\t}]\n}"; + Assert.assertEquals(2, response.getDetokenizedFields().size()); + Assert.assertEquals(2, response.getErrors().size()); + Assert.assertEquals("1234-5678-9012-3456", response.getDetokenizedFields().get(0).getToken()); + Assert.assertEquals("4111111111111111", response.getDetokenizedFields().get(0).getValue()); + Assert.assertEquals("STRING", response.getDetokenizedFields().get(0).getType()); + Assert.assertEquals("Invalid token", response.getErrors().get(0).getError()); + Assert.assertEquals(responseString, response.toString()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } } diff --git a/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java index 850553f4..18edf253 100644 --- a/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java @@ -47,6 +47,8 @@ public static void setup() { columnValues = new ArrayList<>(); value = "test_value"; group = "test_group"; + + tokens = new ArrayList<>(); } @Before @@ -120,4 +122,18 @@ public void testEmptyColumnGroupInColumnValuesInTokenizeRequestValidations() { Assert.assertEquals(ErrorMessage.EmptyColumnGroupInColumnValue.getMessage(), e.getMessage()); } } + + @Test + public void testTokenizeResponse() { + try { + tokens.add("1234-5678-9012-3456"); + tokens.add("5678-9012-3456-7890"); + TokenizeResponse response = new TokenizeResponse(tokens); + String responseString = "{\n\t\"tokens\": [1234-5678-9012-3456, 5678-9012-3456-7890]\n}"; + Assert.assertEquals(2, response.getTokens().size()); + Assert.assertEquals(responseString, response.toString()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } } From b9ab36f9301f0b5fe92a3a263f940c877bff7f8b Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 19 Nov 2024 20:23:17 +0530 Subject: [PATCH 054/126] SK-1752 workflow for internal release --- .github/workflows/internal-release.yml | 39 +++++++++++++++ .github/workflows/release.yml | 2 +- pom.xml | 66 +++++++++++++++++--------- 3 files changed, 83 insertions(+), 24 deletions(-) create mode 100644 .github/workflows/internal-release.yml diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml new file mode 100644 index 00000000..1bacef24 --- /dev/null +++ b/.github/workflows/internal-release.yml @@ -0,0 +1,39 @@ +name: Publish package to the JFROG Artifactory +on: + push: + tags: '*.*.*' + paths-ignore: + - "pom.xml" + - "*.md" + branches: + - release/* + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - name: Set up Jfrog artifactory + uses: actions/setup-java@v1 + with: + java-version: '1.8' + distribution: 'adopt' + server-id: central + server-username: JFROG_USERNAME + server-password: JFROG_PASSWORD + gpg-private-key: ${{ secrets.JFROG_GPG_KEY }} # Value of the GPG private key to import + gpg-passphrase: JFROG_GPG_PASSPHRASE # env variable for GPG private key passphrase + + - name: create-json + id: create-json + uses: jsdaniell/create-json@1.1.2 + with: + name: "credentials.json" + json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} + + - name: Publish package to Jfrog Artifactory + run: mvn clean deploy -P jfrog + env: + JFROG_USERNAME: ${{ secrets.ARTIFACTORY_USERNAME }} + JFROG_PASSWORD: ${{ secrets.ARTIFACTORY_PASSWORD }} + JFROG_GPG_PASSPHRASE: ${{ secrets.JFROG_GPG_PASSPHRASE }} \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 02c7b612..f30dda26 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,7 +26,7 @@ jobs: json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - name: Publish package to Maven Central - run: mvn --batch-mode deploy + run: mvn --batch-mode deploy -P maven-central env: MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} MAVEN_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} diff --git a/pom.xml b/pom.xml index 1dc1b785..1bbca53f 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0 + 1.15.0-v2dev1.0 jar ${project.groupId}:${project.artifactId} @@ -44,17 +44,6 @@ 1.3.5 - - - ossrh - https://s01.oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://s01.oss.sonatype.org/service/local/staging/deploy/maven2 - - - @@ -132,17 +121,17 @@ - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ossrh - https://s01.oss.sonatype.org/ - true - - + + + + + + + + + + + org.apache.maven.plugins maven-source-plugin @@ -253,4 +242,35 @@ + + + maven-central + + + ossrh + https://s01.oss.sonatype.org/service/local/staging/deploy/maven2 + + + ossrh + https://s01.oss.sonatype.org/content/repositories/snapshots + + + + + jfrog + + + central + prekarilabs.jfrog.io-releases + https://prekarilabs.jfrog.io/artifactory/skyflow-java + + + snapshots + prekarilabs.jfrog.io-snapshots + https://prekarilabs.jfrog.io/artifactory/skyflow-java + + + + + \ No newline at end of file From 656272d73e1f7eb87f57e532065295b9c9e445e0 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 19 Nov 2024 21:42:35 +0530 Subject: [PATCH 055/126] SK-1752 workflow for internal release --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1bbca53f..90f9d592 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0-v2dev1.0 + 1.15.0-v2dev2.0 jar ${project.groupId}:${project.artifactId} From 57657d2421f468d7bbf1f454beab723a27ccf08a Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 19 Nov 2024 22:03:42 +0530 Subject: [PATCH 056/126] SK-1753 add create env step --- .github/workflows/internal-release.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index 1bacef24..38d6424f 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -24,6 +24,13 @@ jobs: gpg-private-key: ${{ secrets.JFROG_GPG_KEY }} # Value of the GPG private key to import gpg-passphrase: JFROG_GPG_PASSPHRASE # env variable for GPG private key passphrase + - name: create env + id: create-env + run: | + touch .env + echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env + echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + - name: create-json id: create-json uses: jsdaniell/create-json@1.1.2 From d09ff9428f59e02b82f8c03098c5c83c326a36ce Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Wed, 20 Nov 2024 15:54:52 +0530 Subject: [PATCH 057/126] SK-1753 auto generate release version in pom.xml --- .github/workflows/internal-release.yml | 23 +++++++++++++-- pom.xml | 2 +- scripts/bump_version.sh | 40 ++++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 3 deletions(-) create mode 100755 scripts/bump_version.sh diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index 38d6424f..17176e5e 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -24,14 +24,33 @@ jobs: gpg-private-key: ${{ secrets.JFROG_GPG_KEY }} # Value of the GPG private key to import gpg-passphrase: JFROG_GPG_PASSPHRASE # env variable for GPG private key passphrase - - name: create env + - name: Get Previous tag + id: previoustag + uses: WyriHaximus/github-action-get-previous-tag@v1 + with: + fallback: 1.0.0 + + - name: Bump Version + run: | + chmod +x ./scripts/bump_version.sh + ./scripts/bump_version.sh "${{ steps.previoustag.outputs.tag }}" "$(git rev-parse --short "$GITHUB_SHA")" + + - name: Commit changes + run: | + git config user.name ${{ github.actor }} + git config user.email ${{ github.actor }}@users.noreply.github.com + git add pom.xml + git commit -m "[AUTOMATED] Private Release ${{ steps.previoustag.outputs.tag }}-dev.$(git rev-parse --short $GITHUB_SHA)" + git push origin -f + + - name: Create env id: create-env run: | touch .env echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env - - name: create-json + - name: Create credentials json id: create-json uses: jsdaniell/create-json@1.1.2 with: diff --git a/pom.xml b/pom.xml index 90f9d592..b0686004 100644 --- a/pom.xml +++ b/pom.xml @@ -273,4 +273,4 @@ - \ No newline at end of file + diff --git a/scripts/bump_version.sh b/scripts/bump_version.sh new file mode 100755 index 00000000..58ab83a5 --- /dev/null +++ b/scripts/bump_version.sh @@ -0,0 +1,40 @@ +# Input Arguments +Version=$1 +CommitHash=$2 +PomFile="../pom.xml" + +if [ -z "$Version" ]; then + echo "Error: Version argument is required." + exit 1 +fi + +# Update only the main project's +if [ -z "$CommitHash" ]; then + echo "Bumping main project version to $Version" + + awk -v version="$Version" ' + BEGIN { updated = 0 } + // && updated == 0 { + sub(/.*<\/version>/, "" version "") + updated = 1 + } + { print } + ' "$PomFile" > tempfile && cat tempfile > "$PomFile" && rm -f tempfile + + echo "--------------------------" + echo "Done. Main project version now at $Version" +else + echo "Bumping main project version to $Version-dev-$CommitHash" + + awk -v version="$Version-dev.$CommitHash" ' + BEGIN { updated = 0 } + // && updated == 0 { + sub(/.*<\/version>/, "" version "") + updated = 1 + } + { print } + ' "$PomFile" > tempfile && cat tempfile > "$PomFile" && rm -f tempfile + + echo "--------------------------" + echo "Done. Main project version now at $Version-dev.$CommitHash" +fi From b76fa831677a38f8dd572d16f9096b16c7f7aa03 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Wed, 20 Nov 2024 16:28:00 +0530 Subject: [PATCH 058/126] SK-1753 auto generate release version in pom.xml --- .github/workflows/internal-release.yml | 7 ++++++- scripts/bump_version.sh | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index 17176e5e..959f0000 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -7,6 +7,8 @@ on: - "*.md" branches: - release/* + pull-request: + - release/* jobs: publish: @@ -30,6 +32,9 @@ jobs: with: fallback: 1.0.0 + - name: Print working directory + run: pwd + - name: Bump Version run: | chmod +x ./scripts/bump_version.sh @@ -58,7 +63,7 @@ jobs: json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - name: Publish package to Jfrog Artifactory - run: mvn clean deploy -P jfrog + run: mvn clean deplo -P jfrog env: JFROG_USERNAME: ${{ secrets.ARTIFACTORY_USERNAME }} JFROG_PASSWORD: ${{ secrets.ARTIFACTORY_PASSWORD }} diff --git a/scripts/bump_version.sh b/scripts/bump_version.sh index 58ab83a5..d729ea63 100755 --- a/scripts/bump_version.sh +++ b/scripts/bump_version.sh @@ -1,7 +1,7 @@ # Input Arguments Version=$1 CommitHash=$2 -PomFile="../pom.xml" +PomFile="$GITHUB_WORKSPACE/pom.xml" if [ -z "$Version" ]; then echo "Error: Version argument is required." From 92eae6ab8976d9487544a9076a163c56c913b2bd Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Wed, 20 Nov 2024 16:31:56 +0530 Subject: [PATCH 059/126] SK-1753 auto generate release version in pom.xml --- .github/workflows/internal-release.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index 959f0000..829f0c29 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -6,9 +6,9 @@ on: - "pom.xml" - "*.md" branches: - - release/* - pull-request: - - release/* + branches: [ release/*, '*' ] + pull_request: + branches: [ release/* ] jobs: publish: From 167b1b41d17f3af7df16ca0524351dc9dc2bcf17 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Wed, 20 Nov 2024 16:38:55 +0530 Subject: [PATCH 060/126] SK-1753 auto generate release version in pom.xml --- .github/workflows/internal-release.yml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index 829f0c29..b5d40bcc 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -5,10 +5,9 @@ on: paths-ignore: - "pom.xml" - "*.md" - branches: - branches: [ release/*, '*' ] - pull_request: - branches: [ release/* ] + branches: [ release/*, '*' ] + pull_request: + branches: [ release/* ] jobs: publish: From 953903a3ff94f1cdac3542addaf250b22f8c2671 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Wed, 20 Nov 2024 16:45:43 +0530 Subject: [PATCH 061/126] SK-1753 auto generate release version in pom.xml --- .github/workflows/internal-release.yml | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index b5d40bcc..4fbb156f 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -5,9 +5,8 @@ on: paths-ignore: - "pom.xml" - "*.md" - branches: [ release/*, '*' ] - pull_request: - branches: [ release/* ] + branches: + - release/* jobs: publish: @@ -31,9 +30,6 @@ jobs: with: fallback: 1.0.0 - - name: Print working directory - run: pwd - - name: Bump Version run: | chmod +x ./scripts/bump_version.sh From 817bdc4b9c447cf4bb6164d7c12c4954b9b014c3 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Wed, 20 Nov 2024 16:48:06 +0530 Subject: [PATCH 062/126] SK-1753 auto generate release version in pom.xml --- .github/workflows/internal-release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index 4fbb156f..17176e5e 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -58,7 +58,7 @@ jobs: json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - name: Publish package to Jfrog Artifactory - run: mvn clean deplo -P jfrog + run: mvn clean deploy -P jfrog env: JFROG_USERNAME: ${{ secrets.ARTIFACTORY_USERNAME }} JFROG_PASSWORD: ${{ secrets.ARTIFACTORY_PASSWORD }} From 5e2d385dea430fbc503f3fba86a78667032a9310 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Wed, 20 Nov 2024 17:05:27 +0530 Subject: [PATCH 063/126] SK-1753 auto generate release version in pom.xml --- .github/workflows/internal-release.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index 17176e5e..5d82fda1 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -12,7 +12,11 @@ jobs: publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v2 + with: + ref: ${{ github.ref_name }} + fetch-depth: 0 + - name: Set up Jfrog artifactory uses: actions/setup-java@v1 with: From 5c482719042b8296e319110adb4cb21126b9ee7a Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Wed, 20 Nov 2024 17:26:47 +0530 Subject: [PATCH 064/126] SK-1753 restore version in pom.xml --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b0686004..36544eb5 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0-v2dev2.0 + 1.15.0 jar ${project.groupId}:${project.artifactId} From 222e54a291d7b1684970bcd7113066a737863eb8 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 20 Nov 2024 17:39:45 +0530 Subject: [PATCH 065/126] SK-1623 Fix typos in Samples --- .../connection/InvokeConnectionExample.java | 30 +++++++++---------- .../java/com/example/vault/DeleteExample.java | 12 ++++---- .../com/example/vault/DetokenizeExample.java | 12 ++++---- .../java/com/example/vault/GetExample.java | 14 ++++----- .../java/com/example/vault/InsertExample.java | 20 ++++++------- .../java/com/example/vault/QueryExample.java | 8 ++--- .../com/example/vault/TokenizeExample.java | 12 ++++---- .../java/com/example/vault/UpdateExample.java | 22 +++++++------- 8 files changed, 65 insertions(+), 65 deletions(-) diff --git a/samples/src/main/java/com/example/connection/InvokeConnectionExample.java b/samples/src/main/java/com/example/connection/InvokeConnectionExample.java index 1c1ee12f..431fd79d 100644 --- a/samples/src/main/java/com/example/connection/InvokeConnectionExample.java +++ b/samples/src/main/java/com/example/connection/InvokeConnectionExample.java @@ -15,19 +15,19 @@ public class InvokeConnectionExample { public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); ConnectionConfig connectionConfig1 = new ConnectionConfig(); - connectionConfig1.setConnectionId(""); - connectionConfig1.setConnectionUrl(""); + connectionConfig1.setConnectionId(""); + connectionConfig1.setConnectionUrl(""); connectionConfig1.setCredentials(credentials); ConnectionConfig connectionConfig2 = new ConnectionConfig(); - connectionConfig2.setConnectionId(""); - connectionConfig2.setConnectionUrl(""); + connectionConfig2.setConnectionId(""); + connectionConfig2.setConnectionUrl(""); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + skyflowCredentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) @@ -37,11 +37,11 @@ public static void main(String[] args) throws SkyflowException { .build(); Map requestBody = new HashMap<>(); - requestBody.put("", ""); - requestBody.put("", ""); + requestBody.put("", ""); + requestBody.put("", ""); Map requestHeaders = new HashMap<>(); - requestHeaders.put("", ""); - requestHeaders.put("", ""); + requestHeaders.put("", ""); + requestHeaders.put("", ""); InvokeConnectionRequest invokeConnectionRequest1 = InvokeConnectionRequest.builder() .methodName(RequestMethod.POST) .requestBody(requestBody) @@ -51,18 +51,18 @@ public static void main(String[] args) throws SkyflowException { System.out.println(invokeConnectionResponse1); Map pathParams = new HashMap<>(); - pathParams.put("", ""); - pathParams.put("", ""); + pathParams.put("", ""); + pathParams.put("", ""); Map queryParams = new HashMap<>(); - queryParams.put("", ""); - queryParams.put("", ""); + queryParams.put("", ""); + queryParams.put("", ""); InvokeConnectionRequest invokeConnectionRequest2 = InvokeConnectionRequest.builder() .methodName(RequestMethod.GET) .pathParams(pathParams) .queryParams(queryParams) .build(); InvokeConnectionResponse invokeConnectionResponse2 = skyflowClient - .connection("").invoke(invokeConnectionRequest2); + .connection("").invoke(invokeConnectionRequest2); System.out.println(invokeConnectionResponse2); } } diff --git a/samples/src/main/java/com/example/vault/DeleteExample.java b/samples/src/main/java/com/example/vault/DeleteExample.java index 17887204..d14554ce 100644 --- a/samples/src/main/java/com/example/vault/DeleteExample.java +++ b/samples/src/main/java/com/example/vault/DeleteExample.java @@ -28,7 +28,7 @@ public static void main(String[] args) throws SkyflowException { stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + skyflowCredentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) @@ -38,15 +38,15 @@ public static void main(String[] args) throws SkyflowException { .build(); ArrayList ids1 = new ArrayList<>(); - ids1.add(""); - DeleteRequest deleteRequest1 = DeleteRequest.builder().ids(ids1).table("").build(); + ids1.add(""); + DeleteRequest deleteRequest1 = DeleteRequest.builder().ids(ids1).table("").build(); DeleteResponse deleteResponse1 = skyflowClient.vault().delete(deleteRequest1); System.out.println(deleteResponse1); ArrayList ids2 = new ArrayList<>(); - ids2.add(""); - DeleteRequest deleteRequest2 = DeleteRequest.builder().ids(ids2).table("").build(); - DeleteResponse deleteResponse2 = skyflowClient.vault("").delete(deleteRequest2); + ids2.add(""); + DeleteRequest deleteRequest2 = DeleteRequest.builder().ids(ids2).table("").build(); + DeleteResponse deleteResponse2 = skyflowClient.vault("").delete(deleteRequest2); System.out.println(deleteResponse2); } } diff --git a/samples/src/main/java/com/example/vault/DetokenizeExample.java b/samples/src/main/java/com/example/vault/DetokenizeExample.java index f026e43e..cd6d38ad 100644 --- a/samples/src/main/java/com/example/vault/DetokenizeExample.java +++ b/samples/src/main/java/com/example/vault/DetokenizeExample.java @@ -29,7 +29,7 @@ public static void main(String[] args) throws SkyflowException { stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + skyflowCredentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) @@ -39,19 +39,19 @@ public static void main(String[] args) throws SkyflowException { .build(); ArrayList tokens1 = new ArrayList<>(); - tokens1.add(""); - tokens1.add(""); + tokens1.add(""); + tokens1.add(""); DetokenizeRequest detokenizeRequest1 = DetokenizeRequest.builder().tokens(tokens1).continueOnError(true).build(); DetokenizeResponse detokenizeResponse1 = skyflowClient.vault().detokenize(detokenizeRequest1); System.out.println(detokenizeResponse1); ArrayList tokens2 = new ArrayList<>(); - tokens2.add(""); - tokens2.add(""); + tokens2.add(""); + tokens2.add(""); DetokenizeRequest detokenizeRequest2 = DetokenizeRequest.builder() .tokens(tokens2).continueOnError(false).redactionType(RedactionType.DEFAULT).build(); - DetokenizeResponse detokenizeResponse2 = skyflowClient.vault("").detokenize(detokenizeRequest2); + DetokenizeResponse detokenizeResponse2 = skyflowClient.vault("").detokenize(detokenizeRequest2); System.out.println(detokenizeResponse2); } } diff --git a/samples/src/main/java/com/example/vault/GetExample.java b/samples/src/main/java/com/example/vault/GetExample.java index 357c3516..5dda25d3 100644 --- a/samples/src/main/java/com/example/vault/GetExample.java +++ b/samples/src/main/java/com/example/vault/GetExample.java @@ -29,7 +29,7 @@ public static void main(String[] args) throws SkyflowException { stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + skyflowCredentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) @@ -39,20 +39,20 @@ public static void main(String[] args) throws SkyflowException { .build(); ArrayList ids = new ArrayList<>(); - ids.add(""); - GetRequest getByIdRequest = GetRequest.builder().returnTokens(true).ids(ids).table("").build(); + ids.add(""); + GetRequest getByIdRequest = GetRequest.builder().returnTokens(true).ids(ids).table("").build(); GetResponse getByIdResponse = skyflowClient.vault().get(getByIdRequest); System.out.println(getByIdResponse); ArrayList columnValues = new ArrayList<>(); - columnValues.add(""); + columnValues.add(""); GetRequest getByColumnRequest = GetRequest.builder() - .table("") - .columnName("") + .table("") + .columnName("") .columnValues(columnValues) .redactionType(RedactionType.PLAIN_TEXT) .build(); - GetResponse getByColumnResponse = skyflowClient.vault("").get(getByColumnRequest); + GetResponse getByColumnResponse = skyflowClient.vault("").get(getByColumnRequest); System.out.println(getByColumnResponse); } } diff --git a/samples/src/main/java/com/example/vault/InsertExample.java b/samples/src/main/java/com/example/vault/InsertExample.java index 21d9260b..20070e83 100644 --- a/samples/src/main/java/com/example/vault/InsertExample.java +++ b/samples/src/main/java/com/example/vault/InsertExample.java @@ -30,7 +30,7 @@ public static void main(String[] args) throws SkyflowException { stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + skyflowCredentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) @@ -41,17 +41,17 @@ public static void main(String[] args) throws SkyflowException { ArrayList> values1 = new ArrayList<>(); HashMap value1 = new HashMap<>(); - value1.put("", ""); - value1.put("", ""); + value1.put("", ""); + value1.put("", ""); values1.add(value1); ArrayList> tokens = new ArrayList<>(); HashMap token = new HashMap<>(); - token.put("", ""); + token.put("", ""); tokens.add(token); InsertRequest insertRequest = InsertRequest.builder() - .table("") + .table("") .continueOnError(true) .tokenStrict(Byot.ENABLE) .values(values1) @@ -63,19 +63,19 @@ public static void main(String[] args) throws SkyflowException { ArrayList> values2 = new ArrayList<>(); HashMap value2 = new HashMap<>(); - value2.put("", ""); - value2.put("", ""); + value2.put("", ""); + value2.put("", ""); values2.add(value2); InsertRequest upsertRequest = InsertRequest.builder() - .table("") + .table("") .continueOnError(false) .tokenStrict(Byot.DISABLE) .values(values2) .returnTokens(false) - .upsert("") + .upsert("") .build(); - InsertResponse upsertResponse = skyflowClient.vault("").insert(upsertRequest); + InsertResponse upsertResponse = skyflowClient.vault("").insert(upsertRequest); System.out.println(upsertResponse); } } diff --git a/samples/src/main/java/com/example/vault/QueryExample.java b/samples/src/main/java/com/example/vault/QueryExample.java index c80a2443..d5928cd5 100644 --- a/samples/src/main/java/com/example/vault/QueryExample.java +++ b/samples/src/main/java/com/example/vault/QueryExample.java @@ -26,7 +26,7 @@ public static void main(String[] args) throws SkyflowException { stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + skyflowCredentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) @@ -35,14 +35,14 @@ public static void main(String[] args) throws SkyflowException { .addSkyflowCredentials(skyflowCredentials) .build(); - String query1 = ""; + String query1 = ""; QueryRequest queryRequest1 = QueryRequest.builder().query(query1).build(); QueryResponse queryResponse1 = skyflowClient.vault().query(queryRequest1); System.out.println(queryResponse1); - String query2 = ""; + String query2 = ""; QueryRequest queryRequest2 = QueryRequest.builder().query(query2).build(); - QueryResponse queryResponse2 = skyflowClient.vault("").query(queryRequest2); + QueryResponse queryResponse2 = skyflowClient.vault("").query(queryRequest2); System.out.println(queryResponse2); } diff --git a/samples/src/main/java/com/example/vault/TokenizeExample.java b/samples/src/main/java/com/example/vault/TokenizeExample.java index f7677670..e7db6fb2 100644 --- a/samples/src/main/java/com/example/vault/TokenizeExample.java +++ b/samples/src/main/java/com/example/vault/TokenizeExample.java @@ -30,7 +30,7 @@ public static void main(String[] args) throws SkyflowException { stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + skyflowCredentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) @@ -40,8 +40,8 @@ public static void main(String[] args) throws SkyflowException { .build(); List columnValues1 = new ArrayList<>(); - ColumnValue value1 = ColumnValue.builder().value("").columnGroup("").build(); - ColumnValue value2 = ColumnValue.builder().value("").columnGroup("").build(); + ColumnValue value1 = ColumnValue.builder().value("").columnGroup("").build(); + ColumnValue value2 = ColumnValue.builder().value("").columnGroup("").build(); columnValues1.add(value1); columnValues1.add(value2); TokenizeRequest tokenizeRequest1 = TokenizeRequest.builder().values(columnValues1).build(); @@ -49,12 +49,12 @@ public static void main(String[] args) throws SkyflowException { System.out.println(tokenizeResponse1); List columnValues2 = new ArrayList<>(); - ColumnValue value3 = ColumnValue.builder().value("").columnGroup("").build(); - ColumnValue value4 = ColumnValue.builder().value("").columnGroup("").build(); + ColumnValue value3 = ColumnValue.builder().value("").columnGroup("").build(); + ColumnValue value4 = ColumnValue.builder().value("").columnGroup("").build(); columnValues2.add(value3); columnValues2.add(value4); TokenizeRequest tokenizeRequest2 = TokenizeRequest.builder().values(columnValues2).build(); - TokenizeResponse tokenizeResponse2 = skyflowClient.vault("").tokenize(tokenizeRequest2); + TokenizeResponse tokenizeResponse2 = skyflowClient.vault("").tokenize(tokenizeRequest2); System.out.println(tokenizeResponse2); } } diff --git a/samples/src/main/java/com/example/vault/UpdateExample.java b/samples/src/main/java/com/example/vault/UpdateExample.java index b782d80d..1508fc25 100644 --- a/samples/src/main/java/com/example/vault/UpdateExample.java +++ b/samples/src/main/java/com/example/vault/UpdateExample.java @@ -29,7 +29,7 @@ public static void main(String[] args) throws SkyflowException { stageConfig.setEnv(Env.STAGE); Credentials skyflowCredentials = new Credentials(); - credentials.setPath(""); + skyflowCredentials.setPath(""); Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.DEBUG) @@ -39,15 +39,15 @@ public static void main(String[] args) throws SkyflowException { .build(); HashMap values1 = new HashMap<>(); - values1.put("", ""); - values1.put("", ""); + values1.put("", ""); + values1.put("", ""); HashMap tokens = new HashMap<>(); - tokens.put("", ""); + tokens.put("", ""); UpdateRequest updateRequest1 = UpdateRequest.builder() - .id("") + .id("") + .table("") .tokenStrict(Byot.ENABLE) .values(values1) .tokens(tokens) @@ -57,17 +57,17 @@ public static void main(String[] args) throws SkyflowException { System.out.println(updateResponse1); HashMap values2 = new HashMap<>(); - values2.put("", ""); - values2.put("", ""); + values2.put("", ""); + values2.put("", ""); UpdateRequest updateRequest2 = UpdateRequest.builder() - .id("") + .id("") + .table("") .tokenStrict(Byot.DISABLE) .values(values2) .returnTokens(false) .build(); - UpdateResponse updateResponse2 = skyflowClient.vault("").update(updateRequest2); + UpdateResponse updateResponse2 = skyflowClient.vault("").update(updateRequest2); System.out.println(updateResponse2); } } From b4f2015c2bfcc6856033afdc178ca2dc9eb56d55 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 22 Nov 2024 18:59:20 +0530 Subject: [PATCH 066/126] SK-1623 Worked on feedback for Update vault API interface --- src/main/java/com/skyflow/VaultClient.java | 2 +- .../java/com/skyflow/errors/ErrorMessage.java | 7 +- src/main/java/com/skyflow/logs/ErrorLogs.java | 3 + .../utils/validations/Validations.java | 42 +++--- .../vault/controller/VaultController.java | 2 +- .../com/skyflow/vault/data/UpdateRequest.java | 20 +-- .../skyflow/vault/data/UpdateResponse.java | 12 +- .../com/skyflow/vault/data/UpdateTests.java | 135 +++++++++++------- 8 files changed, 122 insertions(+), 101 deletions(-) diff --git a/src/main/java/com/skyflow/VaultClient.java b/src/main/java/com/skyflow/VaultClient.java index 08c161de..a6a63f64 100644 --- a/src/main/java/com/skyflow/VaultClient.java +++ b/src/main/java/com/skyflow/VaultClient.java @@ -144,7 +144,7 @@ protected RecordServiceUpdateRecordBody getUpdateRequestBody(UpdateRequest reque RecordServiceUpdateRecordBody updateRequestBody = new RecordServiceUpdateRecordBody(); updateRequestBody.byot(request.getTokenStrict().getBYOT()); updateRequestBody.setTokenization(request.getReturnTokens()); - HashMap values = request.getValues(); + HashMap values = request.getData(); HashMap tokens = request.getTokens(); V1FieldRecords record = new V1FieldRecords(); record.setFields(values); diff --git a/src/main/java/com/skyflow/errors/ErrorMessage.java b/src/main/java/com/skyflow/errors/ErrorMessage.java index 31648fb8..ac5fd0cf 100644 --- a/src/main/java/com/skyflow/errors/ErrorMessage.java +++ b/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -100,8 +100,11 @@ public enum ErrorMessage { PartialSuccess("%s0 Validation error. Check 'SkyflowError.data' for details."), // update - SkyflowIdKeyError("%s0 Validation error. 'id' key is missing from the payload. Specify an 'id' key."), - EmptySkyflowId("%s0 Validation error. 'id' can't be empty. Specify an id."), + DataKeyError("%s0 Validation error. 'data' key is missing from the payload. Specify a 'data' key."), + EmptyData("%s0 Validation error. 'data' can't be empty. Specify data."), + SkyflowIdKeyError("%s0 Validation error. 'skyflow_id' is missing from the data payload. Specify a 'skyflow_id'."), + InvalidSkyflowIdType("%s0 Validation error. Invalid type for 'skyflow_id' in data payload. Specify 'skyflow_id' as a string."), + EmptySkyflowId("%s0 Validation error. 'skyflow_id' can't be empty. Specify a skyflow id."), // query QueryKeyError("%s0 Validation error. 'query' key is missing from the payload. Specify a 'query' key."), diff --git a/src/main/java/com/skyflow/logs/ErrorLogs.java b/src/main/java/com/skyflow/logs/ErrorLogs.java index 98bc3064..ad32b886 100644 --- a/src/main/java/com/skyflow/logs/ErrorLogs.java +++ b/src/main/java/com/skyflow/logs/ErrorLogs.java @@ -82,7 +82,10 @@ public enum ErrorLogs { EMPTY_COLUMN_VALUES("Invalid %s1 request. Column values can not be empty."), EMPTY_OR_NULL_COLUMN_VALUE_IN_COLUMN_VALUES("Invalid %s1 request. Column value can not by null or empty in column values at index %s2."), GET_REQUEST_REJECTED("Get request resulted in failure."), + DATA_IS_REQUIRED("Invalid %s1 request. Data is required."), + EMPTY_DATA("Invalid %s1 request. Data can not be empty."), SKYFLOW_ID_IS_REQUIRED("Invalid %s1 request. Skyflow Id is required."), + INVALID_SKYFLOW_ID_TYPE("Invalid %s1 request. Skyflow Id should of type String."), EMPTY_SKYFLOW_ID("Invalid %s1 request. Skyflow Id can not be empty."), UPDATE_REQUEST_REJECTED("Update request resulted in failure."), QUERY_IS_REQUIRED("Invalid %s1 request. Query is required."), diff --git a/src/main/java/com/skyflow/utils/validations/Validations.java b/src/main/java/com/skyflow/utils/validations/Validations.java index 5e88ec1b..77f6b823 100644 --- a/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/src/main/java/com/skyflow/utils/validations/Validations.java @@ -486,8 +486,7 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep public static void validateUpdateRequest(UpdateRequest updateRequest) throws SkyflowException { String table = updateRequest.getTable(); - String skyflowId = updateRequest.getId(); - HashMap values = updateRequest.getValues(); + HashMap data = updateRequest.getData(); HashMap tokens = updateRequest.getTokens(); Byot tokenStrict = updateRequest.getTokenStrict(); @@ -501,26 +500,31 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky ErrorLogs.EMPTY_TABLE_NAME.getLog(), InterfaceName.UPDATE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); - } else if (skyflowId == null) { + } else if (data == null) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.SKYFLOW_ID_IS_REQUIRED.getLog(), InterfaceName.UPDATE.getName() + ErrorLogs.DATA_IS_REQUIRED.getLog(), InterfaceName.UPDATE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.SkyflowIdKeyError.getMessage()); - } else if (skyflowId.trim().isEmpty()) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.DataKeyError.getMessage()); + } else if (data.isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.EMPTY_SKYFLOW_ID.getLog(), InterfaceName.UPDATE.getName() + ErrorLogs.EMPTY_DATA.getLog(), InterfaceName.UPDATE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptySkyflowId.getMessage()); - } else if (values == null) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyData.getMessage()); + } else if (!data.containsKey("skyflow_id")) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.VALUES_IS_REQUIRED.getLog(), InterfaceName.UPDATE.getName() + ErrorLogs.SKYFLOW_ID_IS_REQUIRED.getLog(), InterfaceName.UPDATE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ValuesKeyError.getMessage()); - } else if (values.isEmpty()) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.SkyflowIdKeyError.getMessage()); + } else if (!(data.get("skyflow_id") instanceof String)) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.EMPTY_VALUES.getLog(), InterfaceName.UPDATE.getName() + ErrorLogs.INVALID_SKYFLOW_ID_TYPE.getLog(), InterfaceName.UPDATE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyValues.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidSkyflowIdType.getMessage()); + } else if (data.get("skyflow_id").toString().trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_SKYFLOW_ID.getLog(), InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptySkyflowId.getMessage()); } else if (tokens != null && tokens.isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_TOKENS.getLog(), InterfaceName.UPDATE.getName() @@ -528,14 +532,14 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTokens.getMessage()); } - for (String key : values.keySet()) { + for (String key : data.keySet()) { if (key == null || key.trim().isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_KEY_IN_VALUES.getLog(), InterfaceName.UPDATE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyKeyInValues.getMessage()); } else { - Object value = values.get(key); + Object value = data.get(key); if (value == null || value.toString().trim().isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_VALUE_IN_VALUES.getLog(), InterfaceName.UPDATE.getName(), key @@ -565,7 +569,7 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE.toString())); } - validateTokensMapWithTokenStrict(tokens, values); + validateTokensMapWithTokenStrict(tokens, data); break; case ENABLE_STRICT: if (tokens == null) { @@ -575,7 +579,7 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString())); - } else if (tokens.size() != values.size()) { + } else if (tokens.size() != (data.size() - 1)) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_BYOT_ENABLE_STRICT.getLog(), InterfaceName.INSERT.getName() @@ -583,7 +587,7 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage()); } - validateTokensMapWithTokenStrict(tokens, values); + validateTokensMapWithTokenStrict(tokens, data); break; } } diff --git a/src/main/java/com/skyflow/vault/controller/VaultController.java b/src/main/java/com/skyflow/vault/controller/VaultController.java index 3a3bc03f..2c211687 100644 --- a/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -273,7 +273,7 @@ public UpdateResponse update(UpdateRequest updateRequest) throws SkyflowExceptio result = super.getRecordsApi().recordServiceUpdateRecord( super.getVaultConfig().getVaultId(), updateRequest.getTable(), - updateRequest.getId(), + updateRequest.getData().get("skyflow_id").toString(), updateBody ); LogUtil.printInfoLog(InfoLogs.UPDATE_REQUEST_RESOLVED.getLog()); diff --git a/src/main/java/com/skyflow/vault/data/UpdateRequest.java b/src/main/java/com/skyflow/vault/data/UpdateRequest.java index 78abcd20..58e075ac 100644 --- a/src/main/java/com/skyflow/vault/data/UpdateRequest.java +++ b/src/main/java/com/skyflow/vault/data/UpdateRequest.java @@ -19,16 +19,12 @@ public String getTable() { return this.builder.table; } - public String getId() { - return this.builder.id; - } - public Boolean getReturnTokens() { return this.builder.returnTokens; } - public HashMap getValues() { - return this.builder.values; + public HashMap getData() { + return this.builder.data; } public HashMap getTokens() { @@ -41,9 +37,8 @@ public Byot getTokenStrict() { public static final class UpdateRequestBuilder { private String table; - private String id; private Boolean returnTokens; - private HashMap values; + private HashMap data; private HashMap tokens; private Byot tokenStrict; @@ -57,18 +52,13 @@ public UpdateRequestBuilder table(String table) { return this; } - public UpdateRequestBuilder id(String id) { - this.id = id; - return this; - } - public UpdateRequestBuilder returnTokens(Boolean returnTokens) { this.returnTokens = returnTokens == null || returnTokens; return this; } - public UpdateRequestBuilder values(HashMap values) { - this.values = values; + public UpdateRequestBuilder data(HashMap data) { + this.data = data; return this; } diff --git a/src/main/java/com/skyflow/vault/data/UpdateResponse.java b/src/main/java/com/skyflow/vault/data/UpdateResponse.java index 2ca52365..4567e2e1 100644 --- a/src/main/java/com/skyflow/vault/data/UpdateResponse.java +++ b/src/main/java/com/skyflow/vault/data/UpdateResponse.java @@ -24,23 +24,17 @@ public String toString() { StringBuilder response = new StringBuilder("{"); response.append("\n\t\"skyflowId\": \"").append(skyflowId).append("\""); if (!tokens.isEmpty()) { - response.append("\n\t\"tokens\": ").append(formatRecords(tokens)); + response.append(formatTokens(tokens)); } response.append("\n}"); return response.toString(); } - private String formatRecords(HashMap tokens) { + private String formatTokens(HashMap tokens) { StringBuilder sb = new StringBuilder(); - sb.append("{"); for (String key : tokens.keySet()) { sb.append("\n\t\"").append(key).append("\": \"").append(tokens.get(key)).append("\","); } - sb.append("\n}"); - return toIndentedString(sb); - } - - private String toIndentedString(Object o) { - return o.toString().replace("\n", "\n\t"); + return sb.toString(); } } diff --git a/src/test/java/com/skyflow/vault/data/UpdateTests.java b/src/test/java/com/skyflow/vault/data/UpdateTests.java index b82a0734..d323dcee 100644 --- a/src/test/java/com/skyflow/vault/data/UpdateTests.java +++ b/src/test/java/com/skyflow/vault/data/UpdateTests.java @@ -32,7 +32,7 @@ public class UpdateTests { private static String clusterID = null; private static String skyflowID = null; private static String table = null; - private static HashMap valueMap = null; + private static HashMap dataMap = null; private static HashMap tokenMap = null; private static Skyflow skyflowClient = null; @@ -56,34 +56,33 @@ public static void setup() throws SkyflowException { skyflowID = "test_update_id_1"; table = "test_table"; - valueMap = new HashMap<>(); + dataMap = new HashMap<>(); tokenMap = new HashMap<>(); } @Before public void setupTest() { - valueMap.clear(); + dataMap.clear(); tokenMap.clear(); } @Test public void testValidInputInUpdateRequestValidations() { try { - valueMap.put("test_column_1", "test_value_1"); - valueMap.put("test_column_2", "test_value_2"); + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); tokenMap.put("test_column_1", "test_token_1"); UpdateRequest request = UpdateRequest.builder() - .id(skyflowID) .table(table) - .values(valueMap) + .data(dataMap) .tokens(tokenMap) .returnTokens(true) .tokenStrict(Byot.ENABLE) .build(); Validations.validateUpdateRequest(request); Assert.assertEquals(table, request.getTable()); - Assert.assertEquals(skyflowID, request.getId()); - Assert.assertEquals(2, request.getValues().size()); + Assert.assertEquals(3, request.getData().size()); Assert.assertEquals(1, request.getTokens().size()); Assert.assertTrue(request.getReturnTokens()); } catch (SkyflowException e) { @@ -93,7 +92,8 @@ public void testValidInputInUpdateRequestValidations() { @Test public void testNoSkyflowIdInUpdateRequestValidations() { - UpdateRequest request = UpdateRequest.builder().table(table).build(); + dataMap.put("test_column_1", "test_value_1"); + UpdateRequest request = UpdateRequest.builder().table(table).data(dataMap).build(); try { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); @@ -106,9 +106,26 @@ public void testNoSkyflowIdInUpdateRequestValidations() { } } + @Test + public void testInvalidSkyflowIdTypeInUpdateRequestValidations() { + dataMap.put("skyflow_id", 123); + UpdateRequest request = UpdateRequest.builder().table(table).data(dataMap).build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.InvalidSkyflowIdType.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + @Test public void testEmptySkyflowIdInUpdateRequestValidations() { - UpdateRequest request = UpdateRequest.builder().id("").table(table).build(); + dataMap.put("skyflow_id", ""); + UpdateRequest request = UpdateRequest.builder().table(table).data(dataMap).build(); try { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); @@ -123,7 +140,7 @@ public void testEmptySkyflowIdInUpdateRequestValidations() { @Test public void testNoTableInUpdateRequestValidations() { - UpdateRequest request = UpdateRequest.builder().id(skyflowID).build(); + UpdateRequest request = UpdateRequest.builder().build(); try { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); @@ -138,7 +155,7 @@ public void testNoTableInUpdateRequestValidations() { @Test public void testEmptyTableInUpdateRequestValidations() { - UpdateRequest request = UpdateRequest.builder().id(skyflowID).table("").build(); + UpdateRequest request = UpdateRequest.builder().table("").build(); try { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); @@ -153,14 +170,14 @@ public void testEmptyTableInUpdateRequestValidations() { @Test public void testNoValuesInUpdateRequestValidations() { - UpdateRequest request = UpdateRequest.builder().id(skyflowID).table(table).build(); + UpdateRequest request = UpdateRequest.builder().table(table).build(); try { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.ValuesKeyError.getMessage(), Constants.SDK_PREFIX), + Utils.parameterizedString(ErrorMessage.DataKeyError.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); } @@ -168,14 +185,14 @@ public void testNoValuesInUpdateRequestValidations() { @Test public void testEmptyValuesInUpdateRequestValidations() { - UpdateRequest request = UpdateRequest.builder().id(skyflowID).table(table).values(valueMap).build(); + UpdateRequest request = UpdateRequest.builder().table(table).data(dataMap).build(); try { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.EmptyValues.getMessage(), Constants.SDK_PREFIX), + Utils.parameterizedString(ErrorMessage.EmptyData.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); } @@ -183,10 +200,11 @@ public void testEmptyValuesInUpdateRequestValidations() { @Test public void testEmptyKeyInValuesInUpdateRequestValidations() { - valueMap.put("test_column_1", "test_value_1"); - valueMap.put("test_column_2", "test_value_2"); - valueMap.put("", "test_value_3"); - UpdateRequest request = UpdateRequest.builder().id(skyflowID).table(table).values(valueMap).build(); + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); + dataMap.put("", "test_value_3"); + UpdateRequest request = UpdateRequest.builder().table(table).data(dataMap).build(); try { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); @@ -201,10 +219,11 @@ public void testEmptyKeyInValuesInUpdateRequestValidations() { @Test public void testEmptyValueInValuesInUpdateRequestValidations() { - valueMap.put("test_column_1", "test_value_1"); - valueMap.put("test_column_2", "test_value_2"); - valueMap.put("test_column_3", ""); - UpdateRequest request = UpdateRequest.builder().id(skyflowID).table(table).values(valueMap).build(); + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); + dataMap.put("test_column_3", ""); + UpdateRequest request = UpdateRequest.builder().table(table).data(dataMap).build(); try { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); @@ -219,11 +238,12 @@ public void testEmptyValueInValuesInUpdateRequestValidations() { @Test public void testTokensWithTokenStrictDisableInUpdateRequestValidations() { - valueMap.put("test_column_1", "test_value_1"); - valueMap.put("test_column_2", "test_value_2"); + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); tokenMap.put("test_column_1", "test_token_1"); UpdateRequest request = UpdateRequest.builder() - .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.DISABLE) + .table(table).data(dataMap).tokens(tokenMap).tokenStrict(Byot.DISABLE) .build(); try { Validations.validateUpdateRequest(request); @@ -239,10 +259,11 @@ public void testTokensWithTokenStrictDisableInUpdateRequestValidations() { @Test public void testNoTokensWithTokenStrictEnableInUpdateRequestValidations() { - valueMap.put("test_column_1", "test_value_1"); - valueMap.put("test_column_2", "test_value_2"); + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); UpdateRequest request = UpdateRequest.builder() - .id(skyflowID).table(table).values(valueMap).tokenStrict(Byot.ENABLE) + .table(table).data(dataMap).tokenStrict(Byot.ENABLE) .build(); try { Validations.validateUpdateRequest(request); @@ -258,10 +279,11 @@ public void testNoTokensWithTokenStrictEnableInUpdateRequestValidations() { @Test public void testNoTokensWithTokenStrictEnableStrictInUpdateRequestValidations() { - valueMap.put("test_column_1", "test_value_1"); - valueMap.put("test_column_2", "test_value_2"); + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); UpdateRequest request = UpdateRequest.builder() - .id(skyflowID).table(table).values(valueMap).tokenStrict(Byot.ENABLE_STRICT) + .table(table).data(dataMap).tokenStrict(Byot.ENABLE_STRICT) .build(); try { Validations.validateUpdateRequest(request); @@ -277,10 +299,11 @@ public void testNoTokensWithTokenStrictEnableStrictInUpdateRequestValidations() @Test public void testEmptyTokensWithTokenStrictEnableInUpdateRequestValidations() { - valueMap.put("test_column_1", "test_value_1"); - valueMap.put("test_column_2", "test_value_2"); + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); UpdateRequest request = UpdateRequest.builder() - .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE) + .table(table).data(dataMap).tokens(tokenMap).tokenStrict(Byot.ENABLE) .build(); try { Validations.validateUpdateRequest(request); @@ -293,11 +316,12 @@ public void testEmptyTokensWithTokenStrictEnableInUpdateRequestValidations() { @Test public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestValidations() { - valueMap.put("test_column_1", "test_value_1"); - valueMap.put("test_column_2", "test_value_2"); + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); tokenMap.put("test_column_1", "test_token_1"); UpdateRequest request = UpdateRequest.builder() - .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) + .table(table).data(dataMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) .build(); try { Validations.validateUpdateRequest(request); @@ -310,12 +334,13 @@ public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestVali @Test public void testTokenValueMismatchInUpdateRequestValidations() { - valueMap.put("test_column_1", "test_value_1"); - valueMap.put("test_column_2", "test_value_2"); + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("test_column_3", "test_token_3"); UpdateRequest request = UpdateRequest.builder() - .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) + .table(table).data(dataMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) .build(); try { Validations.validateUpdateRequest(request); @@ -328,12 +353,13 @@ public void testTokenValueMismatchInUpdateRequestValidations() { @Test public void testEmptyKeyInTokensInUpdateRequestValidations() { - valueMap.put("test_column_1", "test_value_1"); - valueMap.put("test_column_2", "test_value_2"); + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("", "test_token_2"); UpdateRequest request = UpdateRequest.builder() - .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) + .table(table).data(dataMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) .build(); try { Validations.validateUpdateRequest(request); @@ -346,12 +372,13 @@ public void testEmptyKeyInTokensInUpdateRequestValidations() { @Test public void testEmptyValueInTokensInUpdateRequestValidations() { - valueMap.put("test_column_1", "test_value_1"); - valueMap.put("test_column_2", "test_value_2"); + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("test_column_2", ""); UpdateRequest request = UpdateRequest.builder() - .id(skyflowID).table(table).values(valueMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) + .table(table).data(dataMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) .build(); try { Validations.validateUpdateRequest(request); @@ -365,14 +392,14 @@ public void testEmptyValueInTokensInUpdateRequestValidations() { @Test public void testUpdateResponse() { try { - valueMap.put("test_column_1", "test_value_1"); - valueMap.put("test_column_2", "test_value_2"); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("test_column_2", "test_token_2"); UpdateResponse response = new UpdateResponse(skyflowID, tokenMap); - String responseString = "{\n\t\"skyflowId\": \"" + skyflowID + "\"\n\t\"tokens\": " - + "{\n\t\t\"test_column_1\": \"test_token_1\"," - + "\n\t\t\"test_column_2\": \"test_token_2\",\n\t}\n}"; + String responseString = "{\n\t\"skyflowId\": \"" + skyflowID + "\"" + + "\n\t\"test_column_1\": \"test_token_1\"," + + "\n\t\"test_column_2\": \"test_token_2\",\n}"; Assert.assertEquals(skyflowID, response.getSkyflowId()); Assert.assertEquals(2, response.getTokens().size()); Assert.assertEquals(responseString, response.toString()); From 42bec3b7052524a17e5255ce9c9ab287a3386a78 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 25 Nov 2024 11:19:11 +0530 Subject: [PATCH 067/126] SK-1633 Upgraded dependency version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 36544eb5..08afca20 100644 --- a/pom.xml +++ b/pom.xml @@ -85,7 +85,7 @@ io.jsonwebtoken jjwt - 0.9.1 + 0.12.6 jakarta.annotation From 1eb16d7666980df8312be6025e81fda360826064 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 25 Nov 2024 14:03:05 +0530 Subject: [PATCH 068/126] SK-1623 Made constructors for Bearer token utilities builders private --- .../serviceaccount/BearerTokenGenerationExample.java | 2 +- .../BearerTokenGenerationUsingThreadsExample.java | 4 ++-- .../BearerTokenGenerationWithContextExample.java | 6 +++--- .../serviceaccount/ScopedTokenGenerationExample.java | 6 +++--- .../serviceaccount/SignedTokenGenerationExample.java | 6 +++--- .../src/main/java/com/example/vault/TokenizeExample.java | 5 ++--- .../java/com/skyflow/serviceaccount/util/BearerToken.java | 3 +++ .../com/skyflow/serviceaccount/util/SignedDataTokens.java | 3 +++ 8 files changed, 20 insertions(+), 15 deletions(-) diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java index ae1bce1b..5dbd6372 100644 --- a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java @@ -18,7 +18,7 @@ public static void main(String[] args) { token = bearerToken.getBearerToken(); } System.out.println(token); - } catch (Exception e) { + } catch (SkyflowException e) { e.printStackTrace(); } diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java index 1d750ade..8cfba8fa 100644 --- a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java @@ -10,7 +10,7 @@ public static void main(String[] args) { // Generate BearerToken with context by specifying credentials.json file path try { String filePath = ""; - final BearerToken bearerToken = new BearerToken.BearerTokenBuilder() + final BearerToken bearerToken = BearerToken.builder() .setCredentials(new File(filePath)) .setCtx("abc") .build(); @@ -35,7 +35,7 @@ public static void main(String[] args) { // Generate BearerToken with context by specifying credentials.json as string try { String fileContents = ""; - final BearerToken bearerToken = new BearerToken.BearerTokenBuilder() + final BearerToken bearerToken = BearerToken.builder() .setCredentials(fileContents) .setCtx("abc") .build(); diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java index 69e6ff14..b85de6df 100644 --- a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java @@ -12,21 +12,21 @@ public static void main(String[] args) { // Generate BearerToken with context by specifying credentials.json file path try { String filePath = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() + BearerToken token = BearerToken.builder() .setCredentials(new File(filePath)) .setCtx("abc") .build(); bearerToken = token.getBearerToken(); System.out.println(bearerToken); - } catch (Exception e) { + } catch (SkyflowException e) { e.printStackTrace(); } // Generate BearerToken with context by specifying credentials.json as string try { String fileContents = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() + BearerToken token = BearerToken.builder() .setCredentials(fileContents) .setCtx("abc") .build(); diff --git a/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java b/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java index b8dfbc53..3fda1e07 100644 --- a/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java +++ b/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java @@ -15,14 +15,14 @@ public static void main(String[] args) { ArrayList roles = new ArrayList<>(); roles.add("YOUR_ROLE_ID"); String filePath = ""; - BearerToken bearerToken = new BearerToken.BearerTokenBuilder() + BearerToken bearerToken = BearerToken.builder() .setCredentials(new File(filePath)) .setRoles(roles) .build(); scopedToken = bearerToken.getBearerToken(); System.out.println(scopedToken); - } catch (Exception e) { + } catch (SkyflowException e) { e.printStackTrace(); } @@ -31,7 +31,7 @@ public static void main(String[] args) { ArrayList roles = new ArrayList<>(); roles.add("YOUR_ROLE_ID"); String fileContents = ""; - BearerToken bearerToken = new BearerToken.BearerTokenBuilder() + BearerToken bearerToken = BearerToken.builder() .setCredentials(fileContents) .setRoles(roles) .build(); diff --git a/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java b/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java index 7f030838..0acca5fe 100644 --- a/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java +++ b/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java @@ -18,7 +18,7 @@ public static void main(String[] args) { String context = "abc"; ArrayList dataTokens = new ArrayList<>(); dataTokens.add("YOUR_DATA_TOKEN_1"); - SignedDataTokens signedToken = new SignedDataTokens.SignedDataTokensBuilder() + SignedDataTokens signedToken = SignedDataTokens.builder() .setCredentials(new File(filePath)) .setCtx(context) .setTimeToLive(30) // in seconds @@ -27,7 +27,7 @@ public static void main(String[] args) { signedTokenValues = signedToken.getSignedDataTokens(); System.out.println(signedTokenValues); - } catch (Exception e) { + } catch (SkyflowException e) { e.printStackTrace(); } @@ -37,7 +37,7 @@ public static void main(String[] args) { String context = "abc"; ArrayList dataTokens = new ArrayList<>(); dataTokens.add("YOUR_DATA_TOKEN_1"); - SignedDataTokens signedToken = new SignedDataTokens.SignedDataTokensBuilder() + SignedDataTokens signedToken = SignedDataTokens.builder() .setCredentials(fileContents) .setCtx(context) .setTimeToLive(30) // in seconds diff --git a/samples/src/main/java/com/example/vault/TokenizeExample.java b/samples/src/main/java/com/example/vault/TokenizeExample.java index e7db6fb2..578e7ced 100644 --- a/samples/src/main/java/com/example/vault/TokenizeExample.java +++ b/samples/src/main/java/com/example/vault/TokenizeExample.java @@ -11,7 +11,6 @@ import com.skyflow.vault.tokens.TokenizeResponse; import java.util.ArrayList; -import java.util.List; public class TokenizeExample { public static void main(String[] args) throws SkyflowException { @@ -39,7 +38,7 @@ public static void main(String[] args) throws SkyflowException { .addSkyflowCredentials(skyflowCredentials) .build(); - List columnValues1 = new ArrayList<>(); + ArrayList columnValues1 = new ArrayList<>(); ColumnValue value1 = ColumnValue.builder().value("").columnGroup("").build(); ColumnValue value2 = ColumnValue.builder().value("").columnGroup("").build(); columnValues1.add(value1); @@ -48,7 +47,7 @@ public static void main(String[] args) throws SkyflowException { TokenizeResponse tokenizeResponse1 = skyflowClient.vault().tokenize(tokenizeRequest1); System.out.println(tokenizeResponse1); - List columnValues2 = new ArrayList<>(); + ArrayList columnValues2 = new ArrayList<>(); ColumnValue value3 = ColumnValue.builder().value("").columnGroup("").build(); ColumnValue value4 = ColumnValue.builder().value("").columnGroup("").build(); columnValues2.add(value3); diff --git a/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java b/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java index f235da49..da221458 100644 --- a/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java +++ b/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java @@ -194,6 +194,9 @@ public static class BearerTokenBuilder { private ArrayList roles; private String credentialsType; + private BearerTokenBuilder() { + } + private void setCredentialsType(String credentialsType) { this.credentialsType = credentialsType; } diff --git a/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java index 2f486c42..83fd0543 100644 --- a/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java +++ b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java @@ -172,6 +172,9 @@ public static class SignedDataTokensBuilder { private String ctx; private String credentialsType; + private SignedDataTokensBuilder() { + } + private void setCredentialsType(String credentialsType) { this.credentialsType = credentialsType; } From 92dde61951f5d03d4ed66ec4341cf0134a134395 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 25 Nov 2024 14:04:51 +0530 Subject: [PATCH 069/126] SK-1750 Rewrited README for SDK v2 --- README.md | 2149 ++++++++++++++++++++++++++++------------------------- 1 file changed, 1122 insertions(+), 1027 deletions(-) diff --git a/README.md b/README.md index 647e8fe5..eb623084 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # Skyflow Java + The Skyflow Java SDK is designed to help with integrating Skyflow into a Java backend. [![CI](https://img.shields.io/static/v1?label=CI&message=passing&color=green?style=plastic&logo=github)](https://github.com/skyflowapi/skyflow-java/actions) @@ -9,141 +10,165 @@ The Skyflow Java SDK is designed to help with integrating Skyflow into a Java ba - [Skyflow Java](#skyflow-java) - [Table of Contents](#table-of-contents) - - [Features](#features) - - [Installation](#installation) - - [Requirements](#requirements) - - [Configuration](#configuration) - - [Gradle users](#gradle-users) - - [Maven users](#maven-users) - - [Service Account Bearer Token Generation](#service-account-bearer-token-generation) - - [Service Account Bearer Token with Context Generation](#service-account-bearer-token-with-context-generation) - - [Service Account Scoped Bearer Token Generation](#service-account-scoped-bearer-token-generation) - - [Signed Data Tokens Generation](#signed-data-tokens-generation) - - [Vault APIs](#vault-apis) - - [Insert](#insert) - - [InsertBulk](#insertbulk) - - [Detokenize](#detokenize) - - [Get](#get) - - [Use Skyflow IDs](#use-skyflow-ids) - - [Use column name and values](#use-column-name-and-values) - - [Redaction types](#redaction-types) - - [Examples](#examples) - - [GetById](#getbyid) - - [Update](#update) - - [Delete](#delete) - - [Invoke Connection](#invoke-connection) - - [Query](#query) - - [Logging](#logging) - - [Reporting a Vulnerability](#reporting-a-vulnerability) + - [Features](#features) + - [Installation](#installation) + - [Requirements](#requirements) + - [Configuration](#configuration) + - [Gradle users](#gradle-users) + - [Maven users](#maven-users) + - [Service Account Bearer Token Generation](#service-account-bearer-token-generation) + - [Service Account Bearer Token with Context Generation](#service-account-bearer-token-with-context-generation) + - [Service Account Scoped Bearer Token Generation](#service-account-scoped-bearer-token-generation) + - [Signed Data Tokens Generation](#signed-data-tokens-generation) + - [Vault APIs](#vault-apis) + - [Insert](#insert-data-into-the-vault) + - [Detokenize](#detokenize) + - [Get](#get) + - [Use Skyflow IDs](#get-by-skyflow-ids) + - [Use column name and values](#get-by-column-name-and-column-values) + - [Redaction types](#redaction-types) + - [Update](#update) + - [Delete](#delete) + - [Query](#query) + - [Connections](#connections) + - [Invoke Connection](#invoke-connection) + - [Logging](#logging) + - [Reporting a Vulnerability](#reporting-a-vulnerability) ## Features -- Authenticate with a Skyflow service account and generate a bearer token. -- Insert, retrieve and tokenize sensitive data. -- Invoke connections to call downstream third party APIs without directly handling sensitive data. +- Authentication with a Skyflow Service Account and generation of a bearer token +- Vault API operations to insert, retrieve and tokenize sensitive data +- Invoking connections to call downstream third party APIs without directly handling sensitive data ## Installation ### Requirements + - Java 1.8 and above ### Configuration --- + #### Gradle users Add this dependency to your project's build file: + ``` -implementation 'com.skyflow:skyflow-java:1.15.0' +implementation 'com.skyflow:skyflow-java:2.0.0' ``` #### Maven users + Add this dependency to your project's POM: ```xml - - com.skyflow - skyflow-java - 1.15.0 - + + + com.skyflow + skyflow-java + 2.0.0 + ``` + --- ## Service Account Bearer Token Generation -The [Service Account](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/serviceaccount) java module is used to generate service account tokens from service account credentials file which is downloaded upon creation of service account. The token generated from this module is valid for 60 minutes and can be used to make API calls to vault services as well as management API(s) based on the permissions of the service account. -The `generateBearerToken(filepath)` function takes the credentials file path for token generation, alternatively, you can also send the entire credentials as string, by using `generateBearerTokenFromCreds(credentials)` +The [Service Account](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/serviceaccount/util) +java module is used to generate service account tokens from service account credentials file which is downloaded upon +creation of service account. The token generated from this module is valid for 60 minutes and can be used to make API +calls to vault services as well as management API(s) based on the permissions of the service account. + +The `BearerToken` utility class allows to generate bearer token with the help of credentials json file. Alternatively, +you can also send the entire credentials as a string. -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/TokenGenerationExample.java +[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java ): ```java - import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.BearerToken; import com.skyflow.serviceaccount.util.Token; -import com.skyflow.entities.ResponseToken; -public class TokenGenerationUtil { - - private static String bearerToken = null; +import java.io.File; - public static String getSkyflowBearerToken() { +public class BearerTokenGenerationExample { + public static void main(String[] args) { + String token = null; + // Generate BearerToken by specifying credentials.json file path try { String filePath = ""; - if(Token.isExpired(bearerToken)) { - ResponseToken response = Token.generateBearerToken(filePath); - // or Token.generateBearerTokenFromCreds(credentialsString) - bearerToken = response.getAccessToken(); + if (Token.isExpired(token)) { + BearerToken bearerToken = BearerToken.builder().setCredentials(new File(filePath)).build(); + token = bearerToken.getBearerToken(); } + System.out.println(token); } catch (SkyflowException e) { e.printStackTrace(); } - return bearerToken; + // Generate BearerToken by specifying credentials.json as string + try { + String fileContents = ""; + if (Token.isExpired(token)) { + BearerToken bearerToken = BearerToken.builder().setCredentials(fileContents).build(); + token = bearerToken.getBearerToken(); + } + System.out.println(token); + } catch (SkyflowException e) { + e.printStackTrace(); + } } } ``` -## Service Account Bearer Token with Context Generation +## Service Account Bearer Token with Context Generation -Context-Aware Authorization enables you to embed context values into a Bearer token when you generate it, and reference those values in your policies for more dynamic access control of data in the vault or validating signed data tokens during detokenization. It can be used to track end user identity when making API calls using service accounts. +Context-Aware Authorization enables you to embed context values into a Bearer token when you generate it, and reference +those values in your policies for more dynamic access control of data in the vault or validating signed data tokens +during detokenization. It can be used to track end user identity when making API calls using service accounts. -The service account generated with `context_id` identifier enabled can be used to generate bearer tokens with `context`, which is a `jwt` claim for a skyflow generated bearer token. The token generated from this service account will have a `context_identifier` claim and is valid for 60 minutes and can be used to make API calls to vault services as well as management API(s) based on the permissions of the service account. +The service account generated with `context_id` identifier enabled can be used to generate bearer tokens with `context`, +which is a `jwt` claim for a skyflow generated bearer token. The token generated from this service account will have a +`context_identifier` claim and is valid for 60 minutes and can be used to make API calls to vault services as well as +management API(s) based on the permissions of the service account. -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/BearerTokenWithContextGenerationExample.java): +[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java): ``` java -import com.skyflow.entities.ResponseToken; import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; +import com.skyflow.serviceaccount.util.BearerToken; + import java.io.File; -public class BearerTokenWithContextGeneration { - public static void main(String args[]) { +public class BearerTokenGenerationWithContextExample { + public static void main(String[] args) { String bearerToken = null; - // Generate a bearer token using a service account key file with a context value of "abc". + // Generate BearerToken with context by specifying credentials.json file path try { String filePath = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(filePath)) - .setContext("abc") - .build(); + BearerToken token = BearerToken.builder() + .setCredentials(new File(filePath)) + .setCtx("abc") + .build(); bearerToken = token.getBearerToken(); System.out.println(bearerToken); - } catch (Exception e) { + } catch (SkyflowException e) { e.printStackTrace(); } - // Generate a bearer token using a service account key string with a context value of "abc". + + // Generate BearerToken with context by specifying credentials.json as string try { String fileContents = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(fileContents) - .setContext("abc") - .build(); + BearerToken token = BearerToken.builder() + .setCredentials(fileContents) + .setCtx("abc") + .build(); bearerToken = token.getBearerToken(); System.out.println(bearerToken); - } catch (SkyflowException e) { e.printStackTrace(); } @@ -151,1230 +176,1300 @@ public class BearerTokenWithContextGeneration { } ``` -Note: -- You can pass either a service account key credentials file path or a service account key credentials as string to the `setCredentials` method of the BearerTokenBuilder class. -- If you pass both a file path and string to the `setCredentials` method, the last method used takes precedence. -- To generate multiple bearer tokens using a thread, see this [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/BearerTokenGenerationUsingThreadsExample.java) - ## Service Account Scoped Bearer Token Generation -A service account that has multiple roles can generate bearer tokens with access restricted to a specific role by providing the appropriate `roleID`. Generated bearer tokens are valid for 60 minutes and can only perform operations with the permissions associated with the specified role. +A service account that has multiple roles can generate bearer tokens with access restricted to a specific role by +providing the appropriate `roleID`. Generated bearer tokens are valid for 60 minutes and can only perform operations +with the permissions associated with the specified role. -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/ScopedTokenGenerationExample.java): +[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java): ```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.BearerToken; + import java.io.File; +import java.util.ArrayList; -public class ScopedTokenGeneration { - public static void main(String args[]) { +public class ScopedTokenGenerationExample { + public static void main(String[] args) { String scopedToken = null; - // Generate a bearer token using a service account file path scoped to a specific role. + // Generate Scoped Token by specifying credentials.json file path try { + ArrayList roles = new ArrayList<>(); + roles.add("ROLE_ID"); String filePath = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(filePath)) - .setRoles(new String[] { - "roleID" - }) - .build(); + BearerToken bearerToken = BearerToken.builder() + .setCredentials(new File(filePath)) + .setRoles(roles) + .build(); - scopedToken = token.getBearerToken(); + scopedToken = bearerToken.getBearerToken(); System.out.println(scopedToken); - } catch (Exception e) { + } catch (SkyflowException e) { e.printStackTrace(); } } } ``` -Note: -- You can pass either a service account key credentials file path or a service account key credentials as string to the `setCredentials` method of the BearerTokenBuilder class. + +Notes: + +- You can pass either a service account key credentials file path or a service account key credentials as string to the + `setCredentials` method of the BearerTokenBuilder class. - If you pass both a file path and string to the `setCredentials` method, the last method used takes precedence. -## Signed Data Tokens Generation +- To generate multiple bearer tokens using a thread, see + this [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java) -Skyflow generates data tokens when sensitive data is inserted into the vault. These data tokens can be digitally signed with the private key of the service account credentials, which adds an additional layer of protection. Signed tokens can be detokenized by passing the signed data token and a bearer token generated from service account credentials. The service account must have appropriate permissions and context to detokenize the signed data tokens. +## Signed Data Tokens Generation +Skyflow generates data tokens when sensitive data is inserted into the vault. These data tokens can be digitally signed +with the private key of the service account credentials, which adds an additional layer of protection. Signed tokens can +be detokenized by passing the signed data token and a bearer token generated from service account credentials. The +service account must have appropriate permissions and context to detokenize the signed data tokens. -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/SignedTokenGenerationExample.java): +[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java): ``` java import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.SignedDataTokenResponse; +import com.skyflow.serviceaccount.util.SignedDataTokens; + import java.io.File; +import java.util.ArrayList; import java.util.List; -public class SignedTokenGeneration { - public static void main(String args[]) { - List < SignedDataTokenResponse > signedTokenValue; - // Generate signed data tokens using a service account file path, context information, and a time to live. +public class SignedTokenGenerationExample { + public static void main(String[] args) { + List signedTokenValues; + // Generate Signed data token with context by specifying credentials.json file path try { String filePath = ""; String context = "abc"; - SignedDataTokens signedToken = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(new File(filePath)) - .setContext(context) - .setTimeToLive(30.0) // Time to live set in seconds. - .setDataTokens(new String[] { - "dataToken1" - }).build(); - - signedTokenValue = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValue); - } catch (Exception e) { + ArrayList dataTokens = new ArrayList<>(); + dataTokens.add("YOUR_DATA_TOKEN_1"); + SignedDataTokens signedToken = SignedDataTokens.builder() + .setCredentials(new File(filePath)) + .setCtx(context) + .setTimeToLive(30) // in seconds + .setDataTokens(dataTokens) + .build(); + signedTokenValues = signedToken.getSignedDataTokens(); + System.out.println(signedTokenValues); + } catch (SkyflowException e) { e.printStackTrace(); } - // Generate signed data tokens using a service account key string, context information, and a time to live. + + // Generate Signed data token with context by specifying credentials.json as string try { String fileContents = ""; String context = "abc"; - SignedDataTokens signedToken = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(fileContents) - .setContext(context) - .setTimeToLive(30.0) // Time to live set in seconds. - .setDataTokens(new String[] { - "dataToken1" - }).build(); - - signedTokenValue = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValue); - + ArrayList dataTokens = new ArrayList<>(); + dataTokens.add("YOUR_DATA_TOKEN_1"); + SignedDataTokens signedToken = SignedDataTokens.builder() + .setCredentials(fileContents) + .setCtx(context) + .setTimeToLive(30) // in seconds + .setDataTokens(dataTokens) + .build(); + signedTokenValues = signedToken.getSignedDataTokens(); + System.out.println(signedTokenValues); } catch (SkyflowException e) { e.printStackTrace(); } } } ``` + Response: ``` java [ { - "token":"5530-4316-0674-5748", - "signedToken":"signed_token_eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJzLCpZjA" + "dataToken":"5530-4316-0674-5748", + "signedDataToken":"signed_token_eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJzLCpZjA" } ] ``` -Note: -- You can pass either a service account key credentials file path or a service account key credentials as string to the `setCredentials` method of the SignedDataTokensBuilder class. + +Notes: + +- You can pass either a service account key credentials file path or a service account key credentials as string to the + `setCredentials` method of the SignedDataTokensBuilder class. - If you pass both a file path and string to the `setCredentials` method, the last method used takes precedence. - Time to live value expects time as seconds. - The default time to live value is 60 seconds. ## Vault APIs -The [Vault](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault) module is used to perform operations on the vault such as inserting records, detokenizing tokens, retrieving tokens for a skyflow_id and to invoke a connection. + +The [Vault](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault) module is used to +perform operations on the vault such as inserting records, detokenizing tokens and retrieving tokens for a skyflow_id. To use this module, the skyflow client must first be initialized as follows. + ```java -import com.skyflow.vault.Skyflow; -import com.skyflow.entities.SkyflowConfiguration; +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; -// DemoTokenProvider class is an implementation of the TokenProvider interface -DemoTokenProvider demoTokenProvider = new DemoTokenProvider(); +public class InitSkyflowClient { + public static void main(String[] args) throws SkyflowException { + // Pass only one of apiKey, token, credentialsString or path in credentials + Credentials credentials = new Credentials(); + credentials.setToken(""); + + VaultConfig config = new VaultConfig(); + config.setVaultId(""); // Primary vault + config.setClusterId(""); // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + config.setEnv(Env.PROD); // Env by default is set to PROD + config.setCredentials(credentials); // Individual credentials + + JsonObject credentialsObject = new JsonObject(); + credentialsObject.addProperty("clientID", ""); + credentialsObject.addProperty("clientName", ""); + credentialsObject.addProperty("TokenURI", ""); + credentialsObject.addProperty("keyID", ""); + credentialsObject.addProperty("privateKey", ""); + + // To generate Bearer Token from credentials string. + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(credentialsObject.toString()); + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.INFO) // Set log level. By default, it is set to ERROR + .addVaultConfig(config) // Add vault config + .addSkyflowCredentials(skyflowCredentials) // Skyflow credentials will be used if no individual credentials are passed + .build(); + } +} +``` -SkyflowConfiguration skyflowConfig = new SkyflowConfiguration(,,demoTokenProvider); +Notes: + +- If both Skyflow common credentials and individual credentials at the configuration level are provided, the individual + credentials at the configuration level will take priority. + +All Vault APIs must be invoked using a client instance. + +## Insert data into the vault + +To insert data into your vault, use the `insert` method. The `InsertRequest` class is used to create an insert request, +which contains the values to be inserted in the form of a list of records. Additionally, you can provide options in the +insert request, such as returning tokenized data, upserting records, and continuing on error. + +Insert call schema -Skyflow skyflowClient = Skyflow.init(skyflowConfig); -``` -Example implementation of DemoTokenProvider using credentials file path is as follows ```java -import com.skyflow.entities.TokenProvider; - -static class DemoTokenProvider implements TokenProvider { - - @Override - public String getBearerToken() throws Exception { - ResponseToken res = null; - try { - String filePath = ""; - res = Token.generateBearerToken(filePath); - } catch (SkyflowException e) { - e.printStackTrace(); - } - return res.getAccessToken(); +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.InsertResponse; + +import java.util.ArrayList; +import java.util.HashMap; + +public class InsertSchema { + public static void main(String[] args) { + try { + // Initialize skyflow client + ArrayList> insertData = new ArrayList<>(); + + HashMap insertRecord1 = new HashMap<>(); + insertRecord1.put("", ""); + insertRecord1.put("", ""); + + HashMap insertRecord2 = new HashMap<>(); + insertRecord2.put("", ""); + insertRecord2.put("", ""); + + insertData.add(insertRecord1); + insertData.add(insertRecord2); + + InsertRequest insertRequest = InsertRequest.builder().table("").values(insertData).build(); + InsertResponse insertResponse = skyflowClient.vault("").insert(); + System.out.println("Insert Response: " + insertResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); } } +} ``` -Example implementation of DemoTokenProvider using credentials file content is as follows +Insert +call [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/InsertExample.java) + ```java -import com.skyflow.entities.TokenProvider; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.InsertResponse; -static class DemoTokenProvider implements TokenProvider { - @Override - public String getBearerToken() throws Exception { - ResponseToken res = null; +import java.util.ArrayList; +import java.util.HashMap; + +public class InsertExample { + public static void main(String[] args) { try { - String filePath = ""; - res = Token.generateBearerTokenFromCreds(filePath); + // Initialize skyflow client + ArrayList> insertData = new ArrayList<>(); + HashMap insertRecord = new HashMap<>(); + insertRecord.put("card_number", "4111111111111111"); + insertRecord.put("cardholder_name", "john doe"); + insertData.add(insertRecord); + + InsertRequest insertRequest = InsertRequest.builder() + .table("table1") + .values(insertData) + .returnTokens(true) + .build(); + InsertResponse insertResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").insert(); + System.out.println("Insert Response: " + insertResponse); } catch (SkyflowException e) { - e.printStackTrace(); + System.out.println("Error occurred: "); + System.out.println(e); } - return res.getAccessToken(); } - return res.getAccessToken(); } ``` -All Vault APIs must be invoked using a client instance. - -## Insert +Skyflow returns tokens for the record you just inserted. -To insert data into your vault, use the **insert(JSONObject insertInput, InsertOptions options)** method. The first parameter `insertInput` is a JSON object that must have a `records` key and takes an array of records to insert into the vault as a value. The second parameter, `options` is an `InsertOptions` object that provides further options for your insert call, including **upsert** operations as shown below: -```java -import com.skyflow.entities.InsertOptions; -import com.skyflow.entities.UpsertOption; -// initialize Skyflow - -// construct insert input -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject record = new JSONObject(); -record.put("table", ""); - -JSONObject fields = new JSONObject(); -fields.put("", ""); -record.put("fields", fields); -recordsArray.add(record); -records.put("records", recordsArray); - -// Create an upsert option and insert it into the UpsertOption array. -UpsertOption[] upsertOptions = new UpsertOption[1]; -upsertOptions[0] = new UpsertOption( - '', // Table name. - '' // Unique column in the table. - ); -// Indicates whether or not tokens should be returned for the inserted data. Defaults to 'True' -InsertOptions insertOptions = new InsertOptions( - true, - upsertOptions - ); - +```js +Insert Response: { + "insertedFields": [{ + "card_number": "5484-7829-1702-9110", + "request_index": "0", + "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", + "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b", + }], + "errors": [] +} ``` -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/InsertWithUpsertExample.java) of insert call with upsert support -```java -JSONObject recordsJson = new JSONObject(); -JSONArray recordsArrayJson = new JSONArray(); - -JSONObject recordJson = new JSONObject(); -recordJson.put("table", "cards"); -JSONObject fieldsJson = new JSONObject(); -fields.put("cardNumber", "41111111111"); -fields.put("cvv","123"); +Insert call example with `continueOnError` option -recordJson.put("fields", fieldsJson); -recordsArrayJson.add(record); -recordsJson.put("records", recordsArrayJson); - -// Create an Uupsert option and insert it into the UpsertOptions array. -UpsertOption[] upsertOptions = new UpsertOption[1]; -upsertOptions[0] = new UpsertOption("cards", "cardNumber"); +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.InsertResponse; -// Pass Upsert options in the insert method options. -InsertOptions insertOptions = new InsertOptions(true, upsertOptions); +import java.util.ArrayList; +import java.util.HashMap; -try { - JSONObject insertResponse = skyflowClient.insert(records,insertOptions); - System.out.println(insertResponse); -} catch (SkyflowException exception) { - System.out.println(exception); +public class InsertExample { + public static void main(String[] args) { + try { + // Initialize skyflow client + ArrayList> insertData = new ArrayList<>(); + + HashMap insertRecord1 = new HashMap<>(); + insertRecord1.put("card_number", "4111111111111111"); + insertRecord1.put("cardholder_name", "john doe"); + + HashMap insertRecord2 = new HashMap<>(); + insertRecord2.put("card_numbe", "4111111111111111"); + insertRecord2.put("cardholder_name", "jane doe"); + + insertData.add(insertRecord1); + insertData.add(insertRecord2); + + InsertRequest insertRequest = InsertRequest.builder() + .table("table1") + .values(insertData) + .returnTokens(true) + .continueOnError(true) + .build(); + InsertResponse insertResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").insert(); + System.out.println("Insert Response: " + insertResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } } ``` -Sample insert Response + +Sample response: + ```js { - "records": [ - { - "table": "cards", - "fields": { - "skyflow_id": "16419435-aa63-4823-aae7-19c6a2d6a19f", - "cardNumber": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", - "cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5", - }, - } - ] + "insertedFields": [{ + "card_number": "5484-7829-1702-9110", + "request_index": "0", + "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", + "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b", + }], + "errors": [{ + "request_index": "1", + "error": "Insert failed. Column card_numbe is invalid. Specify a valid column.", + }] } ``` -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/InsertWithContinueOnErrorExample.java) of Insert call with `continueOnError` support: +Insert call example with `upsert` option + ```java -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject invalidRecord = new JSONObject(); -invalidRecord.put("table", "cards"); -JSONObject invalidRecordFields = new JSONObject(); -invalidRecordFields.put("namee", "john doe"); -invalidRecordFields.put("card_number", "4111111111111111"); -invalidRecordFields.put("cvv", "1125"); -invalidRecord.put("fields", invalidRecordFields); - -JSONObject validRecord = new JSONObject(); -validRecord.put("table", "cards"); -JSONObject validRecordFields = new JSONObject(); -validRecordFields.put("name", "jane doe"); -validRecordFields.put("card_number", "4111111111111111"); -validRecordFields.put("cvv", "1125"); -validRecord.put("fields", validRecordFields); - -recordsArray.add(invalidRecord); -recordsArray.add(validRecord); -records.put("records", recordsArray); - -try { - InsertOptions insertOptions = new InsertOptions(true, true); - JSONObject insertResponse = skyflowClient.insert(records, insertOptions); - System.out.println(insertResponse); -} catch (SkyflowException e) { - System.out.println(e); - e.printStackTrace(); +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.InsertResponse; + +import java.util.ArrayList; +import java.util.HashMap; + +public class InsertExample { + public static void main(String[] args) { + try { + // Initialize skyflow client + ArrayList> upsertData = new ArrayList<>(); + HashMap upsertRecord = new HashMap<>(); + upsertRecord.put("cardholder_name", "jane doe"); + upsertData.add(upsertRecord); + + InsertRequest insertRequest = InsertRequest.builder() + .table("table1") + .values(upsertData) + .returnTokens(true) + .upsert("cardholder_name") + .build(); + InsertResponse insertResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").insert(); + System.out.println("Insert Response: " + insertResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } } ``` -Sample Response: +Skyflow returns tokens, with `upsert` support, for the record you just inserted. + ```js { - "records": [ - { - "table": "cards", - "fields": { - "skyflow_id": "16419435-aa63-4823-aae7-19c6a2d6a19f", - "cardNumber": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", - "cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5", - "name": "245d3a0f-a2d3-443b-8a20-8c17de86e186", - }, - "request_index": 1, - } - ], - "errors": [ - { - "error": { - "code":400, - "description":"Invalid field present in JSON namee - requestId: 87fb2e32-6287-4e61-8304-9268df12bfe8", - "request_index": 0, - } - } - ] + "insertedFields": [{ + "skyflowId": "9fac9201-7b8a-4446-93f8-5244e1213bd1", + "cardholder_name": "73ce45ce-20fd-490e-9310-c1d4f603ee83" + }], + "errors": [] } ``` -## InsertBulk +## Detokenize -To insert data into your vault using Bulk operation, use the **insertBulk(JSONObject insertInput, InsertBulkOptions options)** method. The first parameter `insertInput` is a JSON object that must have a `records` key and takes an array of records to insert into the vault as a value. The second parameter, `options` is an `InsertOptions` object that provides further options for your insert call, including **upsert** operations as shown below: +To retrieve tokens from your vault, you can use the `detokenize` method. The `DetokenizeRequest` class requires a list +of detokenization data to be provided as input. Additionally, the redaction type and continue on error are optional +parameters. ```java -import com.skyflow.entities.InsertOptions; -import com.skyflow.entities.UpsertOption; -// initialize Skyflow - -// construct insert input -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject record = new JSONObject(); -record.put("table", ""); - -JSONObject fields = new JSONObject(); -fields.put("", ""); -record.put("fields", fields); -recordsArray.add(record); -records.put("records", recordsArray); - -// Create an upsert option and insert it into the UpsertOption array. -UpsertOption[] upsertOptions = new UpsertOption[1]; -upsertOptions[0] = new UpsertOption( - '', // Table name. - '' // Unique column in the table. - ); -// Indicates whether or not tokens should be returned for the inserted data. Defaults to 'True' -InsertBulkOptions insertOptions = new InsertBulkOptions( - true, - upsertOptions - ); -``` -An [example]() of insert call with upsert support: +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.DetokenizeResponse; -```java -JSONObject recordsJson = new JSONObject(); -JSONArray recordsArrayJson = new JSONArray(); +import java.util.ArrayList; -JSONObject recordJson = new JSONObject(); -recordJson.put("table", "cards"); +public class DetokenizeSchema { + public static void main(String[] args) { + try { + // Initialize skyflow client + ArrayList tokens = new ArrayList<>(); + tokens.add(""); + tokens.add(""); + tokens.add(""); + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .tokens(tokens) + .continueOnError(true) + .redactionType(RedactionType.PLAIN_TEXT) + .build(); + DetokenizeResponse detokenizeResponse = skyflowClient.vault("").detokenize(detokenizeRequest); + System.out.println(detokenizeResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } +} +``` + +Notes: -JSONObject fieldsJson = new JSONObject(); -fields.put("cardNumber", "41111111111"); -fields.put("cvv","123"); +- `redactionType` defaults to [`RedactionType.PLAIN_TEXT`](#redaction-types). +- `continueOnError` defaults to `true`. -recordJson.put("fields", fieldsJson); -recordsArrayJson.add(record); -recordsJson.put("records", recordsArrayJson); +An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/DetokenizeExample.java) +of a detokenize call: -// Create an Uupsert option and insert it into the UpsertOptions array. -UpsertOption[] upsertOptions = new UpsertOption[1]; -upsertOptions[0] = new UpsertOption("cards", "cardNumber"); +```java +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.DetokenizeResponse; -// Pass Upsert options in the insert method options. -InsertBulkOptions insertOptions = new InsertBulkOptions(true, upsertOptions); +import java.util.ArrayList; -try { - JSONObject insertResponse = skyflowClient.insertBulk(records,insertOptions); - System.out.println(insertResponse); -} catch (SkyflowException exception) { - System.out.println(exception); +public class DetokenizeExample { + public static void main(String[] args) { + try { + // Initialize skyflow client + ArrayList tokens = new ArrayList<>(); + tokens.add("9738-1683-0486-1480"); + tokens.add("6184-6357-8409-6668"); + tokens.add("4914-9088-2814-3840"); + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .tokens(tokens) + .continueOnError(false) + .redactionType(RedactionType.PLAIN_TEXT) + .build(); + DetokenizeResponse detokenizeResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").detokenize(detokenizeRequest); + System.out.println(detokenizeResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } } ``` -Sample insert Response + +Sample response: + ```js { - "records": [ - { - "table": "cards", - "fields": { - "skyflow_id": "16419435-aa63-4823-aae7-19c6a2d6a19f", - "cardNumber": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", - "cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5", - }, - } - ] + "detokenizedFields": [{ + "token": "9738-1683-0486-1480", + "value": "4111111111111115", + "type": "STRING", + }, { + "token": "6184-6357-8409-6668", + "value": "4111111111111119", + "type": "STRING", + }, { + "token": "4914-9088-2814-3840", + "value": "4111111111111118", + "type": "STRING", + }] + "errors": [] } + ``` -An [example]() of Insert using bulk call: +An example of a detokenize call with `continueOnError` option: + ```java -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject invalidRecord = new JSONObject(); -invalidRecord.put("table", "cards"); -JSONObject invalidRecordFields = new JSONObject(); -invalidRecordFields.put("namee", "john doe"); -invalidRecordFields.put("card_number", "4111111111111111"); -invalidRecordFields.put("cvv", "1125"); -invalidRecord.put("fields", invalidRecordFields); - -JSONObject validRecord = new JSONObject(); -validRecord.put("table", "cards"); -JSONObject validRecordFields = new JSONObject(); -validRecordFields.put("name", "jane doe"); -validRecordFields.put("card_number", "4111111111111111"); -validRecordFields.put("cvv", "1125"); -validRecord.put("fields", validRecordFields); - -recordsArray.add(invalidRecord); -recordsArray.add(validRecord); -records.put("records", recordsArray); - -try { - InsertBulkOptions insertOptions = new InsertBulkOptions(true); - JSONObject insertResponse = skyflowClient.insertBulk(records, insertOptions); - System.out.println(insertResponse); -} catch (SkyflowException e) { - System.out.println(e); - e.printStackTrace(); +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.DetokenizeResponse; + +import java.util.ArrayList; + +public class DetokenizeExample { + public static void main(String[] args) { + try { + // Initialize skyflow client + ArrayList tokens = new ArrayList<>(); + tokens.add("9738-1683-0486-1480"); + tokens.add("6184-6357-8409-6668"); + tokens.add("4914-9088-2814-384"); + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .tokens(tokens) + .continueOnError(true) + .redactionType(RedactionType.PLAIN_TEXT) + .build(); + DetokenizeResponse detokenizeResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").detokenize(detokenizeRequest); + System.out.println(detokenizeResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } } ``` -Sample Response: +Sample response: + ```js { - "records": [ - { - "table": "cards", - "fields": { - "skyflow_id": "16419435-aa63-4823-aae7-19c6a2d6a19f", - "cardNumber": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", - "cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5", - "name": "245d3a0f-a2d3-443b-8a20-8c17de86e186", - }, - "request_index": 1, - } - ], - "errors": [ - { - "error": { - "code":400, - "description":"Invalid field present in JSON namee - requestId: 87fb2e32-6287-4e61-8304-9268df12bfe8", - "request_index": 0, - } - } - ] + "detokenizedFields": [{ + "token": "9738-1683-0486-1480", + "value": "4111111111111115", + "type": "STRING", + }, { + "token": "6184-6357-8409-6668", + "value": "4111111111111119", + "type": "STRING", + }] + "errors": [{ + "token": "4914-9088-2814-384", + "error": "Token Not Found", + }] } ``` -## Detokenize +## Tokenize -To retrieve record data using tokens, use the **detokenize(JSONObject records)** method. TheJSONObject must have a `records` key that takes an JSON array of record objects to fetch: +To tokenize data, use the `tokenize` method. The `TokenizeRequest` class is utilized to create a tokenize request. In +this request, you specify the `values` parameter, which is a list of `ColumnValue`. Each `ColumnValue` contains two +properties: `value` and `columnGroup`. + +Tokenize Schema ```java -JSONObject recordsJson = new JSONObject(); +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.ColumnValue; +import com.skyflow.vault.tokens.TokenizeRequest; +import com.skyflow.vault.tokens.TokenizeResponse; + +import java.util.ArrayList; -JSONObject recordJson = new JSONObject(); -recordJson.put("token", ""); -recordJson.put("redaction", ); // Optional. Redaction to apply for retrieved data. E.g. RedactionType.DEFAULT.toString() +public class TokenizeSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + ArrayList columnValues = new ArrayList<>(); -JSONArray recordsArrayJson = new JSONArray(); -recordsArrayJson.put(recordJson); + ColumnValue columnValue1 = ColumnValue.builder().value("").columnGroup("").build(); + ColumnValue columnValue2 = ColumnValue.builder().value("").columnGroup("").build(); -recordsJson.put("records", recordsArrayJson); -``` + columnValues.add(columnValue1); + columnValues.add(columnValue2); -Note: `redaction` defaults to [`RedactionType.PLAIN_TEXT`](#redaction-types). + TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); + TokenizeResponse tokenizeResponse = skyflowClient.vault("").tokenize(tokenizeRequest); + System.out.println(tokenizeResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } +} +``` -The following [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/DetokenizeExample.java) code makes a detokenize call to reveal the masked value of a token: +An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/TokenizeExample.java) +of Tokenize call: ```java -JSONObject recordsJson = new JSONObject(); - -JSONObject validRecordJson = new JSONObject(); -validRecordJson.put("token", "45012507-f72b-4f5c-9bf9-86b133bae719"); -validRecordJson.put("redaction", RedactionType.MASKED.toString()); - -JSONObject invalidRecordJson = new JSONObject(); -invalidRecordJson.put("token","invalid-token"); - -JSONArray recordsArrayJson = new JSONArray(); -recordsArrayJson.put(validRecordJson); -recordsArrayJson.put(invalidRecordJson); - -recordsJson.put("records", recordsArrayJson); -try { - JSONObject detokenizeResponse = skyflowClient.detokenize(recordsJson); - System.out.println(detokenizeResponse); -} catch (SkyflowExeception exception) { - if (exception.getData() != null) - System.out.println(exception.getData()); - else - System.out.println(exception); +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.ColumnValue; +import com.skyflow.vault.tokens.TokenizeRequest; +import com.skyflow.vault.tokens.TokenizeResponse; + +import java.util.ArrayList; + +public class TokenizeSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + ArrayList columnValues = new ArrayList<>(); + ColumnValue columnValue = ColumnValue.builder().value("4111111111111111").columnGroup("card_number_cg").build(); + columnValues.add(columnValue); + + TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); + TokenizeResponse tokenizeResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").tokenize(tokenizeRequest); + System.out.println(tokenizeResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } } ``` -The sample response: + +Sample response: + ```js { - "records": [ - { - "token": "45012507-f72b-4f5c-9bf9-86b133bae719", - "value": "j***oe" - } - ], - "errors": [ - { - "token": "invalid-token", - "error": { - "code": 404, - "description": "Tokens not found for invalid-token" - } - } - ] + "tokens": [5479-4229-4622-1393] } ``` ## Get -In order to retrieve data from your vault using Skyflow IDs or by Unique Column Values, use the **get(JSONObject records, GetOptions options)** method. The `records` parameter takes a JSONObject that should contain -1. Either an array of Skyflow IDs to fetch -2. Or a column name and array of column values - -The second parameter, options, is a GetOptions object that retrieves tokens of Skyflow IDs. -Note: -- GetOptions parameter applicable only for retrieving tokens using Skyflow ID. -- You can't pass GetOptions along with the redaction type. -- `tokens` defaults to false. +To retrieve data using Skyflow IDs or unique column values, use the `get` method. The `GetRequest` class is used to +create a get request, where you specify parameters such as the table name, redaction type, Skyflow IDs, column names, +column values, and return tokens. If Skyflow IDs are provided, column names and column values cannot be used. Similarly, +if column names or column values are provided, Skyflow IDs cannot be used. +Get Schema -### Use Skyflow IDs +```java +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.GetRequest; +import com.skyflow.vault.data.GetResponse; -1. Retrieve data using Redaction type: +import java.util.ArrayList; -```java -import com.skyflow.entities.RedactionType; - -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); -JSONObject record = new JSONObject(); -JSONArray ids = new JSONArray(); -ids.add(""); - -record.put("ids", ids); -record.put("table", ""); -record.put("redaction", RedactionType); - -recordsArray.add(record); -records.put("records", recordsArray); -try { - JSONObject getResponse = skyflowClient.get(records); - System.out.println(getResponse); -} catch(SkyflowException exception) { - if (exception.getData() != null) { - System.out.println(exception.getData()); - } else { - System.out.println(exception); +public class GetSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + ArrayList ids = new ArrayList<>(); + ids.add(""); + ids.add(""); + GetRequest getByIdRequest = GetRequest.builder() + .ids(ids) + .table("") + .returnTokens(false) + .redactionType(RedactionType.PLAIN_TEXT) + .build(); + GetResponse getByIdResponse = skyflowClient.vault("").get(getByIdRequest); + System.out.println(getByIdResponse); + + GetRequest getTokensRequest = GetRequest.builder() + .ids(ids) + .table("") + .returnTokens(true) + .build(); + GetResponse getTokensResponse = skyflowClient.vault("").get(getTokensRequest); + System.out.println(getTokensResponse); + + ArrayList columnValues = new ArrayList<>(); + columnValues.add(""); + columnValues.add(""); + GetRequest getByColumnRequest = GetRequest.builder() + .table("") + .columnName("") + .columnValues(columnValues) + .redactionType(RedactionType.PLAIN_TEXT) + .build(); + GetResponse getByColumnResponse = skyflowClient.vault("").get(getByColumnRequest); + System.out.println(getByColumnResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); } + } } ``` -2. Retrieve tokens using GetOptions: -```java -import com.skyflow.entities.*; - -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject record = new JSONObject(); -JSONArray ids = new JSONArray(); -ids.add(""); - -record.put("ids", ids); -record.put("table", ""); -record.put("redaction", RedactionType); -recordsArray.add(record); -records.put("records", recordsArray); - -try { - GetOptions options = new GetOptions(true); - JSONObject getResponse = skyflowClient.get(records, options); - System.out.println(getResponse); -} catch(SkyflowException exception) { - if (exception.getData() != null) { - System.out.println(exception.getData()); - } else { - System.out.println(exception); - } -} -``` - -### Use column name and values -```java -import com.skyflow.entities.RedactionType; +### Get by skyflow IDs -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); +- -JSONObject record = new JSONObject(); -JSONArray values = new JSONArray(); -values.add(""); - -record.put("table", ""); -record.put("column_name", ""); -record.put("column_values", ""); -record.put("redaction", RedactionType); -recordsArray.add(record); -records.put("records", recordsArray); -``` +An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/GetExample.java) +of a get call to retrieve data using Redaction type: -### Redaction types -There are four accepted values for RedactionType: -* `PLAIN_TEXT` -* `MASKED` -* `REDACTED` -* `DEFAULT` +```java +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.GetRequest; +import com.skyflow.vault.data.GetResponse; -### Examples -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/GetExample.java) call using Skyflow IDs with RedactionType. +import java.util.ArrayList; -```java -import com.skyflow.entities.RedactionType; - -JSONObject recordsJson = new JSONObject(); -JSONArray recordsArrayJson = new JSONArray(); - -JSONObject validRecord = new JSONObject(); -JSONArray idsJson = new JSONArray(); -idsJson.add("f8d8a622-b557-4c6b-a12c-c5ebe0b0bfd9"); -idsJson.add("da26de53-95d5-4bdb-99db-8d8c66a35ff9"); -validRecord.put("ids", idsJson); -validRecord.put("table", "cards"); -validRecord.put("redaction", Redaction.PLAIN_TEXT.toString()); - -JSONObject invalidRecord = new JSONObject(); -JSONArray invalidIdsJson = new JSONArray(); -invalidIdsJson.add("Invalid Skyflow ID"); - -invalidRecord.put("ids", invalidIdsJson); -invalidRecord.put("table", "cards"); -invalidRecord.put("redaction", Redaction.PLAIN_TEXT.toString()); -recordsArrayJson.add(validRecord); -recordsArrayJson.add(invalidRecord); -recordsJson.put("records", recordsArray); - -try { - JSONObject getResponse = skyflowClient.get(recordsJson); - System.out.println(getResponse); -} catch(SkyflowException exception) { - if (exception.getData() != null) { - System.out.println(exception.getData()); - } else { - System.out.println(exception); +public class GetExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + ArrayList ids = new ArrayList<>(); + ids.add("a581d205-1969-4350-acbe-a2a13eb871a6"); + ids.add("5ff887c3-b334-4294-9acc-70e78ae5164a"); + GetRequest getByIdRequest = GetRequest.builder() + .ids(ids) + .table("table1") + .returnTokens(false) + .redactionType(RedactionType.PLAIN_TEXT) + .build(); + GetResponse getByIdResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").get(getByIdRequest); + System.out.println(getByIdResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } } } ``` Sample response: -```json +```js { - "records": [ - { - "fields": { - "card_number": "4111111111111111", - "cvv": "127", - "expiry_date": "11/35", - "fullname": "myname", - "id": "f8d8a622-b557-4c6b-a12c-c5ebe0b0bfd9" - }, - "table": "cards" - }, - { - "fields": { - "card_number": "4111111111111111", - "cvv": "317", - "expiry_date": "10/23", - "fullname": "sam", - "id": "da26de53-95d5-4bdb-99db-8d8c66a35ff9" - }, - "table": "cards" - } - ], - "errors": [ - { - "error": { - "code": "404", - "description": "No Records Found - requestId: fc531b8d-412e-9775-b945-4feacc9b8616" - }, - "ids": ["Invalid Skyflow ID"] - } - ] + "data": [{ + "card_number": "4555555555555553", + "email": "john.doe@gmail.com", + "name": "john doe", + "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6", + }, { + "card_number": "4555555555555559", + "email": "jane.doe@gmail.com", + "name": "jane doe", + "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a", + }], + "errors": [] } ``` -An example call using Skyflow IDs with GetOptions: +- + +An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/getExample.java) +of get call to retrieve tokens using Skyflow IDs: ```java -import com.skyflow.entities.*; - -JSONObject recordsJson = new JSONObject(); -JSONArray recordsArrayJson = new JSONArray(); - -JSONObject validRecord = new JSONObject(); -JSONArray idsJson = new JSONArray(); -idsJson.add("f8d8a622-b557-4c6b-a12c-c5ebe0b0bfd9"); -idsJson.add("da26de53-95d5-4bdb-99db-8d8c66a35ff9"); -validRecord.put("ids", idsJson); -validRecord.put("table", "cards"); - -JSONObject invalidRecord = new JSONObject(); -JSONArray invalidIdsJson = new JSONArray(); -invalidIdsJson.add("Invalid Skyflow ID"); - -invalidRecord.put("ids", invalidIdsJson); -invalidRecord.put("table", "cards"); -recordsArrayJson.add(validRecord); -recordsArrayJson.add(invalidRecord); -recordsJson.put("records", recordsArray); -GetOptions options = new GetOptions(true); -try { - JSONObject getResponse = skyflowClient.get(recordsJson, options); - System.out.println(getResponse); -} catch(SkyflowException exception) { - if (exception.getData() != null) { - System.out.println(exception.getData()); - } else { - System.out.println(exception); - } +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.GetRequest; +import com.skyflow.vault.data.GetResponse; + +import java.util.ArrayList; + +public class GetExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + ArrayList ids = new ArrayList<>(); + ids.add("a581d205-1969-4350-acbe-a2a13eb871a6"); + ids.add("5ff887c3-b334-4294-9acc-70e78ae5164a"); + GetRequest getTokensRequest = GetRequest.builder() + .ids(ids) + .table("table1") + .returnTokens(true) + .build(); + GetResponse getTokensResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").get(getTokensRequest); + System.out.println(getTokensResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } } ``` + Sample response: -```json + +```js { - "records": [ - { - "fields": { - "card_number": "4555-5176-5936-1930", - "expiry_date": "23396425-93c9-419b-834b-7750b76a34b0", - "fullname": "d6bb7fe5-6b77-4842-b898-221c51c3cc20", - "id": "f8d8a622-b557-4c6b-a12c-c5ebe0b0bfd9" - }, - "table": "cards" - }, - { - "fields": { - "card_number": "8882-7418-2776-6660", - "expiry_date": "284fb1f6-3c29-449f-8899-83a7839821bc", - "fullname": "45a69af3-e22a-4668-9016-08bb2ef2259d", - "id": "da26de53-95d5-4bdb-99db-8d8c66a35ff9" - }, - "table": "cards" - } - ], - "errors": [ - { - "error": { - "code": "404", - "description": "No Records Found - requestId: fc531b8d-412e-9775-b945-4feacc9b8616" - }, - "ids": ["Invalid Skyflow ID"] - } - ] + "data": [{ + "card_number": "3998-2139-0328-0697", + "email": "c9a6c9555060@82c092e7.bd52", + "name": "82c092e7-74c0-4e60-bd52-c9a6c9555060", + "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6", + }, { + "card_number": "3562-0140-8820-7499", + "email": "6174366e2bc6@59f82e89.93fc", + "name": "59f82e89-138e-4f9b-93fc-6174366e2bc6", + "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a", + }], + "errors": [] } ``` -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/GetExample.java) call using column names and values. + +### Get By column name and column values + +- + +An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/GetExample.java) +of get call to retrieve data using column name and column values ```java -import com.skyflow.entities.RedactionType; - -JSONObject recordsJson = new JSONObject(); -JSONArray recordsArrayJson = new JSONArray(); - -JSONObject validRecord = new JSONObject(); -JSONArray valuesJson = new JSONArray(); -valuesJson.add("123455432112345"); -valuesJson.add("123455432112346"); - -validRecord.put("table", "account_details"); -validRecord.put("column_name", "bank_account_number"); -validRecord.put("column_values", valuesJson); -validRecord.put("redaction", Redaction.PLAIN_TEXT.toString()); - -JSONObject invalidRecord = new JSONObject(); -JSONArray invalidValuesJson = new JSONArray(); -invalidValuesJson.add("Invalid Skyflow column value"); - -invalidRecord.put("table", "account_details"); -invalidRecord.put("column_name", "bank_account_number"); -invalidRecord.put("column_values", valuesJson); -invalidRecord.put("redaction", Redaction.PLAIN_TEXT.toString()); - -recordsArrayJson.add(validRecord); -recordsArrayJson.add(invalidRecord); -recordsJson.put("records", recordsArray); - -try { - JSONObject getResponse = skyflowClient.get(recordsJson); - System.out.println(getResponse); -} catch(SkyflowException exception) { - if (exception.getData() != null) { - System.out.println(exception.getData()); - } else { - System.out.println(exception); +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.GetRequest; +import com.skyflow.vault.data.GetResponse; + +import java.util.ArrayList; + +public class GetExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + ArrayList columnValues = new ArrayList<>(); + columnValues.add("john.doe@gmail.com"); + columnValues.add("jane.doe@gmail.com"); + GetRequest getByColumnRequest = GetRequest.builder() + .table("table1") + .columnName("email") + .columnValues(columnValues) + .redactionType(RedactionType.PLAIN_TEXT) + .build(); + GetResponse getByColumnResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").get(getByColumnRequest); + System.out.println(getByColumnResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } } } ``` Sample response: -```json +```js { - "records": [ - { - "fields": { - "bank_account_number": "123455432112345", - "pin_code": "123123", - "name": "john doe", - "id": "492c21a1-107f-4d10-ba2c-3482a411827d" - }, - "table": "account_details" - }, - { - "fields": { - "bank_account_number": "123455432112346", - "pin_code": "103113", - "name": "jane doe", - "id": "ac6c6221-bcd1-4265-8fc7-ae7a8fb6dfd5" - }, - "table": "account_details" - } - ], - "errors": [ - { - "columnName": ["bank_account_number"], - "error": { - "code": 404, - "description": "No Records Found - requestId: fc531b8d-412e-9775-b945-4feacc9b8616" - } - } - ] + "data": [{ + "card_number": "4555555555555553", + "email": "john.doe@gmail.com", + "name": "john doe", + "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6", + }, { + "card_number": "4555555555555559", + "email": "jane.doe@gmail.com", + "name": "jane doe", + "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a", + }], + "errors": [] } ``` -`Note:` -While using detokenize and get methods, there is a possibility that some or all of the tokens might be invalid. In such cases, the data from the response consists of both errors and detokenized records. In the SDK, this will raise a SkyflowException and you can retrieve the data from the Exception object, as shown above. +### Redaction types -## GetById +There are four accepted values for RedactionType: -In order to retrieve data from your vault using SkyflowIDs, use the **getById(JSONObject records)** method. The `records` parameter takes a JSONObject that should contain an array of SkyflowIDs to be fetched, as shown below: -```java -import com.skyflow.entities.RedactionType; +* `PLAIN_TEXT` +* `MASKED` +* `REDACTED` +* `DEFAULT` + +## Update + +To update data in your vault, use the `update` method. The `UpdateRequest` class is used to create an update request, +where you specify parameters such as the table name, data (as a map of key value pairs), tokens, returnTokens, and +tokenStrict. If `returnTokens` is set to `true`, Skyflow returns tokens for the updated records. If `returnTokens` is +set to `false`, Skyflow returns IDs for the updated records. + +Update Schema: -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.UpdateRequest; +import com.skyflow.vault.data.UpdateResponse; -JSONObject record = new JSONObject(); -JSONArray ids = new JSONArray(); -ids.add(""); +import java.util.HashMap; -record.put("ids", ids); -record.put("table", ""); -record.put("redaction", RedactionType); -recordsArray.add(record); -records.put("records", recordsArray); +public class UpdateSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + HashMap data = new HashMap<>(); + data.put("skyflow_id", ""); + data.put("", ""); + data.put("", ""); + + HashMap tokens = new HashMap<>(); + tokens.put("", ""); + + UpdateRequest updateRequest = UpdateRequest.builder() + .table("") + .tokenStrict(Byot.ENABLE) + .data(data) + .tokens(tokens) + .returnTokens(true) + .build(); + UpdateResponse updateResponse = skyflowClient.vault("").update(updateRequest); + System.out.println(updateResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } +} ``` -There are 4 accepted values in RedactionType: -- `PLAIN_TEXT` -- `MASKED` -- `REDACTED` -- `DEFAULT` -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/GetByIdExample.java) getById call +An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/UpdateExample.java) +of update call: + ```java -import com.skyflow.entities.RedactionType; - -JSONObject recordsJson = new JSONObject(); -JSONArray recordsArrayJson = new JSONArray(); - -JSONObject validRecord = new JSONObject(); -JSONArray idsJson = new JSONArray(); -idsJson.add("f8d8a622-b557-4c6b-a12c-c5ebe0b0bfd9"); -idsJson.add("da26de53-95d5-4bdb-99db-8d8c66a35ff9"); -validRecord.put("ids",idsJson); -validRecord.put("table","cards"); -validRecord.put("redaction",Redaction.PLAIN_TEXT.toString()); - -JSONObject invalidRecord = new JSONObject(); -JSONArray invalidIdsJson = new JSONArray(); -invalidIdsJson.add("invalid skyflow ID"); - -invalidRecord.put("ids",invalidIdsJson); -invalidRecord.put("table","cards"); -invalidRecord.put("redaction",Redaction.PLAIN_TEXT.toString()); -recordsArrayJson.add(validRecord); -recordsArrayJson.add(invalidRecord); -recordsJson.put("records", recordsArrayJson); - -try{ - JSONObject getByIdResponse = skyflowClient.getById(recordsJson); - System.out.println(getByIdResponse); -}catch(SkyflowException exception){ - if(exception.getData() != null) - System.out.println(exception.getData()); - else - System.out.println(exception); +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.UpdateRequest; +import com.skyflow.vault.data.UpdateResponse; + +import java.util.HashMap; + +public class UpdateExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + HashMap data = new HashMap<>(); + data.put("skyflow_id", "5b699e2c-4301-4f9f-bcff-0a8fd3057413"); + data.put("name", "john doe"); + data.put("card_number", "4111111111111115"); + + HashMap tokens = new HashMap<>(); + tokens.put("name", "72b8ffe3-c8d3-4b4f-8052-38b2a7405b5a"); + + UpdateRequest updateRequest = UpdateRequest.builder() + .table("table1") + .tokenStrict(Byot.ENABLE) + .data(data) + .tokens(tokens) + .build(); + UpdateResponse updateResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").update(updateRequest); + System.out.println(updateResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } } ``` -Sample getById response + +Sample response: + +- `returnTokens` set to `true` + ```js { - "records": [ - { - "fields": { - "card_number": "4111111111111111", - "cvv": "127", - "expiry_date": "11/35", - "fullname": "myname", - "id": "f8d8a622-b557-4c6b-a12c-c5ebe0b0bfd9" - }, - "table": "cards" - }, - { - "fields": { - "card_number": "4111111111111111", - "cvv": "317", - "expiry_date": "10/23", - "fullname": "sam", - "id": "da26de53-95d5-4bdb-99db-8d8c66a35ff9" - }, - "table": "cards" - } - ], - "errors": [ - { - "error": { - "code": "404", - "description": "No Records Found" - }, - "ids": ["invalid skyflow id"] - } - ] + "skyflowId": "5b699e2c-4301-4f9f-bcff-0a8fd3057413", + "name": "72b8ffe3-c8d3-4b4f-8052-38b2a7405b5a", + "card_number": "4315-7650-1359-9681" } ``` -`Note:` While using detokenize and getByID methods, there is a possibility that some or all of the tokens might be invalid. In such cases, the data from response consists of both errors and detokenized records. In the SDK, this will raise a SkyflowException and you can retrieve the data from this Exception object as shown above. -## Update +- `returnTokens` set to `false` -In order to update the records in your vault by **skyflow_id**, use the **update(records, options)** method. The first parameter, `records`, is a JSONObject that must have a records key and takes an array of records to update as a value in the vault. The options parameter takes an object of update options and includes an option to return tokens for the updated fields as shown below: -```java -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject record = new JSONObject(); -record.put("table", ""); -record.put("id",""); - -JSONObject fields = new JSONObject(); -fields.put("", ""); -record.put("fields", fields); -recordsArray.add(record); -records.put("records", recordsArray); -UpdateOptions updateOptions = new UpdateOptions(true); +```js +{ + "skyflowId": "5b699e2c-4301-4f9f-bcff-0a8fd3057413" +} ``` -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/UpdateExample.java) of update call: +## Delete + +To delete records using Skyflow IDs, use the `delete` method. The `DeleteRequest` class accepts a list of Skyflow IDs +that you want to delete, as shown below: + +Delete schema: + ```java -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject record = new JSONObject(); -record.put("table", "cards"); -record.put("id","29ebda8d-5272-4063-af58-15cc674e332b"); - -JSONObject fields = new JSONObject(); -fields.put("card_number", "5105105105105100"); -fields.put("cardholder_name", "Thomas"); -fields.put("expiration_date", "07/2032"); -record.put("fields", fields); -recordsArray.add(record); -records.put("records", recordsArray); -UpdateOptions updateOptions = new UpdateOptions(true); - -try { - JSONObject response = skyflowClient.update(records, updateOptions); -} -catch (SkyflowException e) { - e.printStackTrace(); +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.DeleteRequest; +import com.skyflow.vault.data.DeleteResponse; + +import java.util.ArrayList; + +public class DeleteSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + ArrayList ids = new ArrayList<>(); + ids.add(""); + ids.add(""); + ids.add(""); + DeleteRequest deleteRequest = DeleteRequest.builder().ids(ids).table("").build(); + DeleteResponse deleteResponse = skyflowClient.vault("").delete(deleteRequest); + System.out.println(deleteResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } } ``` -Response: + +An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/DeleteExample.java) +of delete call: + ```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.DeleteRequest; +import com.skyflow.vault.data.DeleteResponse; + +import java.util.ArrayList; + +public class DeleteExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + ArrayList ids = new ArrayList<>(); + ids.add("9cbf66df-6357-48f3-b77b-0f1acbb69280"); + ids.add("ea74bef4-f27e-46fe-b6a0-a28e91b4477b"); + ids.add("47700796-6d3b-4b54-9153-3973e281cafb"); + DeleteRequest deleteRequest = DeleteRequest.builder().ids(ids).table("table1").build(); + DeleteResponse deleteResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").delete(deleteRequest); + System.out.println(deleteResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } +} +``` + +Sample response: + +```json { - "records": [ - { - "id": "29ebda8d-5272-4063-af58-15cc674e332b", - "fields": { - "card_number": "93f28226-51b0-4f24-8151-78b5a61f028b", - "cardholder_name": "0838fd08-9b51-4db2-893c-48542f3b121e", - "expiration_date": "91d7ee77-262f-4d5d-8286-062b694c81fd", - }, - "table": "cards" - } - ] + "deletedIds": [ + "9cbf66df-6357-48f3-b77b-0f1acbb69280", + "ea74bef4-f27e-46fe-b6a0-a28e91b4477b", + "47700796-6d3b-4b54-9153-3973e281cafb" + ] } ``` -## Delete -To delete data from the vault, use the `delete(records, options?)` method of the Skyflow client. The `records` parameter takes an array of records to delete in the following format. The `options` parameter is optional and takes an object of deletion parameters. Currently, there are no supported deletion parameters. +### Query + +To retrieve data with SQL queries, use the `query` method. The `QueryRequest` class accepts a `query` parameter as +follows: -Call schema: +Query Schema ```java -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.QueryRequest; +import com.skyflow.vault.data.QueryResponse; -JSONObject record = new JSONObject(); +public class QueryExample { + public static void main(String[] args) { + try { + // initialize Skyflow client + String query = ""; + QueryRequest queryRequest = QueryRequest.builder().query(query).build(); + QueryResponse queryResponse = skyflowClient.vault("").query(queryRequest); + System.out.println(queryResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } +} +``` -record.put("id", ""); -record.put("table", ""); -recordsArray.add(record); -records.put("records", recordsArray); +See [Query your data](https://docs.skyflow.com/query-data/) +and [Execute Query](https://docs.skyflow.com/record/#QueryService_ExecuteQuery) for guidelines and restrictions on +supported SQL statements, operators, and keywords. -skyflowClient.delete(records); -``` +An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/QueryExample.java) +of query call: -An example of delete call: ```java -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject record = new JSONObject(); -record.put("id", "71be4592-b9af-4dec-8669-5b9c926afb4c"); -record.put("table", "cards"); -recordsArray.add(record); - -JSONObject record2 = new JSONObject(); -record2.put("id", "2adf32e7-9a04-408e-b8bb-5b0a852422e0"); -record2.put("table", "cards"); -recordsArray.add(record2); - -records.put("records", recordsArray); - -try { - JSONObject response = skyflowClient.delete(records); -} catch (SkyflowException e) { - e.printStackTrace(); - System.out.println("error"+ e.getData()); +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.QueryRequest; +import com.skyflow.vault.data.QueryResponse; + +public class QueryExample { + public static void main(String[] args) { + try { + // initialize Skyflow client + String query = "SELECT * FROM cards WHERE skyflow_id='3ea3861-x107-40w8-la98-106sp08ea83f'"; + QueryRequest queryRequest = QueryRequest.builder().query(query).build(); + QueryResponse queryResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").query(queryRequest); + System.out.println(queryResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } } ``` -Response: -```json + +Sample response: + +```js { - "records": [ - { - "skyflow_id": "71be4592-b9af-4dec-8669-5b9c926afb4c", - "deleted": true, - }, - { - "skyflow_id": "2adf32e7-9a04-408e-b8bb-5b0a852422e0", - "deleted": true, - } - ] + "fields": [{ + "card_number": "XXXXXXXXXXXX1112", + "name": "S***ar", + "skyflow_id": "3ea3861-x107-40w8-la98-106sp08ea83f", + "tokenizedData": null + }] } ``` +# Connections + +The [connections](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault/connection) +module is used to invoke INBOUND and/or OUTBOUND connections. + ## Invoke Connection -Using the InvokeConnection method, you can integrate their server-side application with third party APIs and services without directly handling sensitive data. Prior to invoking the `InvokeConnection` method, you must have created a connection and have a connectionURL already generated. Once you have the connectionURL, you can invoke a connection by using the **invokeConnection(JSONObject config)** method. The JSONObject config parameter must include a `connectionURL` and `methodName`. The other fields are optional. +Using Skyflow Connection, end-user applications can integrate checkout/card issuance flow with their apps/systems. To +invoke connection, use the `invoke` method of the Skyflow client. + +Invoke Connection Schema: + ```java -JSONObject invokeConfig = new JSONObject(); -// connection url received when creating a skyflow connection integration -invokeConfig.put("connectionURL", ""); -invokeConfig.put("methodName", RequestMethod); - -JSONObject pathParamsJson = new JSONObject(); -pathParamsJson.put("", ""); -invokeConfig.put("pathParams", pathParamsJson); - -JSONObject queryParamsJson = new JSONObject(); -queryParamsJson.put("", ""); -invokeConfig.put("queryParams", queryParamsJson); - -JSONObject requestHeadersJson = new JSONObject(); -requestHeadersJson.put("", ""); -invokeConfig.put("requestHeader", requestHeadersJson); - -JSONObject requestBodyJson = new JSONObject(); -requestBodyJson.put("", ""); -invokeConfig.put("requestBody", requestBodyJson); +import com.skyflow.enums.RequestMethod; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.connection.InvokeConnectionRequest; +import com.skyflow.vault.connection.InvokeConnectionResponse; + +import java.util.HashMap; +import java.util.Map; + +public class InvokeConnectionSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + Map requestBody = new HashMap<>(); + requestBody.put("", ""); + requestBody.put("", ""); + + Map requestHeaders = new HashMap<>(); + requestHeaders.put("", ""); + requestHeaders.put("", ""); + + Map pathParams = new HashMap<>(); + pathParams.put("", ""); + pathParams.put("", ""); + + Map queryParams = new HashMap<>(); + queryParams.put("", ""); + queryParams.put("", ""); + + InvokeConnectionRequest invokeConnectionRequest = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestBody(requestBody) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .build(); + InvokeConnectionResponse invokeConnectionResponse = skyflowClient.connection("").invoke(invokeConnectionRequest); + System.out.println(invokeConnectionResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } +} ``` `methodName` supports the following methods: + - GET - POST - PUT - PATCH - DELETE +**pathParams, queryParams, requestHeader, requestBody** are the JSON objects represented as HashMaps, that will be sent +through the connection integration url. -**pathParams, queryParams, requestHeader, requestBody** are the JSON objects that will be sent through the connection integration url. +An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/connection/InvokeConnectionExample.java) +of invokeConnection: -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/InvokeConnectionExample.java) of invokeConnection: ```java -JSONObject invokeConfig = new JSONObject(); -invokeConfig.put("connectionURL", ""); -invokeConfig.put("methodName", RequestMethod.POST); - -JSONObject requestHeaderJson = new JSONObject(); -requestHeaderJson.put("Content-Type","application/json"); -requestHeaderJson.put("Authorization",""); - -invokeConfig.put("requestHeader",requestHeaderJson); - -JSONObject requestBodyJson = new JSONObject(); -requestBodyJson.put("expirationDate","12/2026"); -invokeConfig.put("requestBody",requestBodyJson); +import com.skyflow.Skyflow; +import com.skyflow.config.ConnectionConfig; +import com.skyflow.config.Credentials; +import com.skyflow.enums.LogLevel; +import com.skyflow.enums.RequestMethod; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.connection.InvokeConnectionRequest; +import com.skyflow.vault.connection.InvokeConnectionResponse; -JSONObject pathParamsJson = new JSONObject(); -pathParamsJson.put("card_number","1852-344-234-34251"); -invokeConfig.put("pathParams",pathParamsJson); +import java.util.HashMap; +import java.util.Map; -try{ - JSONObject invokeConnectionResponse = skyflow.invokeConnection(invokeConfig); - System.out.println(invokeResponse) -}catch(SkyflowException exception){ - System.out.println(exception); +public class InvokeConnectionExample { + public static void main(String[] args) { + try { + Credentials credentials = new Credentials(); + credentials.setPath("/path/to/credentials.json"); + + ConnectionConfig connectionConfig = new ConnectionConfig(); + connectionConfig.setConnectionId(""); + connectionConfig.setConnectionUrl("https://connection.url.com"); + connectionConfig.setCredentials(credentials); + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addConnectionConfig(connectionConfig) + .build(); + + Map requestBody = new HashMap<>(); + requestBody.put("card_number", "4337-1696-5866-0865"); + requestBody.put("ssn", "524-41-4248"); + + Map requestHeaders = new HashMap<>(); + requestHeaders.put("Content-Type", "application/json"); + + InvokeConnectionRequest invokeConnectionRequest = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) + .requestBody(requestBody) + .requestHeaders(requestHeaders) + .build(); + InvokeConnectionResponse invokeConnectionResponse = skyflowClient.connection("").invoke(invokeConnectionRequest); + System.out.println(invokeConnectionResponse); + } catch (SkyflowException e) { + System.out.println("Error occurred: "); + System.out.println(e); + } + } } - ``` -Sample invokeConnection Response + +Sample response: + ```js -{ - "receivedTimestamp": "2021-11-05 13:43:12.534", - "processingTimeinMs": 12, - "resource": { - "cvv2": "558" - } +InvokeConnectionResponse{ + response={ + "card_number":"4337-1696-5866-0865", + "ssn":"524-41-4248" } ``` -### Query +## Logging -To retrieve data with SQL queries, use the `query(queryInput, options)` method. `queryInput` is an object that takes the `query` parameter as follows: +The skyflow java SDK provides useful logging using python's inbuilt `logging` library. By default, the logging level of +the SDK is set to `LogLevel.ERROR`. This can be changed by using `setLogLevel(logLevel)` method as shown below: ```java -JSONObject queryInput = new JSONObject(); -queryInput.put("query", ""); -skyflowClient.query(queryInput); -``` -See [Query your data](https://docs.skyflow.com/query-data/) and [Execute Query](https://docs.skyflow.com/record/#QueryService_ExecuteQuery) for guidelines and restrictions on supported SQL statements, operators, and keywords. - -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/QueryExample.java) of query call: -```java -JSONObject queryInput = new JSONObject(); -queryInput.put("query", "SELECT * FROM cards WHERE skyflow_id='3ea3861-x107-40w8-la98-106sp08ea83f'"); - -try { - JSONObject res = skyflowClient.query(queryInput); -} catch (SkyflowException e) { - System.out.println(e.getData()); - e.printStackTrace(); -} -``` +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; -Sample Response -```java -{ - "records": [ - { - "fields": { - "card_number": "XXXXXXXXXXXX1111", - "card_pin": "*REDACTED*", - "cvv": "", - "expiration_date": "*REDACTED*", - "expiration_month": "*REDACTED*", - "expiration_year": "*REDACTED*", - "name": "a***te", - "skyflow_id": "3ea3861-x107-40w8-la98-106sp08ea83f", - "ssn": "XXX-XX-6789", - "zip_code": null - }, - "tokens": null +public class ChangeLogLevel { + public static void main(String[] args) throws SkyflowException { + // Pass only one of apiKey, token, credentialsString or path in credentials + Credentials credentials = new Credentials(); + credentials.setToken(""); + + VaultConfig config = new VaultConfig(); + config.setVaultId(""); // Primary vault + config.setClusterId(""); // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com + config.setEnv(Env.PROD); // Env by default is set to PROD + config.setCredentials(credentials); // Individual credentials + + JsonObject credentialsObject = new JsonObject(); + credentialsObject.addProperty("clientID", ""); + credentialsObject.addProperty("clientName", ""); + credentialsObject.addProperty("TokenURI", ""); + credentialsObject.addProperty("keyID", ""); + credentialsObject.addProperty("privateKey", ""); + + // To generate Bearer Token from credentials string. + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(credentialsObject.toString()); + + Skyflow skyflowClient = Skyflow.builder() + .addVaultConfig(config) // Add vault config + .addSkyflowCredentials(skyflowCredentials) // Skyflow credentials will be used if no individual credentials are passed + .setLogLevel(LogLevel.INFO) // Set log level. By default, it is set to ERROR + .build(); } - ] } ``` -## Logging -The skyflow-java SDK provides useful logging using java inbuilt `java.util.logging`. By default the logging level of the SDK is set to `LogLevel.ERROR`. This can be changed by using `setLogLevel(LogLevel)` as shown below: +Currently, the following 5 log levels are supported: -```java -import com.skyflow.entities.LogLevel; -import com.skyflow.Configuration; +- `DEBUG`: -// sets the skyflow-java SDK log level to INFO -Configuration.setLogLevel(LogLevel.INFO); -``` + When `LogLevel.DEBUG` is passed, all level of logs will be printed(DEBUG, INFO, WARN, ERROR) -Current the following 5 log levels are supported: +- `INFO`: -- `DEBUG`: + When `LogLevel.INFO` is passed, INFO logs for every event that has occurred during the SDK flow execution will be + printed along with WARN and ERROR logs - When `LogLevel.DEBUG` is passed, all level of logs will be printed(DEBUG, INFO, WARN, ERROR) - -- `INFO`: +- `WARN`: - When `LogLevel.INFO` is passed, INFO logs for every event that has occurred during the SDK flow execution will be printed along with WARN and ERROR logs - -- `WARN`: + When `LogLevel.WARN` is passed, WARN and ERROR logs will be printed - When `LogLevel.WARN` is passed, WARN and ERROR logs will be printed - - `ERROR`: - When `LogLevel.ERROR` is passed, only ERROR logs will be printed. - -- `OFF`: + When `LogLevel.ERROR` is passed, only ERROR logs will be printed. + +- `OFF`: - `LogLevel.OFF` can be used to turn off all logging from the skyflow-java SDK. - + `LogLevel.OFF` can be used to turn off all logging from the skyflow-java SDK. -`Note`: - - The ranking of logging levels is as follows : `DEBUG` < `INFO` < `WARN` < `ERROR`. +`Note`: The ranking of logging levels is as follows : `DEBUG` < `INFO` < `WARN` < `ERROR`. ## Reporting a Vulnerability -If you discover a potential security issue in this project, please reach out to us at security@skyflow.com. Please do not create public GitHub issues or Pull Requests, as malicious actors could potentially view them. +If you discover a potential security issue in this project, please reach out to us at security@skyflow.com. Please do +not create public GitHub issues or Pull Requests, as malicious actors could potentially view them. From 5fb4dae02f741df4f42e384453ec887a7586f7d9 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 26 Nov 2024 17:10:11 +0530 Subject: [PATCH 070/126] SK-1750 Change tokenStrict to tokenMode --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index eb623084..9c873157 100644 --- a/README.md +++ b/README.md @@ -1030,6 +1030,7 @@ set to `false`, Skyflow returns IDs for the updated records. Update Schema: ```java +import com.skyflow.enums.TokenMode; import com.skyflow.errors.SkyflowException; import com.skyflow.vault.data.UpdateRequest; import com.skyflow.vault.data.UpdateResponse; @@ -1050,7 +1051,7 @@ public class UpdateSchema { UpdateRequest updateRequest = UpdateRequest.builder() .table("") - .tokenStrict(Byot.ENABLE) + .tokenMode(TokenMode.ENABLE) .data(data) .tokens(tokens) .returnTokens(true) @@ -1069,6 +1070,7 @@ An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/ma of update call: ```java +import com.skyflow.enums.TokenMode; import com.skyflow.errors.SkyflowException; import com.skyflow.vault.data.UpdateRequest; import com.skyflow.vault.data.UpdateResponse; @@ -1089,7 +1091,7 @@ public class UpdateExample { UpdateRequest updateRequest = UpdateRequest.builder() .table("table1") - .tokenStrict(Byot.ENABLE) + .tokenMode(TokenMode.ENABLE) .data(data) .tokens(tokens) .build(); @@ -1308,7 +1310,7 @@ public class InvokeConnectionSchema { queryParams.put("", ""); InvokeConnectionRequest invokeConnectionRequest = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestBody(requestBody) .requestHeaders(requestHeaders) .pathParams(pathParams) @@ -1375,7 +1377,7 @@ public class InvokeConnectionExample { requestHeaders.put("Content-Type", "application/json"); InvokeConnectionRequest invokeConnectionRequest = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestBody(requestBody) .requestHeaders(requestHeaders) .build(); From 3817de62fc4f0d1743244120d351996b2ff8f575 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 26 Nov 2024 17:24:16 +0530 Subject: [PATCH 071/126] SK-1790 Changed tokenStrict to tokenMode - Changed tokenStrict to tokenMode for insert and update requests. - Changed methodName to method for invoke connection request. - Changed enum Byot to TokenMode. --- src/main/java/com/skyflow/VaultClient.java | 6 +- .../enums/{Byot.java => TokenMode.java} | 4 +- .../java/com/skyflow/errors/ErrorMessage.java | 6 +- src/main/java/com/skyflow/logs/ErrorLogs.java | 6 +- .../utils/validations/Validations.java | 78 ++++++++++--------- .../connection/InvokeConnectionRequest.java | 13 ++-- .../controller/ConnectionController.java | 2 +- .../com/skyflow/vault/data/InsertRequest.java | 25 ++---- .../com/skyflow/vault/data/UpdateRequest.java | 14 ++-- .../skyflow/config/ConnectionConfigTests.java | 15 +--- .../com/skyflow/config/CredentialsTests.java | 15 +--- .../com/skyflow/config/VaultConfigTests.java | 15 +--- .../java/com/skyflow/utils/UtilsTests.java | 2 +- .../connection/InvokeConnectionTests.java | 36 ++++----- .../com/skyflow/vault/data/DeleteTests.java | 17 +--- .../java/com/skyflow/vault/data/GetTests.java | 14 +--- .../com/skyflow/vault/data/InsertTests.java | 46 ++++------- .../com/skyflow/vault/data/QueryTests.java | 15 +--- .../com/skyflow/vault/data/UpdateTests.java | 41 ++++------ 19 files changed, 131 insertions(+), 239 deletions(-) rename src/main/java/com/skyflow/enums/{Byot.java => TokenMode.java} (88%) diff --git a/src/main/java/com/skyflow/VaultClient.java b/src/main/java/com/skyflow/VaultClient.java index a6a63f64..2f415f4f 100644 --- a/src/main/java/com/skyflow/VaultClient.java +++ b/src/main/java/com/skyflow/VaultClient.java @@ -97,7 +97,7 @@ protected RecordServiceInsertRecordBody getBulkInsertRequestBody(InsertRequest r insertRecordBody.setTokenization(request.getReturnTokens()); insertRecordBody.setHomogeneous(request.getHomogeneous()); insertRecordBody.setUpsert(request.getUpsert()); - insertRecordBody.setByot(request.getTokenStrict().getBYOT()); + insertRecordBody.setByot(request.getTokenMode().getBYOT()); List> values = request.getValues(); List> tokens = request.getTokens(); @@ -117,7 +117,7 @@ protected RecordServiceInsertRecordBody getBulkInsertRequestBody(InsertRequest r protected RecordServiceBatchOperationBody getBatchInsertRequestBody(InsertRequest request) { RecordServiceBatchOperationBody insertRequestBody = new RecordServiceBatchOperationBody(); insertRequestBody.setContinueOnError(true); - insertRequestBody.setByot(request.getTokenStrict().getBYOT()); + insertRequestBody.setByot(request.getTokenMode().getBYOT()); ArrayList> values = request.getValues(); ArrayList> tokens = request.getTokens(); @@ -142,7 +142,7 @@ protected RecordServiceBatchOperationBody getBatchInsertRequestBody(InsertReques protected RecordServiceUpdateRecordBody getUpdateRequestBody(UpdateRequest request) { RecordServiceUpdateRecordBody updateRequestBody = new RecordServiceUpdateRecordBody(); - updateRequestBody.byot(request.getTokenStrict().getBYOT()); + updateRequestBody.byot(request.getTokenMode().getBYOT()); updateRequestBody.setTokenization(request.getReturnTokens()); HashMap values = request.getData(); HashMap tokens = request.getTokens(); diff --git a/src/main/java/com/skyflow/enums/Byot.java b/src/main/java/com/skyflow/enums/TokenMode.java similarity index 88% rename from src/main/java/com/skyflow/enums/Byot.java rename to src/main/java/com/skyflow/enums/TokenMode.java index 9fe7d989..28564bb5 100644 --- a/src/main/java/com/skyflow/enums/Byot.java +++ b/src/main/java/com/skyflow/enums/TokenMode.java @@ -2,14 +2,14 @@ import com.skyflow.generated.rest.models.V1BYOT; -public enum Byot { +public enum TokenMode { DISABLE(V1BYOT.DISABLE), ENABLE(V1BYOT.ENABLE), ENABLE_STRICT(V1BYOT.ENABLE_STRICT); private final V1BYOT byot; - Byot(V1BYOT byot) { + TokenMode(V1BYOT byot) { this.byot = byot; } diff --git a/src/main/java/com/skyflow/errors/ErrorMessage.java b/src/main/java/com/skyflow/errors/ErrorMessage.java index ac5fd0cf..81516e94 100644 --- a/src/main/java/com/skyflow/errors/ErrorMessage.java +++ b/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -65,10 +65,10 @@ public enum ErrorMessage { EmptyValueInTokens("%s0 Validation error. Invalid value in tokens. Specify a valid value."), EmptyUpsert("%s0 Validation error. 'upsert' key can't be empty. Specify an upsert column."), HomogenousNotSupportedWithUpsert("%s0 Validation error. 'homogenous' is not supported with 'upsert'. Specify either 'homogenous' or 'upsert'."), - TokensPassedForByotDisable("%s0 Validation error. 'tokenStrict' wasn't specified. Set 'tokenStrict' to 'ENABLE' to insert tokens."), - NoTokensWithByot("%s0 Validation error. Tokens weren't specified for records while 'tokenStrict' was %s1. Specify tokens."), + TokensPassedForTokenModeDisable("%s0 Validation error. 'tokenMode' wasn't specified. Set 'tokenMode' to 'ENABLE' to insert tokens."), + NoTokensWithTokenMode("%s0 Validation error. Tokens weren't specified for records while 'tokenMode' was %s1. Specify tokens."), MismatchOfFieldsAndTokens("%s0 Validation error. 'fields' and 'tokens' have different columns names. Verify that 'fields' and 'tokens' columns match."), - InsufficientTokensPassedForByotEnableStrict("%s0 Validation error. 'tokenStrict' is set to 'ENABLE_STRICT', but some fields are missing tokens. Specify tokens for all fields."), + InsufficientTokensPassedForTokenModeEnableStrict("%s0 Validation error. 'tokenMode' is set to 'ENABLE_STRICT', but some fields are missing tokens. Specify tokens for all fields."), BatchInsertPartialSuccess("%s0 Insert operation completed with partial success."), BatchInsertFailure("%s0 Insert operation failed."), diff --git a/src/main/java/com/skyflow/logs/ErrorLogs.java b/src/main/java/com/skyflow/logs/ErrorLogs.java index ad32b886..64e40c82 100644 --- a/src/main/java/com/skyflow/logs/ErrorLogs.java +++ b/src/main/java/com/skyflow/logs/ErrorLogs.java @@ -53,12 +53,12 @@ public enum ErrorLogs { EMPTY_OR_NULL_KEY_IN_VALUES("Invalid %s1 request. Key can not be null or empty in values"), EMPTY_UPSERT("Invalid %s1 request. Upsert can not be empty."), HOMOGENOUS_NOT_SUPPORTED_WITH_UPSERT("Invalid %s1 request. Homogenous is not supported when upsert is passed."), - TOKENS_NOT_ALLOWED_WITH_BYOT_DISABLE("Invalid %s1 request. Tokens are not allowed when tokenStrict is DISABLE."), - TOKENS_REQUIRED_WITH_BYOT("Invalid %s1 request. Tokens are required when tokenStrict is %s2."), + TOKENS_NOT_ALLOWED_WITH_TOKEN_MODE_DISABLE("Invalid %s1 request. Tokens are not allowed when tokenMode is DISABLE."), + TOKENS_REQUIRED_WITH_TOKEN_MODE("Invalid %s1 request. Tokens are required when tokenMode is %s2."), EMPTY_TOKENS("Invalid %s1 request. Tokens can not be empty."), EMPTY_OR_NULL_VALUE_IN_TOKENS("Invalid %s1 request. Value can not be null or empty in tokens for key \"%s2\"."), EMPTY_OR_NULL_KEY_IN_TOKENS("Invalid %s1 request. Key can not be null or empty in tokens."), - INSUFFICIENT_TOKENS_PASSED_FOR_BYOT_ENABLE_STRICT("Invalid %s1 request. For tokenStrict as ENABLE_STRICT, tokens should be passed for all fields."), + INSUFFICIENT_TOKENS_PASSED_FOR_TOKEN_MODE_ENABLE_STRICT("Invalid %s1 request. For tokenMode as ENABLE_STRICT, tokens should be passed for all fields."), MISMATCH_OF_FIELDS_AND_TOKENS("Invalid %s1 request. Keys for values and tokens are not matching."), INSERT_RECORDS_REJECTED("Insert request resulted in failure."), TOKENS_REQUIRED("Invalid %s1 request. Tokens are required."), diff --git a/src/main/java/com/skyflow/utils/validations/Validations.java b/src/main/java/com/skyflow/utils/validations/Validations.java index 77f6b823..e1e52581 100644 --- a/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/src/main/java/com/skyflow/utils/validations/Validations.java @@ -3,9 +3,9 @@ import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.Byot; import com.skyflow.enums.InterfaceName; import com.skyflow.enums.RedactionType; +import com.skyflow.enums.TokenMode; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; @@ -238,7 +238,7 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky ArrayList> tokens = insertRequest.getTokens(); String upsert = insertRequest.getUpsert(); Boolean homogeneous = insertRequest.getHomogeneous(); - Byot tokenStrict = insertRequest.getTokenStrict(); + TokenMode tokenMode = insertRequest.getTokenMode(); if (table == null) { LogUtil.printErrorLog(Utils.parameterizedString( @@ -296,46 +296,46 @@ public static void validateInsertRequest(InsertRequest insertRequest) throws Sky } } - switch (tokenStrict) { + switch (tokenMode) { case DISABLE: if (tokens != null) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.TOKENS_NOT_ALLOWED_WITH_BYOT_DISABLE.getLog(), InterfaceName.INSERT.getName() + ErrorLogs.TOKENS_NOT_ALLOWED_WITH_TOKEN_MODE_DISABLE.getLog(), InterfaceName.INSERT.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TokensPassedForByotDisable.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TokensPassedForTokenModeDisable.getMessage()); } break; case ENABLE: if (tokens == null) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.TOKENS_REQUIRED_WITH_BYOT.getLog(), - InterfaceName.INSERT.getName(), Byot.ENABLE.toString() + ErrorLogs.TOKENS_REQUIRED_WITH_TOKEN_MODE.getLog(), + InterfaceName.INSERT.getName(), TokenMode.ENABLE.toString() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), - Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE.toString()) + Utils.parameterizedString(ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE.toString()) ); } - validateTokensForInsertRequest(tokens, values, tokenStrict); + validateTokensForInsertRequest(tokens, values, tokenMode); break; case ENABLE_STRICT: if (tokens == null) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.TOKENS_REQUIRED_WITH_BYOT.getLog(), - InterfaceName.INSERT.getName(), Byot.ENABLE_STRICT.toString() + ErrorLogs.TOKENS_REQUIRED_WITH_TOKEN_MODE.getLog(), + InterfaceName.INSERT.getName(), TokenMode.ENABLE_STRICT.toString() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), - Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString()) + Utils.parameterizedString(ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE_STRICT.toString()) ); } else if (tokens.size() != values.size()) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_BYOT_ENABLE_STRICT.getLog(), + ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_TOKEN_MODE_ENABLE_STRICT.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), - ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage() + ErrorMessage.InsufficientTokensPassedForTokenModeEnableStrict.getMessage() ); } - validateTokensForInsertRequest(tokens, values, tokenStrict); + validateTokensForInsertRequest(tokens, values, tokenMode); break; } } @@ -488,7 +488,7 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky String table = updateRequest.getTable(); HashMap data = updateRequest.getData(); HashMap tokens = updateRequest.getTokens(); - Byot tokenStrict = updateRequest.getTokenStrict(); + TokenMode tokenMode = updateRequest.getTokenMode(); if (table == null) { LogUtil.printErrorLog(Utils.parameterizedString( @@ -550,42 +550,42 @@ public static void validateUpdateRequest(UpdateRequest updateRequest) throws Sky } } - switch (tokenStrict) { + switch (tokenMode) { case DISABLE: if (tokens != null) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.TOKENS_NOT_ALLOWED_WITH_BYOT_DISABLE.getLog(), InterfaceName.INSERT.getName() + ErrorLogs.TOKENS_NOT_ALLOWED_WITH_TOKEN_MODE_DISABLE.getLog(), InterfaceName.UPDATE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), - ErrorMessage.TokensPassedForByotDisable.getMessage()); + ErrorMessage.TokensPassedForTokenModeDisable.getMessage()); } break; case ENABLE: if (tokens == null) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.TOKENS_REQUIRED_WITH_BYOT.getLog(), - InterfaceName.INSERT.getName(), Byot.ENABLE.toString() + ErrorLogs.TOKENS_REQUIRED_WITH_TOKEN_MODE.getLog(), + InterfaceName.UPDATE.getName(), TokenMode.ENABLE.toString() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( - ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE.toString())); + ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE.toString())); } validateTokensMapWithTokenStrict(tokens, data); break; case ENABLE_STRICT: if (tokens == null) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.TOKENS_REQUIRED_WITH_BYOT.getLog(), - InterfaceName.INSERT.getName(), Byot.ENABLE_STRICT.toString() + ErrorLogs.TOKENS_REQUIRED_WITH_TOKEN_MODE.getLog(), + InterfaceName.UPDATE.getName(), TokenMode.ENABLE_STRICT.toString() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( - ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString())); + ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE_STRICT.toString())); } else if (tokens.size() != (data.size() - 1)) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_BYOT_ENABLE_STRICT.getLog(), - InterfaceName.INSERT.getName() + ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_TOKEN_MODE_ENABLE_STRICT.getLog(), + InterfaceName.UPDATE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), - ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage()); + ErrorMessage.InsufficientTokensPassedForTokenModeEnableStrict.getMessage()); } validateTokensMapWithTokenStrict(tokens, data); break; @@ -692,7 +692,7 @@ private static boolean isInvalidURL(String configURL) { private static void validateTokensForInsertRequest( ArrayList> tokens, ArrayList> values, - Byot tokenStrict + TokenMode tokenStrict ) throws SkyflowException { if (tokens.isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( @@ -704,31 +704,37 @@ private static void validateTokensForInsertRequest( for (int index = 0; index < tokens.size(); index++) { HashMap tokensMap = tokens.get(index); HashMap valuesMap = values.get(index); - if (tokensMap.size() != valuesMap.size() && tokenStrict == Byot.ENABLE_STRICT) { + if (tokensMap.size() != valuesMap.size() && tokenStrict == TokenMode.ENABLE_STRICT) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_BYOT_ENABLE_STRICT.getLog(), + ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_TOKEN_MODE_ENABLE_STRICT.getLog(), InterfaceName.INSERT.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), - ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage() + ErrorMessage.InsufficientTokensPassedForTokenModeEnableStrict.getMessage() ); } - validateTokensMapWithTokenStrict(tokensMap, valuesMap); + validateTokensMapWithTokenStrict(tokensMap, valuesMap, InterfaceName.INSERT.getName()); } } private static void validateTokensMapWithTokenStrict( HashMap tokensMap, HashMap valuesMap + ) throws SkyflowException { + validateTokensMapWithTokenStrict(tokensMap, valuesMap, InterfaceName.UPDATE.getName()); + } + + private static void validateTokensMapWithTokenStrict( + HashMap tokensMap, HashMap valuesMap, String interfaceName ) throws SkyflowException { for (String key : tokensMap.keySet()) { if (key == null || key.trim().isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.EMPTY_OR_NULL_KEY_IN_TOKENS.getLog(), InterfaceName.INSERT.getName() + ErrorLogs.EMPTY_OR_NULL_KEY_IN_TOKENS.getLog(), interfaceName )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyKeyInTokens.getMessage()); } else if (!valuesMap.containsKey(key)) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.MISMATCH_OF_FIELDS_AND_TOKENS.getLog(), InterfaceName.INSERT.getName() + ErrorLogs.MISMATCH_OF_FIELDS_AND_TOKENS.getLog(), interfaceName )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MismatchOfFieldsAndTokens.getMessage()); } else { @@ -736,7 +742,7 @@ private static void validateTokensMapWithTokenStrict( if (value == null || value.toString().trim().isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_VALUE_IN_TOKENS.getLog(), - InterfaceName.INSERT.getName(), key + interfaceName, key )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyValueInTokens.getMessage()); } diff --git a/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java b/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java index c64bedf4..ea71cd0a 100644 --- a/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java +++ b/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java @@ -2,7 +2,6 @@ import com.skyflow.enums.RequestMethod; -import java.util.HashMap; import java.util.Map; public class InvokeConnectionRequest { @@ -17,8 +16,8 @@ public static InvokeConnectionRequestBuilder builder() { return new InvokeConnectionRequestBuilder(); } - public RequestMethod getMethodName() { - return builder.methodName; + public RequestMethod getMethod() { + return builder.method; } public Map getPathParams() { @@ -38,19 +37,19 @@ public Object getRequestBody() { } public static final class InvokeConnectionRequestBuilder { - private RequestMethod methodName; + private RequestMethod method; private Map pathParams; private Map queryParams; private Map requestHeaders; private Object requestBody; private InvokeConnectionRequestBuilder() { - this.methodName = RequestMethod.POST; + this.method = RequestMethod.POST; this.requestBody = new Object(); } - public InvokeConnectionRequestBuilder methodName(RequestMethod methodName) { - this.methodName = methodName == null ? RequestMethod.POST : methodName; + public InvokeConnectionRequestBuilder method(RequestMethod method) { + this.method = method == null ? RequestMethod.POST : method; return this; } diff --git a/src/main/java/com/skyflow/vault/controller/ConnectionController.java b/src/main/java/com/skyflow/vault/controller/ConnectionController.java index 890ef530..81e413ed 100644 --- a/src/main/java/com/skyflow/vault/controller/ConnectionController.java +++ b/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -48,7 +48,7 @@ public InvokeConnectionResponse invoke(InvokeConnectionRequest invokeConnectionR headers.put("x-skyflow-authorization", token == null ? apiKey : token); } - RequestMethod requestMethod = invokeConnectionRequest.getMethodName(); + RequestMethod requestMethod = invokeConnectionRequest.getMethod(); JsonObject requestBody = null; Object requestBodyObject = invokeConnectionRequest.getRequestBody(); diff --git a/src/main/java/com/skyflow/vault/data/InsertRequest.java b/src/main/java/com/skyflow/vault/data/InsertRequest.java index b2a49f1b..55db92e4 100644 --- a/src/main/java/com/skyflow/vault/data/InsertRequest.java +++ b/src/main/java/com/skyflow/vault/data/InsertRequest.java @@ -1,6 +1,6 @@ package com.skyflow.vault.data; -import com.skyflow.enums.Byot; +import com.skyflow.enums.TokenMode; import java.util.ArrayList; import java.util.HashMap; @@ -40,16 +40,12 @@ public Boolean getHomogeneous() { return this.builder.homogeneous; } - public Boolean getTokenMode() { - return this.builder.tokenMode; - } - public Boolean getContinueOnError() { return this.builder.continueOnError; } - public Byot getTokenStrict() { - return this.builder.tokenStrict; + public TokenMode getTokenMode() { + return this.builder.tokenMode; } public static final class InsertRequestBuilder { @@ -59,15 +55,13 @@ public static final class InsertRequestBuilder { private Boolean returnTokens; private String upsert; private Boolean homogeneous; - private Boolean tokenMode; private Boolean continueOnError; - private Byot tokenStrict; + private TokenMode tokenMode; private InsertRequestBuilder() { this.returnTokens = true; - this.tokenMode = false; this.continueOnError = false; - this.tokenStrict = Byot.DISABLE; + this.tokenMode = TokenMode.DISABLE; } public InsertRequestBuilder table(String table) { @@ -100,18 +94,13 @@ public InsertRequestBuilder homogeneous(Boolean homogeneous) { return this; } - public InsertRequestBuilder tokenMode(Boolean tokenMode) { - this.tokenMode = tokenMode != null && tokenMode; - return this; - } - public InsertRequestBuilder continueOnError(Boolean continueOnError) { this.continueOnError = continueOnError != null && continueOnError; return this; } - public InsertRequestBuilder tokenStrict(Byot tokenStrict) { - this.tokenStrict = tokenStrict == null ? Byot.DISABLE : tokenStrict; + public InsertRequestBuilder tokenMode(TokenMode tokenMode) { + this.tokenMode = tokenMode == null ? TokenMode.DISABLE : tokenMode; return this; } diff --git a/src/main/java/com/skyflow/vault/data/UpdateRequest.java b/src/main/java/com/skyflow/vault/data/UpdateRequest.java index 58e075ac..03ca8f42 100644 --- a/src/main/java/com/skyflow/vault/data/UpdateRequest.java +++ b/src/main/java/com/skyflow/vault/data/UpdateRequest.java @@ -1,6 +1,6 @@ package com.skyflow.vault.data; -import com.skyflow.enums.Byot; +import com.skyflow.enums.TokenMode; import java.util.HashMap; @@ -31,8 +31,8 @@ public HashMap getTokens() { return this.builder.tokens; } - public Byot getTokenStrict() { - return this.builder.tokenStrict; + public TokenMode getTokenMode() { + return this.builder.tokenMode; } public static final class UpdateRequestBuilder { @@ -40,11 +40,11 @@ public static final class UpdateRequestBuilder { private Boolean returnTokens; private HashMap data; private HashMap tokens; - private Byot tokenStrict; + private TokenMode tokenMode; private UpdateRequestBuilder() { this.returnTokens = true; - this.tokenStrict = Byot.DISABLE; + this.tokenMode = TokenMode.DISABLE; } public UpdateRequestBuilder table(String table) { @@ -67,8 +67,8 @@ public UpdateRequestBuilder tokens(HashMap tokens) { return this; } - public UpdateRequestBuilder tokenStrict(Byot tokenStrict) { - this.tokenStrict = tokenStrict == null ? Byot.DISABLE : tokenStrict; + public UpdateRequestBuilder tokenMode(TokenMode tokenStrict) { + this.tokenMode = tokenStrict == null ? TokenMode.DISABLE : tokenStrict; return this; } diff --git a/src/test/java/com/skyflow/config/ConnectionConfigTests.java b/src/test/java/com/skyflow/config/ConnectionConfigTests.java index 5ff32ca5..21b17838 100644 --- a/src/test/java/com/skyflow/config/ConnectionConfigTests.java +++ b/src/test/java/com/skyflow/config/ConnectionConfigTests.java @@ -3,19 +3,11 @@ import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.validations.Validations; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") public class ConnectionConfigTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; @@ -25,12 +17,7 @@ public class ConnectionConfigTests { private static Credentials credentials = null; @BeforeClass - public static void setup() throws SkyflowException, NoSuchMethodException { - PowerMockito.mockStatic(Token.class); - PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); - PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); - PowerMockito.mock(ApiClient.class); - + public static void setup() { connectionID = "connection123"; connectionURL = "https://connection.url.com"; invalidConnectionURL = "invalid.connection.url.com"; diff --git a/src/test/java/com/skyflow/config/CredentialsTests.java b/src/test/java/com/skyflow/config/CredentialsTests.java index cfc61de6..8093b2c2 100644 --- a/src/test/java/com/skyflow/config/CredentialsTests.java +++ b/src/test/java/com/skyflow/config/CredentialsTests.java @@ -3,22 +3,14 @@ import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.validations.Validations; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") public class CredentialsTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; @@ -32,12 +24,7 @@ public class CredentialsTests { private static String context = null; @BeforeClass - public static void setup() throws SkyflowException, NoSuchMethodException { - PowerMockito.mockStatic(Token.class); - PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); - PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); - PowerMockito.mock(ApiClient.class); - + public static void setup() { path = "valid-path-to-credentials-file"; credentialsString = "valid-credentials-string"; token = "valid-token"; diff --git a/src/test/java/com/skyflow/config/VaultConfigTests.java b/src/test/java/com/skyflow/config/VaultConfigTests.java index 1a5ca703..6bffa6d6 100644 --- a/src/test/java/com/skyflow/config/VaultConfigTests.java +++ b/src/test/java/com/skyflow/config/VaultConfigTests.java @@ -4,19 +4,11 @@ import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.validations.Validations; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") public class VaultConfigTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; @@ -26,12 +18,7 @@ public class VaultConfigTests { @BeforeClass - public static void setup() throws SkyflowException, NoSuchMethodException { - PowerMockito.mockStatic(Token.class); - PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); - PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); - PowerMockito.mock(ApiClient.class); - + public static void setup() { vaultID = "vault123"; clusterID = "cluster123"; diff --git a/src/test/java/com/skyflow/utils/UtilsTests.java b/src/test/java/com/skyflow/utils/UtilsTests.java index 79817bc5..8116046e 100644 --- a/src/test/java/com/skyflow/utils/UtilsTests.java +++ b/src/test/java/com/skyflow/utils/UtilsTests.java @@ -160,7 +160,7 @@ public void testConstructConnectionURL() { connectionConfig.setConnectionUrl(connectionUrl); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST).pathParams(pathParams).queryParams(queryParams).build(); + .method(RequestMethod.POST).pathParams(pathParams).queryParams(queryParams).build(); String filledUrl = Utils.constructConnectionURL(connectionConfig, request); Assert.assertEquals(connectionUrl + "?" + "query_param=value", filledUrl); } catch (Exception e) { diff --git a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java index 8d950279..7c6f6213 100644 --- a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java +++ b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java @@ -46,7 +46,7 @@ public void testValidInputInInvokeConnectionRequestValidations() { requestBody.put("key", "value"); try { InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -56,7 +56,7 @@ public void testValidInputInInvokeConnectionRequestValidations() { Assert.assertEquals(1, request.getQueryParams().size()); Assert.assertEquals(1, request.getPathParams().size()); Assert.assertEquals(1, request.getRequestHeaders().size()); - Assert.assertEquals(RequestMethod.POST, request.getMethodName()); + Assert.assertEquals(RequestMethod.POST, request.getMethod()); Assert.assertNotNull(request.getRequestBody()); } catch (SkyflowException e) { Assert.fail(INVALID_EXCEPTION_THROWN); @@ -67,7 +67,7 @@ public void testValidInputInInvokeConnectionRequestValidations() { public void testEmptyRequestHeadersInInvokeConnectionRequestValidations() { try { InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -87,7 +87,7 @@ public void testNullRequestHeaderKeyInInvokeConnectionRequestValidations() { requestHeaders.put("header1", "value1"); requestHeaders.put(null, "value2"); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -107,7 +107,7 @@ public void testEmptyRequestHeaderKeyInInvokeConnectionRequestValidations() { requestHeaders.put("header1", "value"); requestHeaders.put("", "value"); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -127,7 +127,7 @@ public void testNullRequestHeaderValueInInvokeConnectionRequestValidations() { requestHeaders.put("header1", "value"); requestHeaders.put("header2", null); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -147,7 +147,7 @@ public void testEmptyRequestHeaderValueInInvokeConnectionRequestValidations() { requestHeaders.put("header1", "value"); requestHeaders.put("header2", ""); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -166,7 +166,7 @@ public void testEmptyPathParamsInInvokeConnectionRequestValidations() { try { requestHeaders.put("header1", "value"); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -187,7 +187,7 @@ public void testNullPathParamKeyInInvokeConnectionRequestValidations() { pathParams.put("path_param", "value"); pathParams.put(null, "value"); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -208,7 +208,7 @@ public void testEmptyPathParamKeyInInvokeConnectionRequestValidations() { pathParams.put("path_param", "value"); pathParams.put("", "value"); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -229,7 +229,7 @@ public void testNullPathParamValueInInvokeConnectionRequestValidations() { pathParams.put("path_param1", "value"); pathParams.put("path_param2", null); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -250,7 +250,7 @@ public void testEmptyPathParamValueInInvokeConnectionRequestValidations() { pathParams.put("path_param1", "value"); pathParams.put("path_param2", ""); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -270,7 +270,7 @@ public void testEmptyQueryParamsInInvokeConnectionRequestValidations() { requestHeaders.put("header1", "value"); pathParams.put("path_param", "value"); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -292,7 +292,7 @@ public void testNullQueryParamKeyInInvokeConnectionRequestValidations() { queryParams.put("query_param", "value"); queryParams.put(null, "value"); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -314,7 +314,7 @@ public void testEmptyQueryParamKeyInInvokeConnectionRequestValidations() { queryParams.put("query_param", "value"); queryParams.put("", "value"); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -336,7 +336,7 @@ public void testNullQueryParamValueInInvokeConnectionRequestValidations() { queryParams.put("query_param1", "value"); queryParams.put("query_param2", null); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -358,7 +358,7 @@ public void testEmptyQueryParamValueInInvokeConnectionRequestValidations() { queryParams.put("query_param1", "value"); queryParams.put("query_param2", ""); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) @@ -379,7 +379,7 @@ public void testEmptyRequestBodyInInvokeConnectionRequestValidations() { pathParams.put("path_param", "value"); queryParams.put("query_param", "value"); InvokeConnectionRequest request = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) + .method(RequestMethod.POST) .requestHeaders(requestHeaders) .pathParams(pathParams) .queryParams(queryParams) diff --git a/src/test/java/com/skyflow/vault/data/DeleteTests.java b/src/test/java/com/skyflow/vault/data/DeleteTests.java index 8cb43880..a0401842 100644 --- a/src/test/java/com/skyflow/vault/data/DeleteTests.java +++ b/src/test/java/com/skyflow/vault/data/DeleteTests.java @@ -7,7 +7,6 @@ import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; @@ -15,15 +14,9 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") public class DeleteTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; @@ -35,11 +28,7 @@ public class DeleteTests { private static Skyflow skyflowClient = null; @BeforeClass - public static void setup() throws SkyflowException { - PowerMockito.mockStatic(Token.class); - PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); - PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); - + public static void setup() { vaultID = "vault123"; clusterID = "cluster123"; @@ -50,10 +39,6 @@ public static void setup() throws SkyflowException { vaultConfig.setVaultId(vaultID); vaultConfig.setClusterId(clusterID); vaultConfig.setEnv(Env.DEV); -// vaultConfig.setCredentials(credentials); - -// skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - skyflowID = "test_delete_id_1"; ids = new ArrayList<>(); table = "test_table"; diff --git a/src/test/java/com/skyflow/vault/data/GetTests.java b/src/test/java/com/skyflow/vault/data/GetTests.java index f9fa98d9..769ff868 100644 --- a/src/test/java/com/skyflow/vault/data/GetTests.java +++ b/src/test/java/com/skyflow/vault/data/GetTests.java @@ -8,7 +8,6 @@ import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; @@ -16,16 +15,10 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; import java.util.HashMap; -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") public class GetTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; @@ -42,10 +35,7 @@ public class GetTests { private static Skyflow skyflowClient = null; @BeforeClass - public static void setup() throws SkyflowException { - PowerMockito.mockStatic(Token.class); - PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); - PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); + public static void setup() { vaultID = "vault123"; clusterID = "cluster123"; @@ -59,8 +49,6 @@ public static void setup() throws SkyflowException { vaultConfig.setEnv(Env.DEV); vaultConfig.setCredentials(credentials); -// skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - skyflowID = "test_get_id_1"; ids = new ArrayList<>(); field = "test_get_field"; diff --git a/src/test/java/com/skyflow/vault/data/InsertTests.java b/src/test/java/com/skyflow/vault/data/InsertTests.java index 87057d7c..7b911bc1 100644 --- a/src/test/java/com/skyflow/vault/data/InsertTests.java +++ b/src/test/java/com/skyflow/vault/data/InsertTests.java @@ -3,12 +3,11 @@ import com.skyflow.Skyflow; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.Byot; +import com.skyflow.enums.TokenMode; import com.skyflow.enums.Env; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; @@ -16,16 +15,10 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; import java.util.HashMap; -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") public class InsertTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; @@ -40,10 +33,7 @@ public class InsertTests { private static Skyflow skyflowClient = null; @BeforeClass - public static void setup() throws SkyflowException { - PowerMockito.mockStatic(Token.class); - PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); - PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); + public static void setup() { vaultID = "vault123"; clusterID = "cluster123"; @@ -91,8 +81,7 @@ public void testValidInputInInsertRequestValidations() { .upsert(upsert) .values(values) .tokens(tokens) - .tokenMode(true) - .tokenStrict(Byot.ENABLE) + .tokenMode(TokenMode.ENABLE) .build(); Validations.validateInsertRequest(request); @@ -100,10 +89,9 @@ public void testValidInputInInsertRequestValidations() { Assert.assertEquals(upsert, request.getUpsert()); Assert.assertEquals(1, request.getValues().size()); Assert.assertEquals(1, request.getTokens().size()); - Assert.assertEquals(Byot.ENABLE, request.getTokenStrict()); + Assert.assertEquals(TokenMode.ENABLE, request.getTokenMode()); Assert.assertTrue(request.getContinueOnError()); Assert.assertTrue(request.getReturnTokens()); - Assert.assertTrue(request.getTokenMode()); Assert.assertFalse(request.getHomogeneous()); } catch (SkyflowException e) { Assert.fail(INVALID_EXCEPTION_THROWN); @@ -248,7 +236,7 @@ public void testTokensWithTokenStrictDisableInInsertRequestValidations() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.TokensPassedForByotDisable.getMessage(), Constants.SDK_PREFIX), + Utils.parameterizedString(ErrorMessage.TokensPassedForTokenModeDisable.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); } @@ -258,7 +246,7 @@ public void testTokensWithTokenStrictDisableInInsertRequestValidations() { public void testNoTokensWithTokenStrictEnableInInsertRequestValidations() { values.add(valueMap); InsertRequest request = InsertRequest.builder() - .table(table).values(values).tokenStrict(Byot.ENABLE) + .table(table).values(values).tokenMode(TokenMode.ENABLE) .build(); try { Validations.validateInsertRequest(request); @@ -266,7 +254,7 @@ public void testNoTokensWithTokenStrictEnableInInsertRequestValidations() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE.toString()), + Utils.parameterizedString(ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE.toString()), e.getMessage() ); } @@ -276,7 +264,7 @@ public void testNoTokensWithTokenStrictEnableInInsertRequestValidations() { public void testNoTokensWithTokenStrictEnableStrictInInsertRequestValidations() { values.add(valueMap); InsertRequest request = InsertRequest.builder() - .table(table).values(values).tokenStrict(Byot.ENABLE_STRICT) + .table(table).values(values).tokenMode(TokenMode.ENABLE_STRICT) .build(); try { Validations.validateInsertRequest(request); @@ -284,7 +272,7 @@ public void testNoTokensWithTokenStrictEnableStrictInInsertRequestValidations() } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString()), + Utils.parameterizedString(ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE_STRICT.toString()), e.getMessage() ); } @@ -294,7 +282,7 @@ public void testNoTokensWithTokenStrictEnableStrictInInsertRequestValidations() public void testEmptyTokensWithTokenStrictEnableInInsertRequestValidations() { values.add(valueMap); InsertRequest request = InsertRequest.builder() - .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE) + .table(table).values(values).tokens(tokens).tokenMode(TokenMode.ENABLE) .build(); try { Validations.validateInsertRequest(request); @@ -310,14 +298,14 @@ public void testInsufficientTokensWithTokenStrictEnableStrictInInsertRequestVali values.add(valueMap); tokens.add(tokenMap); InsertRequest request = InsertRequest.builder() - .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) + .table(table).values(values).tokens(tokens).tokenMode(TokenMode.ENABLE_STRICT) .build(); try { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage(), e.getMessage()); + Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForTokenModeEnableStrict.getMessage(), e.getMessage()); } } @@ -327,14 +315,14 @@ public void testInsufficientTokensWithTokenStrictEnableStrictInInsertRequestVali values.add(valueMap); tokens.add(tokenMap); InsertRequest request = InsertRequest.builder() - .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) + .table(table).values(values).tokens(tokens).tokenMode(TokenMode.ENABLE_STRICT) .build(); try { Validations.validateInsertRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage(), e.getMessage()); + Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForTokenModeEnableStrict.getMessage(), e.getMessage()); } } @@ -344,7 +332,7 @@ public void testTokenValueMismatchInInsertRequestValidations() { tokenMap.put("test_column_3", "test_token_3"); tokens.add(tokenMap); InsertRequest request = InsertRequest.builder() - .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) + .table(table).values(values).tokens(tokens).tokenMode(TokenMode.ENABLE_STRICT) .build(); try { Validations.validateInsertRequest(request); @@ -361,7 +349,7 @@ public void testEmptyKeyInTokensInInsertRequestValidations() { values.add(valueMap); tokens.add(tokenMap); InsertRequest request = InsertRequest.builder() - .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) + .table(table).values(values).tokens(tokens).tokenMode(TokenMode.ENABLE_STRICT) .build(); try { Validations.validateInsertRequest(request); @@ -378,7 +366,7 @@ public void testEmptyValueInTokensInInsertRequestValidations() { values.add(valueMap); tokens.add(tokenMap); InsertRequest request = InsertRequest.builder() - .table(table).values(values).tokens(tokens).tokenStrict(Byot.ENABLE_STRICT) + .table(table).values(values).tokens(tokens).tokenMode(TokenMode.ENABLE_STRICT) .build(); try { Validations.validateInsertRequest(request); diff --git a/src/test/java/com/skyflow/vault/data/QueryTests.java b/src/test/java/com/skyflow/vault/data/QueryTests.java index 82b8499a..a18a45cf 100644 --- a/src/test/java/com/skyflow/vault/data/QueryTests.java +++ b/src/test/java/com/skyflow/vault/data/QueryTests.java @@ -7,23 +7,16 @@ import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; import java.util.HashMap; -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") public class QueryTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; @@ -34,11 +27,7 @@ public class QueryTests { private static HashMap queryRecord = null; @BeforeClass - public static void setup() throws SkyflowException { - PowerMockito.mockStatic(Token.class); - PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); - PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); - + public static void setup() { vaultID = "vault123"; clusterID = "cluster123"; @@ -55,8 +44,6 @@ public static void setup() throws SkyflowException { queryRecord = new HashMap<>(); queryRecord.put("name", "test_name"); queryRecord.put("card_number", "test_card_number"); - -// skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); } @Test diff --git a/src/test/java/com/skyflow/vault/data/UpdateTests.java b/src/test/java/com/skyflow/vault/data/UpdateTests.java index d323dcee..c23977c6 100644 --- a/src/test/java/com/skyflow/vault/data/UpdateTests.java +++ b/src/test/java/com/skyflow/vault/data/UpdateTests.java @@ -3,12 +3,11 @@ import com.skyflow.Skyflow; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.Byot; +import com.skyflow.enums.TokenMode; import com.skyflow.enums.Env; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; @@ -16,15 +15,9 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; import java.util.HashMap; -@RunWith(PowerMockRunner.class) -@PrepareForTest(fullyQualifiedNames = "com.skyflow.serviceaccount.util.Token") public class UpdateTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; @@ -37,11 +30,7 @@ public class UpdateTests { private static Skyflow skyflowClient = null; @BeforeClass - public static void setup() throws SkyflowException { - PowerMockito.mockStatic(Token.class); - PowerMockito.when(Token.isExpired("valid_token")).thenReturn(true); - PowerMockito.when(Token.isExpired("not_a_valid_token")).thenReturn(false); - + public static void setup() { vaultID = "vault123"; clusterID = "cluster123"; @@ -78,7 +67,7 @@ public void testValidInputInUpdateRequestValidations() { .data(dataMap) .tokens(tokenMap) .returnTokens(true) - .tokenStrict(Byot.ENABLE) + .tokenMode(TokenMode.ENABLE) .build(); Validations.validateUpdateRequest(request); Assert.assertEquals(table, request.getTable()); @@ -243,7 +232,7 @@ public void testTokensWithTokenStrictDisableInUpdateRequestValidations() { dataMap.put("test_column_2", "test_value_2"); tokenMap.put("test_column_1", "test_token_1"); UpdateRequest request = UpdateRequest.builder() - .table(table).data(dataMap).tokens(tokenMap).tokenStrict(Byot.DISABLE) + .table(table).data(dataMap).tokens(tokenMap).tokenMode(TokenMode.DISABLE) .build(); try { Validations.validateUpdateRequest(request); @@ -251,7 +240,7 @@ public void testTokensWithTokenStrictDisableInUpdateRequestValidations() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.TokensPassedForByotDisable.getMessage(), Constants.SDK_PREFIX), + Utils.parameterizedString(ErrorMessage.TokensPassedForTokenModeDisable.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); } @@ -263,7 +252,7 @@ public void testNoTokensWithTokenStrictEnableInUpdateRequestValidations() { dataMap.put("test_column_1", "test_value_1"); dataMap.put("test_column_2", "test_value_2"); UpdateRequest request = UpdateRequest.builder() - .table(table).data(dataMap).tokenStrict(Byot.ENABLE) + .table(table).data(dataMap).tokenMode(TokenMode.ENABLE) .build(); try { Validations.validateUpdateRequest(request); @@ -271,7 +260,7 @@ public void testNoTokensWithTokenStrictEnableInUpdateRequestValidations() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE.toString()), + Utils.parameterizedString(ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE.toString()), e.getMessage() ); } @@ -283,7 +272,7 @@ public void testNoTokensWithTokenStrictEnableStrictInUpdateRequestValidations() dataMap.put("test_column_1", "test_value_1"); dataMap.put("test_column_2", "test_value_2"); UpdateRequest request = UpdateRequest.builder() - .table(table).data(dataMap).tokenStrict(Byot.ENABLE_STRICT) + .table(table).data(dataMap).tokenMode(TokenMode.ENABLE_STRICT) .build(); try { Validations.validateUpdateRequest(request); @@ -291,7 +280,7 @@ public void testNoTokensWithTokenStrictEnableStrictInUpdateRequestValidations() } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString()), + Utils.parameterizedString(ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE_STRICT.toString()), e.getMessage() ); } @@ -303,7 +292,7 @@ public void testEmptyTokensWithTokenStrictEnableInUpdateRequestValidations() { dataMap.put("test_column_1", "test_value_1"); dataMap.put("test_column_2", "test_value_2"); UpdateRequest request = UpdateRequest.builder() - .table(table).data(dataMap).tokens(tokenMap).tokenStrict(Byot.ENABLE) + .table(table).data(dataMap).tokens(tokenMap).tokenMode(TokenMode.ENABLE) .build(); try { Validations.validateUpdateRequest(request); @@ -321,14 +310,14 @@ public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestVali dataMap.put("test_column_2", "test_value_2"); tokenMap.put("test_column_1", "test_token_1"); UpdateRequest request = UpdateRequest.builder() - .table(table).data(dataMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) + .table(table).data(dataMap).tokens(tokenMap).tokenMode(TokenMode.ENABLE_STRICT) .build(); try { Validations.validateUpdateRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage(), e.getMessage()); + Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForTokenModeEnableStrict.getMessage(), e.getMessage()); } } @@ -340,7 +329,7 @@ public void testTokenValueMismatchInUpdateRequestValidations() { tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("test_column_3", "test_token_3"); UpdateRequest request = UpdateRequest.builder() - .table(table).data(dataMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) + .table(table).data(dataMap).tokens(tokenMap).tokenMode(TokenMode.ENABLE_STRICT) .build(); try { Validations.validateUpdateRequest(request); @@ -359,7 +348,7 @@ public void testEmptyKeyInTokensInUpdateRequestValidations() { tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("", "test_token_2"); UpdateRequest request = UpdateRequest.builder() - .table(table).data(dataMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) + .table(table).data(dataMap).tokens(tokenMap).tokenMode(TokenMode.ENABLE_STRICT) .build(); try { Validations.validateUpdateRequest(request); @@ -378,7 +367,7 @@ public void testEmptyValueInTokensInUpdateRequestValidations() { tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("test_column_2", ""); UpdateRequest request = UpdateRequest.builder() - .table(table).data(dataMap).tokens(tokenMap).tokenStrict(Byot.ENABLE_STRICT) + .table(table).data(dataMap).tokens(tokenMap).tokenMode(TokenMode.ENABLE_STRICT) .build(); try { Validations.validateUpdateRequest(request); From a3bb74deadb383b174028469ac22c78c81ede810 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 26 Nov 2024 12:38:47 +0530 Subject: [PATCH 072/126] SK-1786 common workflow for internal and public release --- .github/workflows/internal-release.yml | 63 +---------- .github/workflows/release.yml | 33 +----- .github/workflows/shared-build-and-deploy.yml | 104 ++++++++++++++++++ pom.xml | 26 +++-- 4 files changed, 129 insertions(+), 97 deletions(-) create mode 100644 .github/workflows/shared-build-and-deploy.yml diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index 5d82fda1..8219984e 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -9,61 +9,8 @@ on: - release/* jobs: - publish: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - with: - ref: ${{ github.ref_name }} - fetch-depth: 0 - - - name: Set up Jfrog artifactory - uses: actions/setup-java@v1 - with: - java-version: '1.8' - distribution: 'adopt' - server-id: central - server-username: JFROG_USERNAME - server-password: JFROG_PASSWORD - gpg-private-key: ${{ secrets.JFROG_GPG_KEY }} # Value of the GPG private key to import - gpg-passphrase: JFROG_GPG_PASSPHRASE # env variable for GPG private key passphrase - - - name: Get Previous tag - id: previoustag - uses: WyriHaximus/github-action-get-previous-tag@v1 - with: - fallback: 1.0.0 - - - name: Bump Version - run: | - chmod +x ./scripts/bump_version.sh - ./scripts/bump_version.sh "${{ steps.previoustag.outputs.tag }}" "$(git rev-parse --short "$GITHUB_SHA")" - - - name: Commit changes - run: | - git config user.name ${{ github.actor }} - git config user.email ${{ github.actor }}@users.noreply.github.com - git add pom.xml - git commit -m "[AUTOMATED] Private Release ${{ steps.previoustag.outputs.tag }}-dev.$(git rev-parse --short $GITHUB_SHA)" - git push origin -f - - - name: Create env - id: create-env - run: | - touch .env - echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env - echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env - - - name: Create credentials json - id: create-json - uses: jsdaniell/create-json@1.1.2 - with: - name: "credentials.json" - json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - - - name: Publish package to Jfrog Artifactory - run: mvn clean deploy -P jfrog - env: - JFROG_USERNAME: ${{ secrets.ARTIFACTORY_USERNAME }} - JFROG_PASSWORD: ${{ secrets.ARTIFACTORY_PASSWORD }} - JFROG_GPG_PASSPHRASE: ${{ secrets.JFROG_GPG_PASSPHRASE }} \ No newline at end of file + build-and-deploy: + uses: ./.github/workflows/shared-build-and-deploy.yml + with: + ref: ${{ github.ref_name }} + is-internal: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f30dda26..c2fb42d5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,31 +3,8 @@ on: push: tags: '*.*.*' jobs: - publish: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - name: Set up Maven Central Repository - uses: actions/setup-java@v1 - with: - java-version: '1.8' - distribution: 'adopt' - server-id: ossrh - server-username: MAVEN_USERNAME - server-password: MAVEN_PASSWORD - gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import - gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase - - - name: create-json - id: create-json - uses: jsdaniell/create-json@1.1.2 - with: - name: "credentials.json" - json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - - - name: Publish package to Maven Central - run: mvn --batch-mode deploy -P maven-central - env: - MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} - MAVEN_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} - MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} \ No newline at end of file + build-and-deploy: + uses: ./.github/workflows/shared-build-and-deploy.yml + with: + ref: ${{ github.ref_name }} + is-internal: false diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml new file mode 100644 index 00000000..9dc71d5e --- /dev/null +++ b/.github/workflows/shared-build-and-deploy.yml @@ -0,0 +1,104 @@ +name: Shared Build and Deploy +on: + workflow_call: + inputs: + ref: + description: 'Git reference to use (e.g., main or branch name)' + required: true + type: string + + is-internal: + description: 'Flag for internal release' + required: true + type: boolean + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + ref: ${{ inputs.ref }} + fetch-depth: 0 + + - name: Set up Jfrog artifactory + if: ${{ inputs.is-internal }} + uses: actions/setup-java@v1 + with: + java-version: '1.8' + distribution: 'adopt' + server-id: central + server-username: JFROG_USERNAME + server-password: JFROG_PASSWORD + gpg-private-key: ${{ secrets.JFROG_GPG_KEY }} # Value of the GPG private key to import + gpg-passphrase: JFROG_GPG_PASSPHRASE # env variable for GPG private key passphrase + + - name: Set up Maven Central Repository + if: ${{ !inputs.is-internal }} + uses: actions/setup-java@v1 + with: + java-version: '1.8' + distribution: 'adopt' + server-id: ossrh + server-username: MAVEN_USERNAME + server-password: MAVEN_PASSWORD + gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import + gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase + + - name: Get Previous tag + id: previoustag + uses: WyriHaximus/github-action-get-previous-tag@v1 + with: + fallback: 1.0.0 + + - name: Bump Version + run: | + chmod +x ./ci-scripts/bump_version.sh + if ${{ inputs.is-internal }}; then + ./ci-scripts/bump_version.sh "${{ steps.previoustag.outputs.tag }}" "$(git rev-parse --short "$GITHUB_SHA")" + else + ./ci-scripts/bump_version.sh "${{ steps.previoustag.outputs.tag }}" + fi + + - name: Commit changes + run: | + git config user.name ${{ github.actor }} + git config user.email ${{ github.actor }}@users.noreply.github.com + git add pom.xml + if ${{ inputs.is-internal }}; then + git commit -m "[AUTOMATED] Private Release ${{ steps.previoustag.outputs.tag }}-dev-$(git rev-parse --short $GITHUB_SHA)" + git push origin ${{ github.ref_name }} -f + else + git commit -m "[AUTOMATED] Public Release - ${{ steps.previoustag.outputs.tag }}" + git push origin + + - name: Create env + if: ${{ inputs.is-internal }} + id: create-env + run: | + touch .env + echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env + echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + + - name: Create credentials json + id: create-json + uses: jsdaniell/create-json@1.1.2 + with: + name: "credentials.json" + json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} + + - name: Publish package to Jfrog Artifactory + if: ${{ inputs.is-internal }} + run: mvn clean deploy -P jfrog + env: + JFROG_USERNAME: ${{ secrets.ARTIFACTORY_USERNAME }} + JFROG_PASSWORD: ${{ secrets.ARTIFACTORY_PASSWORD }} + JFROG_GPG_PASSPHRASE: ${{ secrets.JFROG_GPG_PASSPHRASE }} + + - name: Publish package to Maven Central + if: ${{ !inputs.is-internal }} + run: mvn --batch-mode deploy -P maven-central + env: + MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 08afca20..c36c539b 100644 --- a/pom.xml +++ b/pom.xml @@ -121,17 +121,6 @@ - - - - - - - - - - - org.apache.maven.plugins maven-source-plugin @@ -255,6 +244,21 @@ https://s01.oss.sonatype.org/content/repositories/snapshots + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.7 + true + + ossrh + https://s01.oss.sonatype.org/ + true + + + + jfrog From 525bbb8c6501bb03fac41196c5f902a73e274bc5 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 26 Nov 2024 17:52:18 +0530 Subject: [PATCH 073/126] SK-1789 common workflow for public and internal release v2 --- .github/workflows/internal-release.yml | 6 ++ .github/workflows/release.yml | 6 ++ .github/workflows/shared-build-and-deploy.yml | 75 +++++++++++-------- 3 files changed, 54 insertions(+), 33 deletions(-) diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index 8219984e..c2cace08 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -14,3 +14,9 @@ jobs: with: ref: ${{ github.ref_name }} is-internal: true + server-id: central + server-username: ${{ secrets.ARTIFACTORY_USERNAME }} + server-password: ${{ secrets.ARTIFACTORY_PASSWORD }} + gpg-key: ${{ secrets.JFROG_GPG_KEY }} + gpg-passphrase: ${{ secrets.JFROG_GPG_PASSPHRASE }} + profile: jfrog diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c2fb42d5..9b6f0aab 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -8,3 +8,9 @@ jobs: with: ref: ${{ github.ref_name }} is-internal: false + server-id: ossrh + server-username: ${{ secrets.OSSRH_USERNAME }} + server-password: ${{ secrets.OSSRH_PASSWORD }} + gpg-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} + gpg-passphrase: ${{ secrets.MAVEN_GPG_PASSPHRASE }} + profile: maven-central \ No newline at end of file diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index 9dc71d5e..10b7324c 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -12,6 +12,36 @@ on: required: true type: boolean + server-id: + description: 'Id of the repository' + required: true + type: string + + server-username: + description: 'Username of the repository' + required: true + type: string + + server-password: + description: 'Password of the repository' + required: true + type: string + + gpg-key: + description: 'GPG key to access the repository' + required: true + type: string + + gpg-passphrase: + description: 'GPG passphrase to access the repository' + required: true + type: string + + profile: + description: 'Profile to pick from pom.xml' + required: true + type: string + jobs: publish: runs-on: ubuntu-latest @@ -21,29 +51,16 @@ jobs: ref: ${{ inputs.ref }} fetch-depth: 0 - - name: Set up Jfrog artifactory - if: ${{ inputs.is-internal }} + - name: Set up maven or jfrog repository uses: actions/setup-java@v1 with: java-version: '1.8' distribution: 'adopt' - server-id: central - server-username: JFROG_USERNAME - server-password: JFROG_PASSWORD - gpg-private-key: ${{ secrets.JFROG_GPG_KEY }} # Value of the GPG private key to import - gpg-passphrase: JFROG_GPG_PASSPHRASE # env variable for GPG private key passphrase - - - name: Set up Maven Central Repository - if: ${{ !inputs.is-internal }} - uses: actions/setup-java@v1 - with: - java-version: '1.8' - distribution: 'adopt' - server-id: ossrh - server-username: MAVEN_USERNAME - server-password: MAVEN_PASSWORD - gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import - gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase + server-id: ${{ inputs.server-id }} + server-username: SERVER_USERNAME + server-password: SERVER_PASSWORD + gpg-private-key: ${{ inputs.gpg-key }} # Value of the GPG private key to import + gpg-passphrase: GPG_PASSPHRASE # env variable for GPG private key passphrase - name: Get Previous tag id: previoustag @@ -87,18 +104,10 @@ jobs: name: "credentials.json" json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - - name: Publish package to Jfrog Artifactory - if: ${{ inputs.is-internal }} - run: mvn clean deploy -P jfrog - env: - JFROG_USERNAME: ${{ secrets.ARTIFACTORY_USERNAME }} - JFROG_PASSWORD: ${{ secrets.ARTIFACTORY_PASSWORD }} - JFROG_GPG_PASSPHRASE: ${{ secrets.JFROG_GPG_PASSPHRASE }} - - - name: Publish package to Maven Central - if: ${{ !inputs.is-internal }} - run: mvn --batch-mode deploy -P maven-central + - name: Publish package + run: mvn clean deploy -P ${{ inputs.profile }} env: - MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} - MAVEN_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} - MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} \ No newline at end of file + SERVER_USERNAME: ${{ inputs.server-username }} + SERVER_PASSWORD: ${{ inputs.server-password }} + GPG_PASSPHRASE: ${{ inputs.gpg-passphrase }} + \ No newline at end of file From 0b33663811da11a6468105120e6ebfe731beea26 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 26 Nov 2024 20:37:24 +0530 Subject: [PATCH 074/126] SK-1786 test common workflow --- .github/workflows/internal-release.yml | 5 +++- .github/workflows/shared-build-and-deploy.yml | 29 +++++++------------ 2 files changed, 14 insertions(+), 20 deletions(-) diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index c2cace08..a354c5cc 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -15,8 +15,11 @@ jobs: ref: ${{ github.ref_name }} is-internal: true server-id: central + profile: jfrog + secrets: server-username: ${{ secrets.ARTIFACTORY_USERNAME }} server-password: ${{ secrets.ARTIFACTORY_PASSWORD }} gpg-key: ${{ secrets.JFROG_GPG_KEY }} gpg-passphrase: ${{ secrets.JFROG_GPG_PASSPHRASE }} - profile: jfrog + + diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index 10b7324c..10ee9c9f 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -16,31 +16,23 @@ on: description: 'Id of the repository' required: true type: string - - server-username: - description: 'Username of the repository' + + profile: + description: 'Profile to pick from pom.xml' required: true type: string + secrets: + server-username: + required: true server-password: - description: 'Password of the repository' required: true - type: string gpg-key: - description: 'GPG key to access the repository' required: true - type: string gpg-passphrase: - description: 'GPG passphrase to access the repository' required: true - type: string - - profile: - description: 'Profile to pick from pom.xml' - required: true - type: string jobs: publish: @@ -59,7 +51,7 @@ jobs: server-id: ${{ inputs.server-id }} server-username: SERVER_USERNAME server-password: SERVER_PASSWORD - gpg-private-key: ${{ inputs.gpg-key }} # Value of the GPG private key to import + gpg-private-key: ${{ secrets.gpg-key }} # Value of the GPG private key to import gpg-passphrase: GPG_PASSPHRASE # env variable for GPG private key passphrase - name: Get Previous tag @@ -107,7 +99,6 @@ jobs: - name: Publish package run: mvn clean deploy -P ${{ inputs.profile }} env: - SERVER_USERNAME: ${{ inputs.server-username }} - SERVER_PASSWORD: ${{ inputs.server-password }} - GPG_PASSPHRASE: ${{ inputs.gpg-passphrase }} - \ No newline at end of file + SERVER_USERNAME: ${{ secrets.server-username }} + SERVER_PASSWORD: ${{ secrets.server-password }} + GPG_PASSPHRASE: ${{ secrets.gpg-passphrase }} From 8958b9c173ab08504d14bbefa635fdf76571b12a Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 26 Nov 2024 21:25:17 +0530 Subject: [PATCH 075/126] SK-1786 modify scripts path in workflow --- .github/workflows/shared-build-and-deploy.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index 10ee9c9f..9d726d26 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -62,11 +62,11 @@ jobs: - name: Bump Version run: | - chmod +x ./ci-scripts/bump_version.sh + chmod +x ./scripts/bump_version.sh if ${{ inputs.is-internal }}; then - ./ci-scripts/bump_version.sh "${{ steps.previoustag.outputs.tag }}" "$(git rev-parse --short "$GITHUB_SHA")" + ./scripts/bump_version.sh "${{ steps.previoustag.outputs.tag }}" "$(git rev-parse --short "$GITHUB_SHA")" else - ./ci-scripts/bump_version.sh "${{ steps.previoustag.outputs.tag }}" + ./scripts/bump_version.sh "${{ steps.previoustag.outputs.tag }}" fi - name: Commit changes From ea0d117a1ab15215effe33187d2d9141eddadef8 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 26 Nov 2024 21:40:08 +0530 Subject: [PATCH 076/126] SK-1786 fix commit step --- .github/workflows/shared-build-and-deploy.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index 9d726d26..0dca78f0 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -80,6 +80,7 @@ jobs: else git commit -m "[AUTOMATED] Public Release - ${{ steps.previoustag.outputs.tag }}" git push origin + fi - name: Create env if: ${{ inputs.is-internal }} From 7c1671ceed121a0e94d5347840c7f680461b3087 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 26 Nov 2024 16:23:23 +0000 Subject: [PATCH 077/126] [AUTOMATED] Private Release 1.15.0-dev-f6c7f07 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c36c539b..9fa13707 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0 + 1.15.0-dev.f6c7f07 jar ${project.groupId}:${project.artifactId} From e3847c2a1abcb632ca6512b06ce9ff8a1c06f471 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 26 Nov 2024 22:01:03 +0530 Subject: [PATCH 078/126] SK-1786 include secrets from github --- .github/workflows/release.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9b6f0aab..7b6c57de 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -9,8 +9,10 @@ jobs: ref: ${{ github.ref_name }} is-internal: false server-id: ossrh + profile: maven-central + secrets: server-username: ${{ secrets.OSSRH_USERNAME }} server-password: ${{ secrets.OSSRH_PASSWORD }} gpg-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} gpg-passphrase: ${{ secrets.MAVEN_GPG_PASSPHRASE }} - profile: maven-central \ No newline at end of file + \ No newline at end of file From 4ea53e6658e514624dfa5dc99e5eb902769093af Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 26 Nov 2024 22:17:51 +0530 Subject: [PATCH 079/126] SK-1786 modify pattern in commit message check --- .github/workflows/pr.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index a2d39562..da765524 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -10,12 +10,12 @@ jobs: - name: Check JIRA ID uses: gsactions/commit-message-checker@v1 with: - pattern: '\[?[A-Z]{1,5}-[1-9][0-9]*.+$' - flags: "gm" - excludeDescription: "true" - checkAllCommitMessages: "true" + pattern: '(\[?[A-Z]{1,5}-[1-9][0-9]*)|(\[AUTOMATED\])|(Merge)|(Release).+$' + flags: 'gm' + excludeDescription: 'true' + checkAllCommitMessages: 'true' accessToken: ${{ secrets.PAT_ACTIONS }} - error: "One of your your commit messages is not matching the format with JIRA ID Ex: ( SDK-123 commit message )" + error: 'One of your your commit messages is not matching the format with JIRA ID Ex: ( SDK-123 commit message )' Test: runs-on: ubuntu-latest steps: From 0a777cec91c369eb6afd3a6b0281e274cea041e9 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Tue, 26 Nov 2024 16:48:47 +0000 Subject: [PATCH 080/126] [AUTOMATED] Private Release 1.15.0-dev-4ea53e6 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 9fa13707..2801b615 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0-dev.f6c7f07 + 1.15.0-dev.4ea53e6 jar ${project.groupId}:${project.artifactId} From f015151c6af4358ad41d5f933259ca7775877072 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 5 Dec 2024 17:38:30 +0530 Subject: [PATCH 081/126] SK-1802 Fix inconsistencies in SDK v2 --- src/main/java/com/skyflow/VaultClient.java | 11 ++- .../java/com/skyflow/errors/ErrorMessage.java | 2 +- .../java/com/skyflow/utils/Constants.java | 8 ++ src/main/java/com/skyflow/utils/Utils.java | 83 +++++++++++++---- .../connection/InvokeConnectionResponse.java | 13 ++- .../controller/ConnectionController.java | 6 +- .../vault/controller/VaultController.java | 88 ++++++------------- .../skyflow/vault/data/DeleteResponse.java | 24 ++--- .../com/skyflow/vault/data/GetResponse.java | 29 +----- .../skyflow/vault/data/InsertResponse.java | 39 ++------ .../com/skyflow/vault/data/QueryResponse.java | 33 ++----- .../skyflow/vault/data/UpdateResponse.java | 25 +++--- .../tokens/DetokenizeRecordResponse.java | 18 +--- .../vault/tokens/DetokenizeResponse.java | 21 ++--- .../vault/tokens/TokenizeResponse.java | 12 ++- src/test/java/com/skyflow/SkyflowTests.java | 2 - .../java/com/skyflow/utils/UtilsTests.java | 32 +++++++ .../connection/InvokeConnectionTests.java | 4 +- .../com/skyflow/vault/data/DeleteTests.java | 2 +- .../java/com/skyflow/vault/data/GetTests.java | 12 +-- .../com/skyflow/vault/data/InsertTests.java | 14 +-- .../com/skyflow/vault/data/QueryTests.java | 9 +- .../com/skyflow/vault/data/UpdateTests.java | 6 +- .../skyflow/vault/tokens/DetokenizeTests.java | 11 +-- .../skyflow/vault/tokens/TokenizeTests.java | 2 +- 25 files changed, 246 insertions(+), 260 deletions(-) diff --git a/src/main/java/com/skyflow/VaultClient.java b/src/main/java/com/skyflow/VaultClient.java index 2f415f4f..f35504be 100644 --- a/src/main/java/com/skyflow/VaultClient.java +++ b/src/main/java/com/skyflow/VaultClient.java @@ -23,6 +23,7 @@ import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; import io.github.cdimascio.dotenv.Dotenv; +import io.github.cdimascio.dotenv.DotenvException; import java.util.ArrayList; import java.util.HashMap; @@ -44,6 +45,7 @@ protected VaultClient(VaultConfig vaultConfig, Credentials credentials) { this.vaultConfig = vaultConfig; this.commonCredentials = credentials; this.apiClient = new ApiClient(); + apiClient.addDefaultHeader(Constants.SDK_METRICS_HEADER_KEY, Utils.getMetrics().toString()); this.recordsApi = new RecordsApi(this.apiClient); this.tokensApi = new TokensApi(this.apiClient); this.queryApi = new QueryApi(this.apiClient); @@ -70,12 +72,12 @@ protected VaultConfig getVaultConfig() { return vaultConfig; } - protected void setCommonCredentials(Credentials commonCredentials) { + protected void setCommonCredentials(Credentials commonCredentials) throws SkyflowException { this.commonCredentials = commonCredentials; prioritiseCredentials(); } - protected void updateVaultConfig() { + protected void updateVaultConfig() throws SkyflowException { updateVaultURL(); prioritiseCredentials(); } @@ -197,7 +199,7 @@ private void updateVaultURL() { this.apiClient.setBasePath(vaultURL); } - private void prioritiseCredentials() { + private void prioritiseCredentials() throws SkyflowException { try { if (this.vaultConfig.getCredentials() != null) { this.finalCredentials = this.vaultConfig.getCredentials(); @@ -216,6 +218,9 @@ private void prioritiseCredentials() { } token = null; apiKey = null; + } catch (DotenvException e) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.EmptyCredentials.getMessage()); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/src/main/java/com/skyflow/errors/ErrorMessage.java b/src/main/java/com/skyflow/errors/ErrorMessage.java index 81516e94..e1034976 100644 --- a/src/main/java/com/skyflow/errors/ErrorMessage.java +++ b/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -8,7 +8,7 @@ public enum ErrorMessage { VaultIdNotInConfigList("%s0 Validation error. VaultId is missing from the config. Specify the vaultIds from configs."), ConnectionIdAlreadyInConfigList("%s0 Validation error. ConnectionId is present in an existing config. Specify a connectionId in config."), ConnectionIdNotInConfigList("%s0 Validation error. ConnectionId is missing from the config. Specify the connectionIds from configs."), - EmptyCredentials("%s0 Validation error. Invalid credentials. Specify a valid credentials."), + EmptyCredentials("%s0 Validation error. Invalid credentials. Credentials must not be empty."), // vault config InvalidVaultId("%s0 Initialization failed. Invalid vault ID. Specify a valid vault ID."), diff --git a/src/main/java/com/skyflow/utils/Constants.java b/src/main/java/com/skyflow/utils/Constants.java index f7c378f5..3ce68c79 100644 --- a/src/main/java/com/skyflow/utils/Constants.java +++ b/src/main/java/com/skyflow/utils/Constants.java @@ -16,4 +16,12 @@ public final class Constants { public static final String SDK_NAME = "Skyflow Java SDK "; public static final String SDK_VERSION = "v2"; public static final String SDK_PREFIX = SDK_NAME + SDK_VERSION; + public static final String SDK_METRIC_NAME_VERSION = "sdk_name_version"; + public static final String SDK_METRIC_NAME_VERSION_PREFIX = "skyflow-java@"; + public static final String SDK_METRIC_CLIENT_DEVICE_MODEL = "sdk_client_device_model"; + public static final String SDK_METRIC_CLIENT_OS_DETAILS = "sdk_client_os_details"; + public static final String SDK_METRIC_RUNTIME_DETAILS = "sdk_runtime_details"; + public static final String SDK_METRIC_RUNTIME_DETAILS_PREFIX = "Java@"; + public static final String SDK_AUTH_HEADER_KEY = "x-skyflow-authorization"; + public static final String SDK_METRICS_HEADER_KEY = "sky-metadata"; } diff --git a/src/main/java/com/skyflow/utils/Utils.java b/src/main/java/com/skyflow/utils/Utils.java index 66e50b5a..cc8d572a 100644 --- a/src/main/java/com/skyflow/utils/Utils.java +++ b/src/main/java/com/skyflow/utils/Utils.java @@ -1,5 +1,6 @@ package com.skyflow.utils; +import com.google.gson.JsonObject; import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; import com.skyflow.enums.Env; @@ -7,6 +8,7 @@ import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.logs.ErrorLogs; +import com.skyflow.logs.InfoLogs; import com.skyflow.serviceaccount.util.BearerToken; import com.skyflow.utils.logger.LogUtil; import com.skyflow.vault.connection.InvokeConnectionRequest; @@ -99,23 +101,6 @@ public static String parameterizedString(String base, String... args) { return base; } - private static PrivateKey parsePkcs8PrivateKey(byte[] pkcs8Bytes) throws SkyflowException { - KeyFactory keyFactory; - PrivateKey privateKey = null; - try { - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8Bytes); - keyFactory = KeyFactory.getInstance("RSA"); - privateKey = keyFactory.generatePrivate(keySpec); - } catch (NoSuchAlgorithmException e) { - LogUtil.printErrorLog(ErrorLogs.INVALID_ALGORITHM.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidAlgorithm.getMessage()); - } catch (InvalidKeySpecException e) { - LogUtil.printErrorLog(ErrorLogs.INVALID_KEY_SPEC.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidKeySpec.getMessage()); - } - return privateKey; - } - public static String constructConnectionURL(ConnectionConfig config, InvokeConnectionRequest invokeConnectionRequest) { StringBuilder filledURL = new StringBuilder(config.getConnectionUrl()); @@ -150,4 +135,68 @@ public static Map constructConnectionHeadersMap(Map getFormattedBatchInsertRecord(Object record, int requestIndex) { HashMap insertRecord = new HashMap<>(); - Gson gson = new Gson(); String jsonString = gson.toJson(record); JsonObject bodyObject = JsonParser.parseString(jsonString).getAsJsonObject().get("Body").getAsJsonObject(); JsonArray records = bodyObject.getAsJsonArray("records"); @@ -45,10 +43,9 @@ private static synchronized HashMap getFormattedBatchInsertRecor for (JsonElement recordElement : records) { JsonObject recordObject = recordElement.getAsJsonObject(); insertRecord.put("skyflow_id", recordObject.get("skyflow_id").getAsString()); - - Map tokensMap = recordObject.get("tokens").getAsJsonObject().asMap(); - for (String key : tokensMap.keySet()) { - insertRecord.put(key, tokensMap.get(key)); + JsonElement tokensElement = recordObject.get("tokens"); + if (tokensElement != null) { + insertRecord.putAll(tokensElement.getAsJsonObject().asMap()); } } } @@ -63,78 +60,45 @@ private static synchronized HashMap getFormattedBatchInsertRecor private static synchronized HashMap getFormattedBulkInsertRecord(V1RecordMetaProperties record) { HashMap insertRecord = new HashMap<>(); String skyflowId = record.getSkyflowId(); - insertRecord.put("skyflowId", skyflowId); - - /* - Getting unchecked cast warning, however, this type is inferred - from an exception trying to cast into another type. Therefore, - this type cast will not fail. - */ - LinkedTreeMap tokensMap = (LinkedTreeMap) record.getTokens(); - if (tokensMap != null) { - for (String key : tokensMap.keySet()) { - insertRecord.put(key, tokensMap.get(key)); - } + insertRecord.put("skyflow_id", skyflowId); + String tokensString = gson.toJson(record.getTokens()); + if (tokensString != null) { + JsonObject tokensObject = JsonParser.parseString(tokensString).getAsJsonObject(); + insertRecord.putAll(tokensObject.asMap()); } return insertRecord; } private static synchronized HashMap getFormattedGetRecord(V1FieldRecords record) { HashMap getRecord = new HashMap<>(); - - /* - Getting unchecked cast warning, however, this type is inferred - from an exception trying to cast into another type. Therefore, - this type cast will not fail. - */ - LinkedTreeMap map; - if (record.getTokens() != null) { - map = (LinkedTreeMap) record.getTokens(); - } else { - map = (LinkedTreeMap) record.getFields(); - } - if (map != null) { - for (String key : map.keySet()) { - getRecord.put(key, map.get(key)); - } + String fieldsString = gson.toJson(record.getFields()); + String tokensString = gson.toJson(record.getTokens()); + if (fieldsString != null) { + JsonObject fieldsObject = JsonParser.parseString(fieldsString).getAsJsonObject(); + getRecord.putAll(fieldsObject.asMap()); + } else if (tokensString != null) { + JsonObject tokensObject = JsonParser.parseString(tokensString).getAsJsonObject(); + getRecord.putAll(tokensObject.asMap()); } return getRecord; } private static synchronized HashMap getFormattedUpdateRecord(V1UpdateRecordResponse record) { HashMap updateTokens = new HashMap<>(); - /* - Getting unchecked cast warning, however, this type is inferred - from an exception trying to cast into another type. Therefore, - this type cast will not fail. - */ - LinkedTreeMap map = null; - if (record.getTokens() != null) { - map = (LinkedTreeMap) record.getTokens(); - } - if (map != null) { - for (String key : map.keySet()) { - updateTokens.put(key, map.get(key)); - } + String tokensString = gson.toJson(record.getTokens()); + if (tokensString != null) { + JsonObject tokensObject = JsonParser.parseString(tokensString).getAsJsonObject(); + updateTokens.putAll(tokensObject.asMap()); } return updateTokens; } private static synchronized HashMap getFormattedQueryRecord(V1FieldRecords record) { HashMap queryRecord = new HashMap<>(); - /* - Getting unchecked cast warning, however, this type is inferred - from an exception trying to cast into another type. Therefore, - this type cast will not fail. - */ - LinkedTreeMap map = null; - if (record.getFields() != null) { - map = (LinkedTreeMap) record.getFields(); - } - if (map != null) { - for (String key : map.keySet()) { - queryRecord.put(key, map.get(key)); - } + String fieldsString = gson.toJson(record.getFields()); + if (fieldsString != null) { + JsonObject fieldsObject = JsonParser.parseString(fieldsString).getAsJsonObject(); + queryRecord.putAll(fieldsObject.asMap()); } return queryRecord; } @@ -273,7 +237,7 @@ public UpdateResponse update(UpdateRequest updateRequest) throws SkyflowExceptio result = super.getRecordsApi().recordServiceUpdateRecord( super.getVaultConfig().getVaultId(), updateRequest.getTable(), - updateRequest.getData().get("skyflow_id").toString(), + updateRequest.getData().remove("skyflow_id").toString(), updateBody ); LogUtil.printInfoLog(InfoLogs.UPDATE_REQUEST_RESOLVED.getLog()); diff --git a/src/main/java/com/skyflow/vault/data/DeleteResponse.java b/src/main/java/com/skyflow/vault/data/DeleteResponse.java index 21adc788..7b245bf1 100644 --- a/src/main/java/com/skyflow/vault/data/DeleteResponse.java +++ b/src/main/java/com/skyflow/vault/data/DeleteResponse.java @@ -1,5 +1,10 @@ package com.skyflow.vault.data; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + import java.util.ArrayList; public class DeleteResponse { @@ -15,20 +20,9 @@ public ArrayList getDeletedIds() { @Override public String toString() { - StringBuilder response = new StringBuilder("{"); - response.append("\n\t\"deletedIds\": ").append(formatIds()); - return response.append("\n}").toString(); - } - - private String formatIds() { - StringBuilder sb = new StringBuilder("["); - for (String id : deletedIds) { - sb.append("\n\t\"").append(id).append("\""); - } - return toIndentedString(sb.append("]")); - } - - private String toIndentedString(Object o) { - return o.toString().replace("\n", "\n\t"); + Gson gson = new Gson(); + JsonObject responseObject = JsonParser.parseString(gson.toJson(this)).getAsJsonObject(); + responseObject.add("errors", new JsonArray()); + return responseObject.toString(); } } diff --git a/src/main/java/com/skyflow/vault/data/GetResponse.java b/src/main/java/com/skyflow/vault/data/GetResponse.java index bd882138..41821969 100644 --- a/src/main/java/com/skyflow/vault/data/GetResponse.java +++ b/src/main/java/com/skyflow/vault/data/GetResponse.java @@ -1,5 +1,7 @@ package com.skyflow.vault.data; +import com.google.gson.Gson; + import java.util.ArrayList; import java.util.HashMap; @@ -22,30 +24,7 @@ public ArrayList> getErrors() { @Override public String toString() { - StringBuilder response = new StringBuilder("{"); - response.append("\n\t\"data\": ").append(formatRecords(data)); - response.append(",\n\t\"errors\": ").append(formatRecords(errors)); - response.append("\n}"); - return response.toString(); - } - - private String formatRecords(ArrayList> records) { - StringBuilder sb = new StringBuilder("["); - for (int index = 0; index < records.size(); index++) { - HashMap map = records.get(index); - sb.append("{"); - for (String key : map.keySet()) { - sb.append("\n\t\"").append(key).append("\": \"").append(map.get(key)).append("\","); - } - sb.append("\n}"); - if (index != records.size() - 1) { - sb.append(", "); - } - } - return toIndentedString(sb.append("]")); - } - - private String toIndentedString(Object o) { - return o.toString().replace("\n", "\n\t"); + Gson gson = new Gson(); + return gson.toJson(this); } } diff --git a/src/main/java/com/skyflow/vault/data/InsertResponse.java b/src/main/java/com/skyflow/vault/data/InsertResponse.java index 240c6940..a4f97967 100644 --- a/src/main/java/com/skyflow/vault/data/InsertResponse.java +++ b/src/main/java/com/skyflow/vault/data/InsertResponse.java @@ -1,51 +1,30 @@ package com.skyflow.vault.data; +import com.google.gson.Gson; + import java.util.ArrayList; import java.util.HashMap; public class InsertResponse { private final ArrayList> insertedFields; - private final ArrayList> errorFields; + private final ArrayList> errors; - public InsertResponse(ArrayList> insertedFields, ArrayList> errorFields) { + public InsertResponse(ArrayList> insertedFields, ArrayList> errors) { this.insertedFields = insertedFields; - this.errorFields = errorFields; + this.errors = errors; } public ArrayList> getInsertedFields() { return insertedFields; } - public ArrayList> getErrorFields() { - return errorFields; + public ArrayList> getErrors() { + return errors; } @Override public String toString() { - StringBuilder response = new StringBuilder("{"); - response.append("\n\t\"insertedFields\": ").append(formatRecords(insertedFields)); - response.append(",\n\t\"errors\": ").append(formatRecords(errorFields)); - response.append("\n}"); - return response.toString(); - } - - private String formatRecords(ArrayList> records) { - StringBuilder sb = new StringBuilder("["); - for (int index = 0; index < records.size(); index++) { - HashMap map = records.get(index); - sb.append("{"); - for (String key : map.keySet()) { - sb.append("\n\t\"").append(key).append("\": \"").append(map.get(key)).append("\","); - } - sb.append("\n}"); - if (index != records.size() - 1) { - sb.append(", "); - } - } - return toIndentedString(sb.append("]")); - } - - private String toIndentedString(Object o) { - return o.toString().replace("\n", "\n\t"); + Gson gson = new Gson(); + return gson.toJson(this); } } diff --git a/src/main/java/com/skyflow/vault/data/QueryResponse.java b/src/main/java/com/skyflow/vault/data/QueryResponse.java index e8103506..020a24c1 100644 --- a/src/main/java/com/skyflow/vault/data/QueryResponse.java +++ b/src/main/java/com/skyflow/vault/data/QueryResponse.java @@ -1,5 +1,7 @@ package com.skyflow.vault.data; +import com.google.gson.*; + import java.util.ArrayList; import java.util.HashMap; @@ -17,30 +19,13 @@ public ArrayList> getFields() { @Override public String toString() { - StringBuilder response = new StringBuilder("{"); - response.append("\n\t\"fields\": ").append(formatFields()); - return response.append("\n}").toString(); - } - - private String formatFields() { - StringBuilder sb = new StringBuilder("["); - for (int index = 0; index < fields.size(); index++) { - HashMap map = fields.get(index); - sb.append("{"); - for (String key : map.keySet()) { - sb.append("\n\t\"").append(key).append("\": \"").append(map.get(key)).append("\","); - } - sb.append("\n\t\"tokenizedData\": ").append(tokenizedData); - sb.append("\n}"); - if (index != fields.size() - 1) { - sb.append(", "); - } + Gson gson = new Gson(); + JsonObject responseObject = JsonParser.parseString(gson.toJson(this)).getAsJsonObject(); + JsonArray fieldsArray = responseObject.get("fields").getAsJsonArray(); + for (JsonElement fieldElement : fieldsArray) { + fieldElement.getAsJsonObject().add("tokenizedData", null); } - return toIndentedString(sb.append("]")); + responseObject.add("errors", new JsonArray()); + return responseObject.toString(); } - - private String toIndentedString(Object o) { - return o.toString().replace("\n", "\n\t"); - } - } diff --git a/src/main/java/com/skyflow/vault/data/UpdateResponse.java b/src/main/java/com/skyflow/vault/data/UpdateResponse.java index 4567e2e1..cbeed0f9 100644 --- a/src/main/java/com/skyflow/vault/data/UpdateResponse.java +++ b/src/main/java/com/skyflow/vault/data/UpdateResponse.java @@ -1,5 +1,9 @@ package com.skyflow.vault.data; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + import java.util.HashMap; public class UpdateResponse { @@ -21,20 +25,13 @@ public HashMap getTokens() { @Override public String toString() { - StringBuilder response = new StringBuilder("{"); - response.append("\n\t\"skyflowId\": \"").append(skyflowId).append("\""); - if (!tokens.isEmpty()) { - response.append(formatTokens(tokens)); - } - response.append("\n}"); - return response.toString(); - } - - private String formatTokens(HashMap tokens) { - StringBuilder sb = new StringBuilder(); - for (String key : tokens.keySet()) { - sb.append("\n\t\"").append(key).append("\": \"").append(tokens.get(key)).append("\","); + Gson gson = new Gson(); + JsonObject responseObject = JsonParser.parseString(gson.toJson(this)).getAsJsonObject(); + responseObject.add("skyflow_id", responseObject.remove("skyflowId")); + JsonObject tokensObject = responseObject.remove("tokens").getAsJsonObject(); + for (String key : tokensObject.keySet()) { + responseObject.add(key, tokensObject.get(key)); } - return sb.toString(); + return responseObject.toString(); } } diff --git a/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java index 2fb1d42f..198034a7 100644 --- a/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java @@ -10,8 +10,8 @@ public class DetokenizeRecordResponse { public DetokenizeRecordResponse(V1DetokenizeRecordResponse record) { this.token = record.getToken(); - this.value = record.getValue(); - this.type = record.getValueType().getValue(); + this.value = record.getValue().isEmpty() ? null : record.getValue(); + this.type = record.getValueType().getValue().equals("NONE") ? null : record.getValueType().getValue(); this.error = record.getError(); } @@ -30,18 +30,4 @@ public String getValue() { public String getType() { return type; } - - @Override - public String toString() { - StringBuilder response = new StringBuilder("{"); - response.append("\n\t").append("\"token\": \"").append(token).append("\","); - if (error == null) { - response.append("\n\t").append("\"value\": \"").append(value).append("\","); - response.append("\n\t").append("\"type\": \"").append(type).append("\","); - } else { - response.append("\n\t").append("\"error\": \"").append(error).append("\","); - } - response.append("\n}"); - return response.toString(); - } } \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java index 0c136e1a..31ff64b2 100644 --- a/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java @@ -1,14 +1,16 @@ package com.skyflow.vault.tokens; +import com.google.gson.Gson; + import java.util.ArrayList; public class DetokenizeResponse { private final ArrayList detokenizedFields; - private final ArrayList errorRecords; + private final ArrayList errors; - public DetokenizeResponse(ArrayList detokenizedFields, ArrayList errorRecords) { + public DetokenizeResponse(ArrayList detokenizedFields, ArrayList errors) { this.detokenizedFields = detokenizedFields; - this.errorRecords = errorRecords; + this.errors = errors; } public ArrayList getDetokenizedFields() { @@ -16,19 +18,12 @@ public ArrayList getDetokenizedFields() { } public ArrayList getErrors() { - return errorRecords; + return errors; } @Override public String toString() { - StringBuilder response = new StringBuilder("{"); - response.append("\n\t").append("\"detokenizedFields\": ").append(toIndentedString(detokenizedFields)); - response.append("\n\t").append("\"errors\": ").append(toIndentedString(errorRecords)); - response.append("\n}"); - return response.toString(); - } - - private String toIndentedString(Object o) { - return o.toString().replace("\n", "\n\t"); + Gson gson = new Gson(); + return gson.toJson(this); } } diff --git a/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java b/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java index a82d081a..0b311fbb 100644 --- a/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java +++ b/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java @@ -1,5 +1,10 @@ package com.skyflow.vault.tokens; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + import java.util.List; public class TokenizeResponse { @@ -15,8 +20,9 @@ public List getTokens() { @Override public String toString() { - StringBuilder response = new StringBuilder("{"); - response.append("\n\t\"tokens\": ").append(tokens); - return response.append("\n}").toString(); + Gson gson = new Gson(); + JsonObject responseObject = JsonParser.parseString(gson.toJson(this)).getAsJsonObject(); + responseObject.add("errors", new JsonArray()); + return responseObject.toString(); } } diff --git a/src/test/java/com/skyflow/SkyflowTests.java b/src/test/java/com/skyflow/SkyflowTests.java index 041969a7..f7385af1 100644 --- a/src/test/java/com/skyflow/SkyflowTests.java +++ b/src/test/java/com/skyflow/SkyflowTests.java @@ -140,8 +140,6 @@ public void testUpdatingValidVaultConfigInSkyflowClient() { Credentials credentials = new Credentials(); credentials.setToken(token); - skyflowClient.updateVaultConfig(config); - config.setClusterId(newClusterID); config.setEnv(Env.PROD); config.setCredentials(credentials); diff --git a/src/test/java/com/skyflow/utils/UtilsTests.java b/src/test/java/com/skyflow/utils/UtilsTests.java index 8116046e..930a44f1 100644 --- a/src/test/java/com/skyflow/utils/UtilsTests.java +++ b/src/test/java/com/skyflow/utils/UtilsTests.java @@ -1,5 +1,6 @@ package com.skyflow.utils; +import com.google.gson.JsonObject; import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; import com.skyflow.enums.Env; @@ -181,4 +182,35 @@ public void testConstructConnectionHeaderMap() { Assert.fail(INVALID_EXCEPTION_THROWN); } } + + @Test + public void testGetMetrics() { + try { + JsonObject metrics = Utils.getMetrics(); + Assert.assertNotNull(metrics.get(Constants.SDK_METRIC_NAME_VERSION)); + Assert.assertNotNull(metrics.get(Constants.SDK_METRIC_CLIENT_DEVICE_MODEL)); + Assert.assertNotNull(metrics.get(Constants.SDK_METRIC_CLIENT_OS_DETAILS)); + Assert.assertNotNull(metrics.get(Constants.SDK_METRIC_RUNTIME_DETAILS)); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetMetricsWithException() { + try { + // Clearing System Properties explicitly to throw exception + System.clearProperty("os.name"); + System.clearProperty("os.version"); + System.clearProperty("java.version"); + + JsonObject metrics = Utils.getMetrics(); + Assert.assertEquals("skyflow-java@v2", metrics.get(Constants.SDK_METRIC_NAME_VERSION).getAsString()); + Assert.assertEquals("Java@", metrics.get(Constants.SDK_METRIC_RUNTIME_DETAILS).getAsString()); + Assert.assertTrue(metrics.get(Constants.SDK_METRIC_CLIENT_DEVICE_MODEL).getAsString().isEmpty()); + Assert.assertTrue(metrics.get(Constants.SDK_METRIC_CLIENT_OS_DETAILS).getAsString().isEmpty()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } } diff --git a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java index 7c6f6213..4baa5ebf 100644 --- a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java +++ b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java @@ -400,8 +400,8 @@ public void testInvokeConnectionResponse() { responseObject.addProperty("test_key_1", "test_value_1"); responseObject.addProperty("test_key_2", "test_value_2"); InvokeConnectionResponse connectionResponse = new InvokeConnectionResponse(responseObject); - String responseString = "InvokeConnectionResponse{" + "response=" + responseObject + "}"; - Assert.assertEquals(responseString, connectionResponse.toString()); + Assert.assertEquals(2, connectionResponse.getResponse().size()); + Assert.assertEquals(responseObject.toString(), connectionResponse.toString()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } diff --git a/src/test/java/com/skyflow/vault/data/DeleteTests.java b/src/test/java/com/skyflow/vault/data/DeleteTests.java index a0401842..c261cfd1 100644 --- a/src/test/java/com/skyflow/vault/data/DeleteTests.java +++ b/src/test/java/com/skyflow/vault/data/DeleteTests.java @@ -149,7 +149,7 @@ public void testDeleteResponse() { try { ids.add(skyflowID); DeleteResponse response = new DeleteResponse(ids); - String responseString = "{\n\t\"deletedIds\": [\n\t\t\"" + skyflowID + "\"]\n}"; + String responseString = "{\"deletedIds\":[\"" + skyflowID + "\"],\"errors\":[]}"; Assert.assertEquals(1, response.getDeletedIds().size()); Assert.assertEquals(responseString, response.toString()); } catch (Exception e) { diff --git a/src/test/java/com/skyflow/vault/data/GetTests.java b/src/test/java/com/skyflow/vault/data/GetTests.java index 769ff868..930d696a 100644 --- a/src/test/java/com/skyflow/vault/data/GetTests.java +++ b/src/test/java/com/skyflow/vault/data/GetTests.java @@ -471,12 +471,12 @@ public void testGetResponse() { data.add(record); ArrayList> errors = new ArrayList<>(); GetResponse response = new GetResponse(data, errors); - String responseString = "{\n\t\"data\": [" + - "{\n\t\t\"test_column_1\": \"test_value_1\"," + - "\n\t\t\"test_column_2\": \"test_value_2\",\n\t}, " + - "{\n\t\t\"test_column_1\": \"test_value_1\"," + - "\n\t\t\"test_column_2\": \"test_value_2\",\n\t}]" + - ",\n\t\"errors\": " + errors + "\n}"; + String responseString = "{\"data\":[" + + "{\"test_column_1\":\"test_value_1\"," + + "\"test_column_2\":\"test_value_2\"}," + + "{\"test_column_1\":\"test_value_1\"," + + "\"test_column_2\":\"test_value_2\"}]" + + ",\"errors\":" + errors + "}"; Assert.assertEquals(2, response.getData().size()); Assert.assertTrue(response.getErrors().isEmpty()); Assert.assertEquals(responseString, response.toString()); diff --git a/src/test/java/com/skyflow/vault/data/InsertTests.java b/src/test/java/com/skyflow/vault/data/InsertTests.java index 7b911bc1..facdcf60 100644 --- a/src/test/java/com/skyflow/vault/data/InsertTests.java +++ b/src/test/java/com/skyflow/vault/data/InsertTests.java @@ -384,14 +384,14 @@ public void testInsertResponse() { values.add(valueMap); values.add(valueMap); InsertResponse response = new InsertResponse(values, errorFields); - String responseString = "{\n\t\"insertedFields\": [" + - "{\n\t\t\"test_column_1\": \"test_value_1\"," + - "\n\t\t\"test_column_2\": \"test_value_2\",\n\t}, " + - "{\n\t\t\"test_column_1\": \"test_value_1\"," + - "\n\t\t\"test_column_2\": \"test_value_2\",\n\t}]" + - ",\n\t\"errors\": " + errorFields + "\n}"; + String responseString = "{\"insertedFields\":[" + + "{\"test_column_1\":\"test_value_1\"," + + "\"test_column_2\":\"test_value_2\"}," + + "{\"test_column_1\":\"test_value_1\"," + + "\"test_column_2\":\"test_value_2\"}]" + + ",\"errors\":" + errorFields + "}"; Assert.assertEquals(2, response.getInsertedFields().size()); - Assert.assertTrue(response.getErrorFields().isEmpty()); + Assert.assertTrue(response.getErrors().isEmpty()); Assert.assertEquals(responseString, response.toString()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); diff --git a/src/test/java/com/skyflow/vault/data/QueryTests.java b/src/test/java/com/skyflow/vault/data/QueryTests.java index a18a45cf..fdf51482 100644 --- a/src/test/java/com/skyflow/vault/data/QueryTests.java +++ b/src/test/java/com/skyflow/vault/data/QueryTests.java @@ -94,11 +94,10 @@ public void testQueryResponse() { fields.add(queryRecord); fields.add(queryRecord); QueryResponse response = new QueryResponse(fields); - String responseString = "{\n\t\"fields\": " + - "[{\n\t\t\"card_number\": \"test_card_number\",\n\t\t\"name\": \"test_name\"," + - "\n\t\t\"tokenizedData\": " + null + "\n\t}, " + - "{\n\t\t\"card_number\": \"test_card_number\",\n\t\t\"name\": \"test_name\"," + - "\n\t\t\"tokenizedData\": " + null + "\n\t}]\n}"; + String responseString = "{\"fields\":" + + "[{\"card_number\":\"test_card_number\",\"name\":\"test_name\",\"tokenizedData\":null}," + + "{\"card_number\":\"test_card_number\",\"name\":\"test_name\",\"tokenizedData\":null}]," + + "\"errors\":[]}"; Assert.assertEquals(2, response.getFields().size()); Assert.assertEquals(responseString, response.toString()); } catch (Exception e) { diff --git a/src/test/java/com/skyflow/vault/data/UpdateTests.java b/src/test/java/com/skyflow/vault/data/UpdateTests.java index c23977c6..2f2f1247 100644 --- a/src/test/java/com/skyflow/vault/data/UpdateTests.java +++ b/src/test/java/com/skyflow/vault/data/UpdateTests.java @@ -386,9 +386,9 @@ public void testUpdateResponse() { tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("test_column_2", "test_token_2"); UpdateResponse response = new UpdateResponse(skyflowID, tokenMap); - String responseString = "{\n\t\"skyflowId\": \"" + skyflowID + "\"" - + "\n\t\"test_column_1\": \"test_token_1\"," - + "\n\t\"test_column_2\": \"test_token_2\",\n}"; + String responseString = "{\"skyflow_id\":\"" + skyflowID + "\"," + + "\"test_column_1\":\"test_token_1\"," + + "\"test_column_2\":\"test_token_2\"}"; Assert.assertEquals(skyflowID, response.getSkyflowId()); Assert.assertEquals(2, response.getTokens().size()); Assert.assertEquals(responseString, response.toString()); diff --git a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index 6c49bc8c..df8153d9 100644 --- a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -126,6 +126,7 @@ public void testDetokenizeResponse() { V1DetokenizeRecordResponse record2 = new V1DetokenizeRecordResponse(); record2.setToken("3456-7890-1234-5678"); + record2.setValue(""); record2.setError("Invalid token"); DetokenizeRecordResponse error = new DetokenizeRecordResponse(record2); @@ -138,11 +139,11 @@ public void testDetokenizeResponse() { errors.add(error); DetokenizeResponse response = new DetokenizeResponse(fields, errors); - String responseString = "{\n\t\"detokenizedFields\": [{" + - "\n\t\t\"token\": \"1234-5678-9012-3456\",\n\t\t\"value\": \"4111111111111111\",\n\t\t\"type\": \"STRING\",\n\t}, " + - "{\n\t\t\"token\": \"1234-5678-9012-3456\",\n\t\t\"value\": \"4111111111111111\",\n\t\t\"type\": \"STRING\",\n\t}]" + - "\n\t\"errors\": [{\n\t\t\"token\": \"3456-7890-1234-5678\",\n\t\t\"error\": \"Invalid token\",\n\t}, " + - "{\n\t\t\"token\": \"3456-7890-1234-5678\",\n\t\t\"error\": \"Invalid token\",\n\t}]\n}"; + String responseString = "{\"detokenizedFields\":[{" + + "\"token\":\"1234-5678-9012-3456\",\"value\":\"4111111111111111\",\"type\":\"STRING\"}," + + "{\"token\":\"1234-5678-9012-3456\",\"value\":\"4111111111111111\",\"type\":\"STRING\"}]," + + "\"errors\":[{\"token\":\"3456-7890-1234-5678\",\"error\":\"Invalid token\"}," + + "{\"token\":\"3456-7890-1234-5678\",\"error\":\"Invalid token\"}]}"; Assert.assertEquals(2, response.getDetokenizedFields().size()); Assert.assertEquals(2, response.getErrors().size()); Assert.assertEquals("1234-5678-9012-3456", response.getDetokenizedFields().get(0).getToken()); diff --git a/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java index 18edf253..422cd79e 100644 --- a/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java @@ -129,7 +129,7 @@ public void testTokenizeResponse() { tokens.add("1234-5678-9012-3456"); tokens.add("5678-9012-3456-7890"); TokenizeResponse response = new TokenizeResponse(tokens); - String responseString = "{\n\t\"tokens\": [1234-5678-9012-3456, 5678-9012-3456-7890]\n}"; + String responseString = "{\"tokens\":[\"1234-5678-9012-3456\",\"5678-9012-3456-7890\"],\"errors\":[]}"; Assert.assertEquals(2, response.getTokens().size()); Assert.assertEquals(responseString, response.toString()); } catch (Exception e) { From ea8ae4ca82d258f823f4c94e14155ea7d7e57ee7 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 5 Dec 2024 20:55:52 +0530 Subject: [PATCH 082/126] SK-1802 Fix inconsistencies in SDK v2 - Fix inconsistency between vault and connection client - Added unit tests for vault and connection clients --- .github/workflows/main.yml | 2 +- .github/workflows/pr.yml | 1 + .github/workflows/shared-build-and-deploy.yml | 1 + .../java/com/skyflow/ConnectionClient.java | 14 +- src/main/java/com/skyflow/VaultClient.java | 1 - .../com/skyflow/ConnectionClientTests.java | 95 ++++++ .../java/com/skyflow/VaultClientTests.java | 303 ++++++++++++++++++ 7 files changed, 410 insertions(+), 7 deletions(-) create mode 100644 src/test/java/com/skyflow/ConnectionClientTests.java create mode 100644 src/test/java/com/skyflow/VaultClientTests.java diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index efdecf24..6ec8f15b 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -23,7 +23,7 @@ jobs: json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - name: Build & Run tests with Maven - run: mvn -B package -DTEST_VAULT_ID=${{ secrets.TEST_VAULT_ID }} -DTEST_VAULT_URL=${{ secrets.TEST_VAULT_URL }} -DTEST_SKYFLOW_ID=${{ secrets.TEST_SKYFLOW_ID }} -DTEST_TOKEN=${{ secrets.TEST_TOKEN }} -DTEST_CREDENTIALS=${{ secrets.TEST_CREDENTIALS_FILE_STRING }} -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -f pom.xml + run: mvn -B package -DTEST_VAULT_ID=${{ secrets.TEST_VAULT_ID }} -DTEST_VAULT_URL=${{ secrets.TEST_VAULT_URL }} -DTEST_SKYFLOW_ID=${{ secrets.TEST_SKYFLOW_ID }} -DTEST_TOKEN=${{ secrets.TEST_TOKEN }} -DTEST_CREDENTIALS=${{ secrets.TEST_CREDENTIALS_FILE_STRING }} -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -DTEST_HUNDRED_TOKEN=${{ secrets.TEST_HUNDRED_TOKEN }} -f pom.xml - name: Codecov uses: codecov/codecov-action@v2.1.0 diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index da765524..7e0f5abf 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -37,6 +37,7 @@ jobs: touch .env echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + echo TEST_HUNDRED_TOKEN=${{ secrets.TEST_HUNDRED_TOKEN }} >> .env - name: Build & Run tests with Maven run: mvn -B package -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -DTEST_DATA_CREDENTIALS_FILE=${{ secrets.TEST_DATA_CREDENTIALS_FILE }} -f pom.xml diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index 0dca78f0..845acbd9 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -89,6 +89,7 @@ jobs: touch .env echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + echo TEST_HUNDRED_TOKEN=${{ secrets.TEST_HUNDRED_TOKEN }} >> .env - name: Create credentials json id: create-json diff --git a/src/main/java/com/skyflow/ConnectionClient.java b/src/main/java/com/skyflow/ConnectionClient.java index 72a70fef..e0a6cf19 100644 --- a/src/main/java/com/skyflow/ConnectionClient.java +++ b/src/main/java/com/skyflow/ConnectionClient.java @@ -12,6 +12,7 @@ import com.skyflow.utils.logger.LogUtil; import com.skyflow.utils.validations.Validations; import io.github.cdimascio.dotenv.Dotenv; +import io.github.cdimascio.dotenv.DotenvException; public class ConnectionClient { private final ConnectionConfig connectionConfig; @@ -30,21 +31,19 @@ protected ConnectionConfig getConnectionConfig() { return connectionConfig; } - protected void setCommonCredentials(Credentials commonCredentials) { + protected void setCommonCredentials(Credentials commonCredentials) throws SkyflowException { this.commonCredentials = commonCredentials; prioritiseCredentials(); } - protected void updateConnectionConfig(ConnectionConfig connectionConfig) { + protected void updateConnectionConfig(ConnectionConfig connectionConfig) throws SkyflowException { prioritiseCredentials(); } protected void setBearerToken() throws SkyflowException { - prioritiseCredentials(); Validations.validateCredentials(this.finalCredentials); if (this.finalCredentials.getApiKey() != null) { setApiKey(); - return; } else if (Token.isExpired(token)) { LogUtil.printInfoLog(InfoLogs.BEARER_TOKEN_EXPIRED.getLog()); token = Utils.generateBearerToken(this.finalCredentials); @@ -61,7 +60,7 @@ private void setApiKey() { } } - private void prioritiseCredentials() { + private void prioritiseCredentials() throws SkyflowException { try { if (this.connectionConfig.getCredentials() != null) { this.finalCredentials = this.connectionConfig.getCredentials(); @@ -78,6 +77,11 @@ private void prioritiseCredentials() { this.finalCredentials.setCredentialsString(sysCredentials); } } + token = null; + apiKey = null; + } catch (DotenvException e) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.EmptyCredentials.getMessage()); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/src/main/java/com/skyflow/VaultClient.java b/src/main/java/com/skyflow/VaultClient.java index f35504be..10f89284 100644 --- a/src/main/java/com/skyflow/VaultClient.java +++ b/src/main/java/com/skyflow/VaultClient.java @@ -169,7 +169,6 @@ protected V1TokenizePayload getTokenizePayload(TokenizeRequest request) { } protected void setBearerToken() throws SkyflowException { - prioritiseCredentials(); Validations.validateCredentials(this.finalCredentials); if (this.finalCredentials.getApiKey() != null) { setApiKey(); diff --git a/src/test/java/com/skyflow/ConnectionClientTests.java b/src/test/java/com/skyflow/ConnectionClientTests.java new file mode 100644 index 00000000..533e8a9b --- /dev/null +++ b/src/test/java/com/skyflow/ConnectionClientTests.java @@ -0,0 +1,95 @@ +package com.skyflow; + +import com.skyflow.config.ConnectionConfig; +import com.skyflow.config.Credentials; +import io.github.cdimascio.dotenv.Dotenv; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ConnectionClientTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static ConnectionClient connectionClient; + private static String connectionID = null; + private static String connectionURL = null; + private static String apiKey = null; + private static ConnectionConfig connectionConfig; + + @BeforeClass + public static void setup() { + connectionID = "connection123"; + connectionURL = "https://test.connection.url"; + apiKey = "sky-ab123-abcd1234cdef1234abcd4321cdef4321"; + + Credentials credentials = new Credentials(); + credentials.setApiKey(apiKey); + + connectionConfig = new ConnectionConfig(); + connectionConfig.setConnectionId(connectionID); + connectionConfig.setConnectionUrl(connectionURL); + connectionClient = new ConnectionClient(connectionConfig, credentials); + } + + @Test + public void getConnectionConfig() { + try { + ConnectionConfig config = connectionClient.getConnectionConfig(); + Assert.assertEquals(connectionID, config.getConnectionId()); + Assert.assertEquals(connectionURL, config.getConnectionUrl()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testSetBearerToken() { + try { + Dotenv dotenv = Dotenv.load(); + String bearerToken = dotenv.get("TEST_HUNDRED_TOKEN"); + Credentials credentials = new Credentials(); + credentials.setToken(bearerToken); + connectionConfig.setCredentials(credentials); + connectionClient.updateConnectionConfig(connectionConfig); + + // regular scenario + connectionClient.setBearerToken(); + + // re-use scenario + connectionClient.setBearerToken(); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testSetBearerTokenWithApiKey() { + try { + Credentials credentials = new Credentials(); + credentials.setApiKey(apiKey); + connectionConfig.setCredentials(null); + connectionClient.updateConnectionConfig(connectionConfig); + connectionClient.setCommonCredentials(credentials); + + // regular scenario + connectionClient.setBearerToken(); + + // re-use scenario + connectionClient.setBearerToken(); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testSetBearerTokenWithEnvCredentials() { + try { + connectionConfig.setCredentials(null); + connectionClient.updateConnectionConfig(connectionConfig); + connectionClient.setCommonCredentials(null); + Assert.assertNull(connectionClient.getConnectionConfig().getCredentials()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/VaultClientTests.java b/src/test/java/com/skyflow/VaultClientTests.java new file mode 100644 index 00000000..58cbf08a --- /dev/null +++ b/src/test/java/com/skyflow/VaultClientTests.java @@ -0,0 +1,303 @@ +package com.skyflow; + +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.TokenMode; +import com.skyflow.generated.rest.auth.HttpBearerAuth; +import com.skyflow.generated.rest.models.*; +import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.UpdateRequest; +import com.skyflow.vault.tokens.ColumnValue; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.TokenizeRequest; +import io.github.cdimascio.dotenv.Dotenv; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class VaultClientTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static VaultClient vaultClient; + private static String vaultID = null; + private static String clusterID = null; + private static String token = null; + private static String table = null; + private static String value = null; + private static String columnGroup = null; + private static String apiKey = null; + private static ArrayList tokens = null; + private static ArrayList> insertValues = null; + private static ArrayList> insertTokens = null; + private static HashMap valueMap = null; + private static HashMap tokenMap = null; + private static VaultConfig vaultConfig; + + @BeforeClass + public static void setup() { + vaultID = "vault123"; + clusterID = "cluster123"; + token = "test_token"; + tokens = new ArrayList<>(); + table = "test_table"; + value = "test_value"; + columnGroup = "test_column_group"; + apiKey = "sky-ab123-abcd1234cdef1234abcd4321cdef4321"; + insertValues = new ArrayList<>(); + insertTokens = new ArrayList<>(); + valueMap = new HashMap<>(); + tokenMap = new HashMap<>(); + + Credentials credentials = new Credentials(); + credentials.setApiKey(apiKey); + + vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.PROD); + vaultClient = new VaultClient(vaultConfig, credentials); + } + + @Test + public void testVaultClientGetApiClient() { + try { + Assert.assertNotNull(vaultClient.getApiClient()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testVaultClientGetRecordsAPI() { + try { + Assert.assertNotNull(vaultClient.getRecordsApi()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testVaultClientGetTokensAPI() { + try { + Assert.assertNotNull(vaultClient.getTokensApi()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testVaultClientGetQueryAPI() { + try { + Assert.assertNotNull(vaultClient.getQueryApi()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testVaultClientGetVaultConfig() { + try { + VaultConfig config = vaultClient.getVaultConfig(); + Assert.assertNotNull(config); + Assert.assertEquals(vaultID, config.getVaultId()); + Assert.assertEquals(clusterID, config.getClusterId()); + Assert.assertEquals(Env.PROD, config.getEnv()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetDetokenizePayload() { + try { + tokens.add(token); + tokens.add(token); + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder().tokens(tokens).build(); + V1DetokenizePayload payload = vaultClient.getDetokenizePayload(detokenizeRequest); + Assert.assertTrue(payload.getContinueOnError()); + Assert.assertEquals(2, payload.getDetokenizationParameters().size()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetBulkInsertRequestBody() { + try { + valueMap.clear(); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.clear(); + tokenMap.put("test_column_1", "test_token_1"); + insertValues.clear(); + insertValues.add(valueMap); + insertValues.add(valueMap); + insertTokens.clear(); + insertTokens.add(tokenMap); + InsertRequest insertRequest1 = InsertRequest.builder() + .table(table) + .values(insertValues) + .tokens(insertTokens) + .tokenMode(TokenMode.ENABLE) + .returnTokens(true) + .build(); + RecordServiceInsertRecordBody body1 = vaultClient.getBulkInsertRequestBody(insertRequest1); + Assert.assertTrue(body1.getTokenization()); + Assert.assertNull(body1.getUpsert()); + Assert.assertEquals(2, body1.getRecords().size()); + + InsertRequest insertRequest2 = InsertRequest.builder().table(table).values(insertValues).build(); + RecordServiceInsertRecordBody body2 = vaultClient.getBulkInsertRequestBody(insertRequest2); + Assert.assertEquals(2, body2.getRecords().size()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetBatchInsertRequestBody() { + try { + valueMap.clear(); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.clear(); + tokenMap.put("test_column_1", "test_token_1"); + insertValues.clear(); + insertValues.add(valueMap); + insertValues.add(valueMap); + insertTokens.clear(); + insertTokens.add(tokenMap); + InsertRequest insertRequest1 = InsertRequest.builder() + .table(table) + .values(insertValues) + .tokens(insertTokens) + .tokenMode(TokenMode.ENABLE) + .returnTokens(false) + .build(); + RecordServiceBatchOperationBody body1 = vaultClient.getBatchInsertRequestBody(insertRequest1); + Assert.assertTrue(body1.getContinueOnError()); + Assert.assertEquals(2, body1.getRecords().size()); + + InsertRequest insertRequest2 = InsertRequest.builder().table(table).values(insertValues).build(); + RecordServiceBatchOperationBody body2 = vaultClient.getBatchInsertRequestBody(insertRequest2); + Assert.assertEquals(2, body2.getRecords().size()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetUpdateRequestBodyWithTokens() { + try { + valueMap.clear(); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.clear(); + tokenMap.put("test_column_1", "test_token_1"); + UpdateRequest updateRequest = UpdateRequest.builder() + .table(table) + .data(valueMap) + .tokens(tokenMap) + .returnTokens(true) + .build(); + RecordServiceUpdateRecordBody body = vaultClient.getUpdateRequestBody(updateRequest); + Assert.assertTrue(body.getTokenization()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetUpdateRequestBodyWithoutTokens() { + try { + valueMap.clear(); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.clear(); + tokenMap.put("test_column_1", "test_token_1"); + UpdateRequest updateRequest = UpdateRequest.builder() + .table(table) + .data(valueMap) + .returnTokens(false) + .build(); + RecordServiceUpdateRecordBody body = vaultClient.getUpdateRequestBody(updateRequest); + Assert.assertFalse(body.getTokenization()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetTokenizePayload() { + try { + ColumnValue columnValue = ColumnValue.builder().value(value).columnGroup(columnGroup).build(); + List columnValues = new ArrayList<>(); + columnValues.add(columnValue); + TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); + V1TokenizePayload payload = vaultClient.getTokenizePayload(tokenizeRequest); + Assert.assertEquals(1, payload.getTokenizationParameters().size()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testSetBearerToken() { + try { + Dotenv dotenv = Dotenv.load(); + String bearerToken = dotenv.get("TEST_HUNDRED_TOKEN"); + Credentials credentials = new Credentials(); + credentials.setToken(bearerToken); + vaultConfig.setCredentials(credentials); + vaultClient.updateVaultConfig(); + + // regular scenario + vaultClient.setBearerToken(); + + // re-use scenario + vaultClient.setBearerToken(); + HttpBearerAuth auth = (HttpBearerAuth) vaultClient.getApiClient().getAuthentication("Bearer"); + Assert.assertEquals(bearerToken, auth.getBearerToken()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testSetBearerTokenWithApiKey() { + try { + Credentials credentials = new Credentials(); + credentials.setApiKey(apiKey); + vaultConfig.setCredentials(null); + vaultClient.updateVaultConfig(); + vaultClient.setCommonCredentials(credentials); + + // regular scenario + vaultClient.setBearerToken(); + + // re-use scenario + vaultClient.setBearerToken(); + HttpBearerAuth auth = (HttpBearerAuth) vaultClient.getApiClient().getAuthentication("Bearer"); + Assert.assertEquals(apiKey, auth.getBearerToken()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testSetBearerTokenWithEnvCredentials() { + try { + vaultConfig.setCredentials(null); + vaultClient.updateVaultConfig(); + vaultClient.setCommonCredentials(null); + Assert.assertNull(vaultClient.getVaultConfig().getCredentials()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} From 8b1e5585cc53669be39b837c2e9de2f0f2bbe1e7 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 6 Dec 2024 14:10:38 +0530 Subject: [PATCH 083/126] SK-1802 Update examples and added unit tests --- .../connection/InvokeConnectionExample.java | 112 ++++++++++------ .../BearerTokenGenerationExample.java | 43 ++++++- ...rerTokenGenerationUsingThreadsExample.java | 66 ++++++---- ...arerTokenGenerationWithContextExample.java | 37 ++++-- .../ScopedTokenGenerationExample.java | 53 +++++--- .../SignedTokenGenerationExample.java | 61 ++++++--- .../java/com/example/vault/DeleteExample.java | 82 ++++++++---- .../com/example/vault/DetokenizeExample.java | 89 +++++++++---- .../java/com/example/vault/GetExample.java | 90 ++++++++----- .../java/com/example/vault/InsertExample.java | 121 +++++++++++------- .../java/com/example/vault/QueryExample.java | 72 ++++++++--- .../com/example/vault/TokenizeExample.java | 110 +++++++++++----- .../java/com/example/vault/UpdateExample.java | 106 +++++++++------ .../java/com/skyflow/config/VaultConfig.java | 9 -- .../utils/validations/Validations.java | 2 + .../skyflow/config/ConnectionConfigTests.java | 2 +- .../com/skyflow/config/CredentialsTests.java | 16 +++ .../com/skyflow/config/VaultConfigTests.java | 1 + .../connection/InvokeConnectionTests.java | 24 ++++ .../java/com/skyflow/vault/data/GetTests.java | 43 ++++++- .../com/skyflow/vault/data/InsertTests.java | 33 ++++- .../com/skyflow/vault/data/UpdateTests.java | 80 ++++++++++-- .../skyflow/vault/tokens/DetokenizeTests.java | 21 ++- .../skyflow/vault/tokens/TokenizeTests.java | 28 ++++ 24 files changed, 937 insertions(+), 364 deletions(-) diff --git a/samples/src/main/java/com/example/connection/InvokeConnectionExample.java b/samples/src/main/java/com/example/connection/InvokeConnectionExample.java index 431fd79d..bae6a416 100644 --- a/samples/src/main/java/com/example/connection/InvokeConnectionExample.java +++ b/samples/src/main/java/com/example/connection/InvokeConnectionExample.java @@ -12,57 +12,93 @@ import java.util.HashMap; import java.util.Map; +/** + * This example demonstrates how to use the Skyflow SDK to invoke connections for different endpoints with different configurations. + * It includes: + * 1. Setting up connection configurations. + * 2. Creating a Skyflow client. + * 3. Sending POST and GET requests to connections. + */ public class InvokeConnectionExample { public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the first connection configuration Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); // Replace with the path to the credentials file + // Step 2: Configure the first connection (Connection 1) ConnectionConfig connectionConfig1 = new ConnectionConfig(); - connectionConfig1.setConnectionId(""); - connectionConfig1.setConnectionUrl(""); - connectionConfig1.setCredentials(credentials); + connectionConfig1.setConnectionId(""); // Replace with the ID of the first connection + connectionConfig1.setConnectionUrl(""); // Replace with the URL of the first connection + connectionConfig1.setCredentials(credentials); // Associate credentials for the first connection + // Step 3: Configure the second connection (Connection 2) ConnectionConfig connectionConfig2 = new ConnectionConfig(); - connectionConfig2.setConnectionId(""); - connectionConfig2.setConnectionUrl(""); + connectionConfig2.setConnectionId(""); // Replace with the ID of the second connection + connectionConfig2.setConnectionUrl(""); // Replace with the URL of the second connection + // Step 4: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); + skyflowCredentials.setPath(""); // Replace with the path to another credentials file + // Step 5: Create a Skyflow client and add connection configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) - .addConnectionConfig(connectionConfig1) - .addConnectionConfig(connectionConfig2) - .addSkyflowCredentials(skyflowCredentials) + .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .addConnectionConfig(connectionConfig1) // Add the first connection configuration + .addConnectionConfig(connectionConfig2) // Add the second connection configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - Map requestBody = new HashMap<>(); - requestBody.put("", ""); - requestBody.put("", ""); - Map requestHeaders = new HashMap<>(); - requestHeaders.put("", ""); - requestHeaders.put("", ""); - InvokeConnectionRequest invokeConnectionRequest1 = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) - .requestBody(requestBody) - .requestHeaders(requestHeaders) - .build(); - InvokeConnectionResponse invokeConnectionResponse1 = skyflowClient.connection().invoke(invokeConnectionRequest1); - System.out.println(invokeConnectionResponse1); + // Example 1: Sending a POST request to the first connection + try { + // Set up the request body and headers for the POST request + Map requestBody = new HashMap<>(); + requestBody.put("", ""); // Replace with the actual column name and value + requestBody.put("", ""); // Replace with another column name and value - Map pathParams = new HashMap<>(); - pathParams.put("", ""); - pathParams.put("", ""); - Map queryParams = new HashMap<>(); - queryParams.put("", ""); - queryParams.put("", ""); - InvokeConnectionRequest invokeConnectionRequest2 = InvokeConnectionRequest.builder() - .methodName(RequestMethod.GET) - .pathParams(pathParams) - .queryParams(queryParams) - .build(); - InvokeConnectionResponse invokeConnectionResponse2 = skyflowClient - .connection("").invoke(invokeConnectionRequest2); - System.out.println(invokeConnectionResponse2); + Map requestHeaders = new HashMap<>(); + requestHeaders.put("", ""); // Replace with header name and value + requestHeaders.put("", ""); // Replace with another header name and value + + // Build the POST request to invoke the connection + InvokeConnectionRequest invokeConnectionRequest1 = InvokeConnectionRequest.builder() + .methodName(RequestMethod.POST) // Set the HTTP method to POST + .requestBody(requestBody) // Set the request body + .requestHeaders(requestHeaders) // Set the request headers + .build(); + + // Execute the POST request to the first connection + InvokeConnectionResponse invokeConnectionResponse1 = skyflowClient.connection().invoke(invokeConnectionRequest1); + System.out.println("Invoke Connection Response (POST): " + invokeConnectionResponse1); // Print the response + } catch (SkyflowException e) { + System.out.println("Error while invoking connection (POST):"); + e.printStackTrace(); + } + + // Example 2: Sending a GET request to the second connection + try { + // Set up path parameters and query parameters for the GET request + Map pathParams = new HashMap<>(); + pathParams.put("", ""); // Replace with path parameters + pathParams.put("", ""); // Replace with another path parameter + + Map queryParams = new HashMap<>(); + queryParams.put("", ""); // Replace with query parameters + queryParams.put("", ""); // Replace with another query parameter + + // Build the GET request to invoke the connection + InvokeConnectionRequest invokeConnectionRequest2 = InvokeConnectionRequest.builder() + .methodName(RequestMethod.GET) // Set the HTTP method to GET + .pathParams(pathParams) // Set the path parameters + .queryParams(queryParams) // Set the query parameters + .build(); + + // Execute the GET request to the second connection + InvokeConnectionResponse invokeConnectionResponse2 = skyflowClient + .connection("").invoke(invokeConnectionRequest2); // Invoke connection with ID 2 + System.out.println("Invoke Connection Response (GET): " + invokeConnectionResponse2); // Print the response + } catch (SkyflowException e) { + System.out.println("Error while invoking connection (GET):"); + e.printStackTrace(); + } } } diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java index 5dbd6372..c4578545 100644 --- a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java @@ -6,32 +6,61 @@ import java.io.File; +/** + * Example program to generate a Bearer Token using Skyflow's BearerToken utility. + * The token can be generated in two ways: + * 1. Using the file path to a credentials.json file. + * 2. Using the JSON content of the credentials file as a string. + */ public class BearerTokenGenerationExample { public static void main(String[] args) { + // Variable to store the generated token String token = null; - // Generate BearerToken by specifying credentials.json file path + // Example 1: Generate Bearer Token using a credentials.json file try { + // Specify the full file path to the credentials.json file String filePath = ""; + + // Check if the token is either not initialized or has expired if (Token.isExpired(token)) { - BearerToken bearerToken = BearerToken.builder().setCredentials(new File(filePath)).build(); + // Create a BearerToken object using the credentials file + BearerToken bearerToken = BearerToken.builder() + .setCredentials(new File(filePath)) // Set credentials from the file path + .build(); + + // Generate a new Bearer Token token = bearerToken.getBearerToken(); } - System.out.println(token); + + // Print the generated Bearer Token to the console + System.out.println("Generated Bearer Token (from file): " + token); } catch (SkyflowException e) { + // Handle any exceptions encountered during the token generation process e.printStackTrace(); } - // Generate BearerToken by specifying credentials.json as string + // Example 2: Generate Bearer Token using the credentials JSON as a string try { + // Provide the credentials JSON content as a string String fileContents = ""; + + // Check if the token is either not initialized or has expired if (Token.isExpired(token)) { - BearerToken bearerToken = BearerToken.builder().setCredentials(fileContents).build(); + // Create a BearerToken object using the credentials string + BearerToken bearerToken = BearerToken.builder() + .setCredentials(fileContents) // Set credentials from the string + .build(); + + // Generate a new Bearer Token token = bearerToken.getBearerToken(); } - System.out.println(token); + + // Print the generated Bearer Token to the console + System.out.println("Generated Bearer Token (from string): " + token); } catch (SkyflowException e) { + // Handle any exceptions encountered during the token generation process e.printStackTrace(); } } -} \ No newline at end of file +} diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java index 8cfba8fa..30d8f9ba 100644 --- a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java @@ -5,56 +5,68 @@ import java.io.File; +/** + * This example demonstrates how to generate Bearer tokens in two different ways: + * 1. Using a credentials file specified by its file path. + * 2. Using the credentials as a string. + *

+ * The code also showcases multithreaded token generation with a shared context (`ctx`), + * where each thread generates and prints tokens repeatedly. + */ public class BearerTokenGenerationUsingThreadsExample { public static void main(String[] args) { - // Generate BearerToken with context by specifying credentials.json file path + // Example 1: Generate Bearer token using a credentials file path try { - String filePath = ""; + // Step 1: Specify the path to the credentials file + String filePath = ""; // Replace with the actual file path + + // Step 2: Create a BearerToken object using the file path final BearerToken bearerToken = BearerToken.builder() - .setCredentials(new File(filePath)) - .setCtx("abc") + .setCredentials(new File(filePath)) // Provide the credentials file + .setCtx("abc") // Specify a context string ("abc" in this case) .build(); + // Step 3: Create and start a thread to repeatedly generate and print tokens Thread t = new Thread(() -> { - for (int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) { // Loop to generate tokens 5 times try { - System.out.println(bearerToken.getBearerToken()); - } catch (SkyflowException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException(e); - + System.out.println(bearerToken.getBearerToken()); // Print the Bearer token + } catch (SkyflowException e) { // Handle exceptions during token generation + Thread.currentThread().interrupt(); // Interrupt the thread on error + throw new RuntimeException(e); // Wrap and propagate the exception } - } }); - t.start(); - } catch (Exception e) { + t.start(); // Start the thread + } catch (Exception e) { // Handle exceptions during BearerToken creation e.printStackTrace(); } - // Generate BearerToken with context by specifying credentials.json as string + // Example 2: Generate Bearer token using credentials as a string try { - String fileContents = ""; + // Step 1: Specify the credentials as a string (file contents) + String fileContents = ""; // Replace with actual file contents + + // Step 2: Create a BearerToken object using the credentials string final BearerToken bearerToken = BearerToken.builder() - .setCredentials(fileContents) - .setCtx("abc") + .setCredentials(fileContents) // Provide the credentials as a string + .setCtx("abc") // Specify a context string ("abc" in this case) .build(); + // Step 3: Create and start a thread to repeatedly generate and print tokens Thread t = new Thread(() -> { - for (int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) { // Loop to generate tokens 5 times try { - System.out.println(bearerToken.getBearerToken()); - } catch (SkyflowException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException(e); - + System.out.println(bearerToken.getBearerToken()); // Print the Bearer token + } catch (SkyflowException e) { // Handle exceptions during token generation + Thread.currentThread().interrupt(); // Interrupt the thread on error + throw new RuntimeException(e); // Wrap and propagate the exception } - } }); - t.start(); - } catch (Exception e) { + t.start(); // Start the thread + } catch (Exception e) { // Handle exceptions during BearerToken creation e.printStackTrace(); } } -} \ No newline at end of file +} diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java index b85de6df..3ed9e267 100644 --- a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java @@ -5,35 +5,56 @@ import java.io.File; +/** + * Example program to generate a Bearer Token using Skyflow's BearerToken utility. + * The token is generated using two approaches: + * 1. By providing the credentials.json file path. + * 2. By providing the contents of credentials.json as a string. + */ public class BearerTokenGenerationWithContextExample { public static void main(String[] args) { + // Variable to store the generated Bearer Token String bearerToken = null; - // Generate BearerToken with context by specifying credentials.json file path + // Approach 1: Generate Bearer Token by specifying the path to the credentials.json file try { + // Replace with the full path to your credentials.json file String filePath = ""; + + // Create a BearerToken object using the file path BearerToken token = BearerToken.builder() - .setCredentials(new File(filePath)) - .setCtx("abc") - .build(); + .setCredentials(new File(filePath)) // Set credentials using a File object + .setCtx("abc") // Set context string (example: "abc") + .build(); // Build the BearerToken object + // Retrieve the Bearer Token as a string bearerToken = token.getBearerToken(); + + // Print the generated Bearer Token to the console System.out.println(bearerToken); } catch (SkyflowException e) { + // Handle exceptions specific to Skyflow operations e.printStackTrace(); } - // Generate BearerToken with context by specifying credentials.json as string + // Approach 2: Generate Bearer Token by specifying the contents of credentials.json as a string try { + // Replace with the actual contents of your credentials.json file String fileContents = ""; + + // Create a BearerToken object using the file contents as a string BearerToken token = BearerToken.builder() - .setCredentials(fileContents) - .setCtx("abc") - .build(); + .setCredentials(fileContents) // Set credentials using a string representation of the file + .setCtx("abc") // Set context string (example: "abc") + .build(); // Build the BearerToken object + // Retrieve the Bearer Token as a string bearerToken = token.getBearerToken(); + + // Print the generated Bearer Token to the console System.out.println(bearerToken); } catch (SkyflowException e) { + // Handle exceptions specific to Skyflow operations e.printStackTrace(); } } diff --git a/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java b/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java index 3fda1e07..3cba8bd5 100644 --- a/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java +++ b/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java @@ -6,40 +6,61 @@ import java.io.File; import java.util.ArrayList; +/** + * This example demonstrates how to generate a Scoped Bearer Token in two ways: + * 1. Using a credentials file specified by its file path. + * 2. Using the credentials as a string. + *

+ * Scoped tokens are generated by assigning specific roles for access control. + */ public class ScopedTokenGenerationExample { public static void main(String[] args) { - String scopedToken = null; + String scopedToken = null; // Variable to store the generated Scoped Bearer Token - // Generate Scoped Token by specifying credentials.json file path + // Example 1: Generate Scoped Token using a credentials file path try { + // Step 1: Specify the roles required for the scoped token ArrayList roles = new ArrayList<>(); - roles.add("YOUR_ROLE_ID"); - String filePath = ""; + roles.add("YOUR_ROLE_ID"); // Replace with your actual role ID + + // Step 2: Specify the path to the credentials file + String filePath = ""; // Replace with the actual file path + + // Step 3: Create a BearerToken object using the file path and roles BearerToken bearerToken = BearerToken.builder() - .setCredentials(new File(filePath)) - .setRoles(roles) + .setCredentials(new File(filePath)) // Provide the credentials file + .setRoles(roles) // Set the roles for the scoped token .build(); + // Step 4: Generate and print the Scoped Bearer Token scopedToken = bearerToken.getBearerToken(); - System.out.println(scopedToken); - } catch (SkyflowException e) { + System.out.println("Scoped Token (using file path): " + scopedToken); + } catch (SkyflowException e) { // Handle exceptions during token generation + System.out.println("Error occurred while generating Scoped Token using file path:"); e.printStackTrace(); } - // Generate BearerToken with context by specifying credentials.json as string + // Example 2: Generate Scoped Token using credentials as a string try { + // Step 1: Specify the roles required for the scoped token ArrayList roles = new ArrayList<>(); - roles.add("YOUR_ROLE_ID"); - String fileContents = ""; + roles.add("YOUR_ROLE_ID"); // Replace with your actual role ID + + // Step 2: Specify the credentials as a string (file contents) + String fileContents = ""; // Replace with actual file contents + + // Step 3: Create a BearerToken object using the credentials string and roles BearerToken bearerToken = BearerToken.builder() - .setCredentials(fileContents) - .setRoles(roles) + .setCredentials(fileContents) // Provide the credentials as a string + .setRoles(roles) // Set the roles for the scoped token .build(); + // Step 4: Generate and print the Scoped Bearer Token scopedToken = bearerToken.getBearerToken(); - System.out.println(scopedToken); - } catch (SkyflowException e) { + System.out.println("Scoped Token (using credentials string): " + scopedToken); + } catch (SkyflowException e) { // Handle exceptions during token generation + System.out.println("Error occurred while generating Scoped Token using credentials string:"); e.printStackTrace(); } } -} \ No newline at end of file +} diff --git a/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java b/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java index 0acca5fe..98f552f3 100644 --- a/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java +++ b/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java @@ -8,48 +8,67 @@ import java.util.ArrayList; import java.util.List; +/** + * This example demonstrates how to generate Signed Data Tokens using two methods: + * 1. Specifying the path to a credentials JSON file. + * 2. Providing the credentials JSON as a string. + *

+ * Signed data tokens are used to verify and securely transmit data with a specified context and TTL. + */ public class SignedTokenGenerationExample { public static void main(String[] args) { - List signedTokenValues; + List signedTokenValues; // List to store signed data token responses - // Generate Signed data token with context by specifying credentials.json file path + // Example 1: Generate Signed Data Token using a credentials file path try { - String filePath = ""; - String context = "abc"; + // Step 1: Specify the path to the service account credentials JSON file + String filePath = ""; // Replace with the actual file path + + // Step 2: Set the context and create the list of data tokens to be signed + String context = "abc"; // Replace with your specific context (e.g., session identifier) ArrayList dataTokens = new ArrayList<>(); - dataTokens.add("YOUR_DATA_TOKEN_1"); + dataTokens.add("YOUR_DATA_TOKEN_1"); // Replace with your actual data token(s) + + // Step 3: Build the SignedDataTokens object SignedDataTokens signedToken = SignedDataTokens.builder() - .setCredentials(new File(filePath)) - .setCtx(context) - .setTimeToLive(30) // in seconds - .setDataTokens(dataTokens) + .setCredentials(new File(filePath)) // Provide the credentials file + .setCtx(context) // Set the context for the token + .setTimeToLive(30) // Set the TTL (in seconds) + .setDataTokens(dataTokens) // Set the data tokens to sign .build(); + // Step 4: Retrieve and print the signed data tokens signedTokenValues = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValues); + System.out.println("Signed Tokens (using file path): " + signedTokenValues); } catch (SkyflowException e) { + System.out.println("Error occurred while generating signed tokens using file path:"); e.printStackTrace(); } - // Generate Signed data token with context by specifying credentials.json as string + // Example 2: Generate Signed Data Token using credentials JSON as a string try { - String fileContents = ""; - String context = "abc"; + // Step 1: Provide the contents of the credentials JSON file as a string + String fileContents = ""; // Replace with actual JSON content + + // Step 2: Set the context and create the list of data tokens to be signed + String context = "abc"; // Replace with your specific context ArrayList dataTokens = new ArrayList<>(); - dataTokens.add("YOUR_DATA_TOKEN_1"); + dataTokens.add("YOUR_DATA_TOKEN_1"); // Replace with your actual data token(s) + + // Step 3: Build the SignedDataTokens object SignedDataTokens signedToken = SignedDataTokens.builder() - .setCredentials(fileContents) - .setCtx(context) - .setTimeToLive(30) // in seconds - .setDataTokens(dataTokens) + .setCredentials(fileContents) // Provide the credentials as a string + .setCtx(context) // Set the context for the token + .setTimeToLive(30) // Set the TTL (in seconds) + .setDataTokens(dataTokens) // Set the data tokens to sign .build(); + // Step 4: Retrieve and print the signed data tokens signedTokenValues = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValues); - + System.out.println("Signed Tokens (using credentials string): " + signedTokenValues); } catch (SkyflowException e) { + System.out.println("Error occurred while generating signed tokens using credentials string:"); e.printStackTrace(); } } } - diff --git a/samples/src/main/java/com/example/vault/DeleteExample.java b/samples/src/main/java/com/example/vault/DeleteExample.java index d14554ce..bd6122cd 100644 --- a/samples/src/main/java/com/example/vault/DeleteExample.java +++ b/samples/src/main/java/com/example/vault/DeleteExample.java @@ -11,42 +11,76 @@ import java.util.ArrayList; +/** + * This example demonstrates how to use the Skyflow SDK to delete records from one or more vaults + * by specifying the vault configurations, credentials, and record IDs to delete. + *

+ * Steps include: + * 1. Setting up vault configurations. + * 2. Creating a Skyflow client. + * 3. Deleting records from the specified vault(s) using record IDs and table names. + */ public class DeleteExample { public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the first vault configuration Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); // Replace with the actual path to the credentials file + // Step 2: Configure the first vault (Blitz) VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); - blitzConfig.setEnv(Env.DEV); - blitzConfig.setCredentials(credentials); + blitzConfig.setVaultId(""); // Replace with the ID of the first vault + blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault + blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) + blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 3: Configure the second vault (Stage) VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); - stageConfig.setEnv(Env.STAGE); + stageConfig.setVaultId(""); // Replace with the ID of the second vault + stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault + stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault + // Step 4: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); + skyflowCredentials.setPath(""); // Replace with the path to another credentials file + // Step 5: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) - .addVaultConfig(blitzConfig) - .addVaultConfig(stageConfig) - .addSkyflowCredentials(skyflowCredentials) + .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .addVaultConfig(blitzConfig) // Add the first vault configuration + .addVaultConfig(stageConfig) // Add the second vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - ArrayList ids1 = new ArrayList<>(); - ids1.add(""); - DeleteRequest deleteRequest1 = DeleteRequest.builder().ids(ids1).table("").build(); - DeleteResponse deleteResponse1 = skyflowClient.vault().delete(deleteRequest1); - System.out.println(deleteResponse1); - - ArrayList ids2 = new ArrayList<>(); - ids2.add(""); - DeleteRequest deleteRequest2 = DeleteRequest.builder().ids(ids2).table("").build(); - DeleteResponse deleteResponse2 = skyflowClient.vault("").delete(deleteRequest2); - System.out.println(deleteResponse2); + // Example 1: Delete a record from the first vault + try { + ArrayList ids1 = new ArrayList<>(); + ids1.add(""); // Replace with the ID of the record to delete + DeleteRequest deleteRequest1 = DeleteRequest.builder() + .ids(ids1) // Specify the record IDs to delete + .table("") // Replace with the table name + .build(); + + DeleteResponse deleteResponse1 = skyflowClient.vault().delete(deleteRequest1); // Perform the delete operation + System.out.println("Delete Response (Vault 1): " + deleteResponse1); + } catch (SkyflowException e) { + System.out.println("Error during delete operation in Vault 1:"); + e.printStackTrace(); + } + + // Example 2: Delete a record from the second vault + try { + ArrayList ids2 = new ArrayList<>(); + ids2.add(""); // Replace with the ID of the record to delete + DeleteRequest deleteRequest2 = DeleteRequest.builder() + .ids(ids2) // Specify the record IDs to delete + .table("") // Replace with the table name + .build(); + + DeleteResponse deleteResponse2 = skyflowClient.vault("").delete(deleteRequest2); // Perform the delete operation + System.out.println("Delete Response (Vault 2): " + deleteResponse2); + } catch (SkyflowException e) { + System.out.println("Error during delete operation in Vault 2:"); + e.printStackTrace(); + } } } diff --git a/samples/src/main/java/com/example/vault/DetokenizeExample.java b/samples/src/main/java/com/example/vault/DetokenizeExample.java index cd6d38ad..f25d2be0 100644 --- a/samples/src/main/java/com/example/vault/DetokenizeExample.java +++ b/samples/src/main/java/com/example/vault/DetokenizeExample.java @@ -12,46 +12,79 @@ import java.util.ArrayList; +/** + * This example demonstrates how to use the Skyflow SDK to detokenize sensitive data. + * The steps include: + * 1. Setting up vault configurations. + * 2. Creating a Skyflow client. + * 3. Detokenizing tokens from specified vaults. + */ public class DetokenizeExample { public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the first vault configuration Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); // Replace with the actual path to the credentials file + // Step 2: Configure the first vault (Blitz) VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); - blitzConfig.setEnv(Env.DEV); - blitzConfig.setCredentials(credentials); + blitzConfig.setVaultId(""); // Replace with the ID of the first vault + blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault + blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) + blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 3: Configure the second vault (Stage) VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); - stageConfig.setEnv(Env.STAGE); + stageConfig.setVaultId(""); // Replace with the ID of the second vault + stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault + stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault + // Step 4: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); + skyflowCredentials.setPath(""); // Replace with the path to another credentials file + // Step 5: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) - .addVaultConfig(blitzConfig) - .addVaultConfig(stageConfig) - .addSkyflowCredentials(skyflowCredentials) + .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .addVaultConfig(blitzConfig) // Add the first vault configuration + .addVaultConfig(stageConfig) // Add the second vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - ArrayList tokens1 = new ArrayList<>(); - tokens1.add(""); - tokens1.add(""); - DetokenizeRequest detokenizeRequest1 = DetokenizeRequest.builder().tokens(tokens1).continueOnError(true).build(); - DetokenizeResponse detokenizeResponse1 = skyflowClient.vault().detokenize(detokenizeRequest1); - System.out.println(detokenizeResponse1); - - ArrayList tokens2 = new ArrayList<>(); - tokens2.add(""); - tokens2.add(""); - - DetokenizeRequest detokenizeRequest2 = DetokenizeRequest.builder() - .tokens(tokens2).continueOnError(false).redactionType(RedactionType.DEFAULT).build(); - DetokenizeResponse detokenizeResponse2 = skyflowClient.vault("").detokenize(detokenizeRequest2); - System.out.println(detokenizeResponse2); + // Example 1: Detokenize tokens from the first vault + try { + ArrayList tokens1 = new ArrayList<>(); + tokens1.add(""); // Replace with the first token to detokenize + tokens1.add(""); // Replace with the second token to detokenize + + DetokenizeRequest detokenizeRequest1 = DetokenizeRequest.builder() + .tokens(tokens1) // Specify the tokens to detokenize + .continueOnError(true) // Continue processing even if an error occurs for some tokens + .build(); + + DetokenizeResponse detokenizeResponse1 = skyflowClient.vault().detokenize(detokenizeRequest1); // Perform detokenization + System.out.println("Detokenize Response (Vault 1): " + detokenizeResponse1); + } catch (SkyflowException e) { + System.out.println("Error during detokenization in Vault 1:"); + e.printStackTrace(); + } + + // Example 2: Detokenize tokens from the second vault + try { + ArrayList tokens2 = new ArrayList<>(); + tokens2.add(""); // Replace with the first token to detokenize + tokens2.add(""); // Replace with the second token to detokenize + + DetokenizeRequest detokenizeRequest2 = DetokenizeRequest.builder() + .tokens(tokens2) // Specify the tokens to detokenize + .continueOnError(false) // Stop processing on the first error + .redactionType(RedactionType.DEFAULT) // Use the default redaction type for detokenization + .build(); + + DetokenizeResponse detokenizeResponse2 = skyflowClient.vault("").detokenize(detokenizeRequest2); // Perform detokenization + System.out.println("Detokenize Response (Vault 2): " + detokenizeResponse2); + } catch (SkyflowException e) { + System.out.println("Error during detokenization in Vault 2:"); + e.printStackTrace(); + } } } diff --git a/samples/src/main/java/com/example/vault/GetExample.java b/samples/src/main/java/com/example/vault/GetExample.java index 5dda25d3..a25f580f 100644 --- a/samples/src/main/java/com/example/vault/GetExample.java +++ b/samples/src/main/java/com/example/vault/GetExample.java @@ -12,47 +12,79 @@ import java.util.ArrayList; +/** + * This example demonstrates how to use the Skyflow SDK to fetch sensitive data securely. + * The steps include: + * 1. Setting up vault configurations. + * 2. Creating a Skyflow client. + * 3. Retrieving records using Skyflow IDs and column values. + */ public class GetExample { public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the first vault configuration Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); // Replace with the actual path to the credentials file + // Step 2: Configure the first vault (Blitz) VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); - blitzConfig.setEnv(Env.DEV); - blitzConfig.setCredentials(credentials); + blitzConfig.setVaultId(""); // Replace with the ID of the first vault + blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault + blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) + blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 3: Configure the second vault (Stage) VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); - stageConfig.setEnv(Env.STAGE); + stageConfig.setVaultId(""); // Replace with the ID of the second vault + stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault + stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault + // Step 4: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); + skyflowCredentials.setPath(""); // Replace with the path to another credentials file + // Step 5: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) - .addVaultConfig(blitzConfig) - .addVaultConfig(stageConfig) - .addSkyflowCredentials(skyflowCredentials) + .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .addVaultConfig(blitzConfig) // Add the first vault configuration + .addVaultConfig(stageConfig) // Add the second vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - ArrayList ids = new ArrayList<>(); - ids.add(""); - GetRequest getByIdRequest = GetRequest.builder().returnTokens(true).ids(ids).table("").build(); - GetResponse getByIdResponse = skyflowClient.vault().get(getByIdRequest); - System.out.println(getByIdResponse); - - ArrayList columnValues = new ArrayList<>(); - columnValues.add(""); - GetRequest getByColumnRequest = GetRequest.builder() - .table("") - .columnName("") - .columnValues(columnValues) - .redactionType(RedactionType.PLAIN_TEXT) - .build(); - GetResponse getByColumnResponse = skyflowClient.vault("").get(getByColumnRequest); - System.out.println(getByColumnResponse); + // Example 1: Fetch records by Skyflow IDs from the first vault + try { + ArrayList ids = new ArrayList<>(); + ids.add(""); // Replace with the Skyflow ID to fetch the record + + GetRequest getByIdRequest = GetRequest.builder() + .returnTokens(true) // Return tokens along with the fetched data + .ids(ids) // Specify the list of Skyflow IDs + .table("") // Replace with the table name + .build(); + + GetResponse getByIdResponse = skyflowClient.vault().get(getByIdRequest); // Perform the get operation + System.out.println("Get Response (By ID): " + getByIdResponse); + } catch (SkyflowException e) { + System.out.println("Error during fetch by ID:"); + e.printStackTrace(); + } + + // Example 2: Fetch records by column values from the second vault + try { + ArrayList columnValues = new ArrayList<>(); + columnValues.add(""); // Replace with the column value to fetch the record + + GetRequest getByColumnRequest = GetRequest.builder() + .table("") // Replace with the table name + .columnName("") // Replace with the column name + .columnValues(columnValues) // Specify the list of column values + .redactionType(RedactionType.PLAIN_TEXT) // Fetch the data in plain text format + .build(); + + GetResponse getByColumnResponse = skyflowClient.vault("").get(getByColumnRequest); // Fetch from the second vault + System.out.println("Get Response (By Column): " + getByColumnResponse); + } catch (SkyflowException e) { + System.out.println("Error during fetch by column:"); + e.printStackTrace(); + } } } diff --git a/samples/src/main/java/com/example/vault/InsertExample.java b/samples/src/main/java/com/example/vault/InsertExample.java index 20070e83..3aa5309c 100644 --- a/samples/src/main/java/com/example/vault/InsertExample.java +++ b/samples/src/main/java/com/example/vault/InsertExample.java @@ -13,69 +13,96 @@ import java.util.ArrayList; import java.util.HashMap; +/** + * This example demonstrates how to use the Skyflow SDK to securely insert records into a vault. + * It includes: + * 1. Setting up vault configurations. + * 2. Creating a Skyflow client. + * 3. Performing record insertion with and without BYOT (Bring Your Own Token). + * 4. Using upsert functionality to handle conflicts. + */ public class InsertExample { public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the first vault configuration Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); // Replace with the path to the credentials file + // Step 2: Configure the first vault (Blitz) VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); - blitzConfig.setEnv(Env.DEV); - blitzConfig.setCredentials(credentials); + blitzConfig.setVaultId(""); // Replace with the ID of the first vault + blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault + blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) + blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 3: Configure the second vault (Stage) VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); - stageConfig.setEnv(Env.STAGE); + stageConfig.setVaultId(""); // Replace with the ID of the second vault + stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault + stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault + // Step 4: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); + skyflowCredentials.setPath(""); // Replace with the path to another credentials file + // Step 5: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) - .addVaultConfig(blitzConfig) - .addVaultConfig(stageConfig) - .addSkyflowCredentials(skyflowCredentials) + .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .addVaultConfig(blitzConfig) // Add the first vault configuration + .addVaultConfig(stageConfig) // Add the second vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - ArrayList> values1 = new ArrayList<>(); - HashMap value1 = new HashMap<>(); - value1.put("", ""); - value1.put("", ""); - values1.add(value1); + // Example 1: Insert records into the first vault with BYOT enabled + try { + ArrayList> values1 = new ArrayList<>(); + HashMap value1 = new HashMap<>(); + value1.put("", ""); // Replace with column name and value + value1.put("", ""); // Replace with another column name and value + values1.add(value1); - ArrayList> tokens = new ArrayList<>(); - HashMap token = new HashMap<>(); - token.put("", ""); - tokens.add(token); + ArrayList> tokens = new ArrayList<>(); + HashMap token = new HashMap<>(); + token.put("", ""); // Replace with the token for COLUMN_NAME_2 + tokens.add(token); - InsertRequest insertRequest = InsertRequest.builder() - .table("") - .continueOnError(true) - .tokenStrict(Byot.ENABLE) - .values(values1) - .tokens(tokens) - .returnTokens(true) - .build(); - InsertResponse insertResponse = skyflowClient.vault().insert(insertRequest); - System.out.println(insertResponse); + InsertRequest insertRequest = InsertRequest.builder() + .table("") // Replace with the table name + .continueOnError(true) // Continue inserting even if some records fail + .tokenStrict(Byot.ENABLE) // Enable BYOT for token validation + .values(values1) // Data to insert + .tokens(tokens) // Provide tokens for BYOT columns + .returnTokens(true) // Return tokens along with the response + .build(); - ArrayList> values2 = new ArrayList<>(); - HashMap value2 = new HashMap<>(); - value2.put("", ""); - value2.put("", ""); - values2.add(value2); + InsertResponse insertResponse = skyflowClient.vault().insert(insertRequest); // Perform the insertion + System.out.println("Insert Response (BYOT Enabled): " + insertResponse); + } catch (SkyflowException e) { + System.out.println("Error during insertion with BYOT enabled:"); + e.printStackTrace(); + } - InsertRequest upsertRequest = InsertRequest.builder() - .table("") - .continueOnError(false) - .tokenStrict(Byot.DISABLE) - .values(values2) - .returnTokens(false) - .upsert("") - .build(); - InsertResponse upsertResponse = skyflowClient.vault("").insert(upsertRequest); - System.out.println(upsertResponse); + // Example 2: Insert records into the second vault with BYOT disabled and upsert enabled + try { + ArrayList> values2 = new ArrayList<>(); + HashMap value2 = new HashMap<>(); + value2.put("", ""); // Replace with column name and value + value2.put("", ""); // Replace with another column name and value + values2.add(value2); + + InsertRequest upsertRequest = InsertRequest.builder() + .table("") // Replace with the table name + .continueOnError(false) // Stop inserting if any record fails + .tokenStrict(Byot.DISABLE) // Disable BYOT + .values(values2) // Data to insert + .returnTokens(false) // Do not return tokens + .upsert("") // Replace with the column name used for upsert logic + .build(); + + InsertResponse upsertResponse = skyflowClient.vault("").insert(upsertRequest); // Perform the insertion + System.out.println("Insert Response (Upsert Enabled): " + upsertResponse); + } catch (SkyflowException e) { + System.out.println("Error during insertion with upsert enabled:"); + e.printStackTrace(); + } } } diff --git a/samples/src/main/java/com/example/vault/QueryExample.java b/samples/src/main/java/com/example/vault/QueryExample.java index d5928cd5..43f42a82 100644 --- a/samples/src/main/java/com/example/vault/QueryExample.java +++ b/samples/src/main/java/com/example/vault/QueryExample.java @@ -9,41 +9,71 @@ import com.skyflow.vault.data.QueryRequest; import com.skyflow.vault.data.QueryResponse; +/** + * This example demonstrates how to use the Skyflow SDK to perform secure queries on multiple vaults. + * It includes: + * 1. Setting up vault configurations. + * 2. Creating a Skyflow client. + * 3. Performing SQL queries on the vaults. + */ public class QueryExample { public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the first vault configuration Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); // Replace with the path to the credentials file + // Step 2: Configure the first vault (Blitz) VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); - blitzConfig.setEnv(Env.DEV); - blitzConfig.setCredentials(credentials); + blitzConfig.setVaultId(""); // Replace with the ID of the first vault + blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault + blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) + blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 3: Configure the second vault (Stage) VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); - stageConfig.setEnv(Env.STAGE); + stageConfig.setVaultId(""); // Replace with the ID of the second vault + stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault + stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault + // Step 4: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); + skyflowCredentials.setPath(""); // Replace with the path to another credentials file + // Step 5: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) - .addVaultConfig(blitzConfig) - .addVaultConfig(stageConfig) - .addSkyflowCredentials(skyflowCredentials) + .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .addVaultConfig(blitzConfig) // Add the first vault configuration + .addVaultConfig(stageConfig) // Add the second vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - String query1 = ""; - QueryRequest queryRequest1 = QueryRequest.builder().query(query1).build(); - QueryResponse queryResponse1 = skyflowClient.vault().query(queryRequest1); - System.out.println(queryResponse1); + // Example 1: Perform a query on the first vault + try { + String query1 = ""; // Replace with a valid SQL query for the first vault + QueryRequest queryRequest1 = QueryRequest.builder() + .query(query1) // Build the query request + .build(); - String query2 = ""; - QueryRequest queryRequest2 = QueryRequest.builder().query(query2).build(); - QueryResponse queryResponse2 = skyflowClient.vault("").query(queryRequest2); - System.out.println(queryResponse2); + QueryResponse queryResponse1 = skyflowClient.vault().query(queryRequest1); // Execute the query + System.out.println("Query Response (Vault 1): " + queryResponse1); // Print the query response + } catch (SkyflowException e) { + System.out.println("Error while querying Vault 1:"); + e.printStackTrace(); + } + // Example 2: Perform a query on the second vault + try { + String query2 = ""; // Replace with a valid SQL query for the second vault + QueryRequest queryRequest2 = QueryRequest.builder() + .query(query2) // Build the query request + .build(); + + QueryResponse queryResponse2 = skyflowClient.vault("").query(queryRequest2); // Execute the query + System.out.println("Query Response (Vault 2): " + queryResponse2); // Print the query response + } catch (SkyflowException e) { + System.out.println("Error while querying Vault 2:"); + e.printStackTrace(); + } } } + diff --git a/samples/src/main/java/com/example/vault/TokenizeExample.java b/samples/src/main/java/com/example/vault/TokenizeExample.java index 578e7ced..38bd806b 100644 --- a/samples/src/main/java/com/example/vault/TokenizeExample.java +++ b/samples/src/main/java/com/example/vault/TokenizeExample.java @@ -12,48 +12,98 @@ import java.util.ArrayList; +/** + * This example demonstrates how to use the Skyflow SDK to tokenize data using multiple vault configurations. + * It includes: + * 1. Setting up vault configurations. + * 2. Creating a Skyflow client. + * 3. Performing tokenization on the vaults. + */ public class TokenizeExample { public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the first vault configuration Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); // Replace with the path to the credentials file + // Step 2: Configure the first vault (Blitz) VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); - blitzConfig.setEnv(Env.DEV); - blitzConfig.setCredentials(credentials); + blitzConfig.setVaultId(""); // Replace with the ID of the first vault + blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault + blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) + blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 3: Configure the second vault (Stage) VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); - stageConfig.setEnv(Env.STAGE); + stageConfig.setVaultId(""); // Replace with the ID of the second vault + stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault + stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault + // Step 4: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); + skyflowCredentials.setPath(""); // Replace with the path to another credentials file + // Step 5: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) - .addVaultConfig(blitzConfig) - .addVaultConfig(stageConfig) - .addSkyflowCredentials(skyflowCredentials) + .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .addVaultConfig(blitzConfig) // Add the first vault configuration + .addVaultConfig(stageConfig) // Add the second vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - ArrayList columnValues1 = new ArrayList<>(); - ColumnValue value1 = ColumnValue.builder().value("").columnGroup("").build(); - ColumnValue value2 = ColumnValue.builder().value("").columnGroup("").build(); - columnValues1.add(value1); - columnValues1.add(value2); - TokenizeRequest tokenizeRequest1 = TokenizeRequest.builder().values(columnValues1).build(); - TokenizeResponse tokenizeResponse1 = skyflowClient.vault().tokenize(tokenizeRequest1); - System.out.println(tokenizeResponse1); - - ArrayList columnValues2 = new ArrayList<>(); - ColumnValue value3 = ColumnValue.builder().value("").columnGroup("").build(); - ColumnValue value4 = ColumnValue.builder().value("").columnGroup("").build(); - columnValues2.add(value3); - columnValues2.add(value4); - TokenizeRequest tokenizeRequest2 = TokenizeRequest.builder().values(columnValues2).build(); - TokenizeResponse tokenizeResponse2 = skyflowClient.vault("").tokenize(tokenizeRequest2); - System.out.println(tokenizeResponse2); + // Example 1: Tokenize data for the first vault + try { + ArrayList columnValues1 = new ArrayList<>(); + ColumnValue value1 = ColumnValue.builder() + .value("") // Replace with the actual value to tokenize + .columnGroup("") // Replace with the actual column group name + .build(); + ColumnValue value2 = ColumnValue.builder() + .value("") // Replace with another value to tokenize + .columnGroup("") // Replace with the column group name + .build(); + + columnValues1.add(value1); + columnValues1.add(value2); + + // Build the tokenization request + TokenizeRequest tokenizeRequest1 = TokenizeRequest.builder() + .values(columnValues1) // Set the column values to tokenize + .build(); + + // Execute tokenization request + TokenizeResponse tokenizeResponse1 = skyflowClient.vault().tokenize(tokenizeRequest1); + System.out.println("Tokenization Response (Vault 1): " + tokenizeResponse1); // Print the tokenization response + } catch (SkyflowException e) { + System.out.println("Error while tokenizing data for Vault 1:"); + e.printStackTrace(); + } + + // Example 2: Tokenize data for the second vault + try { + ArrayList columnValues2 = new ArrayList<>(); + ColumnValue value3 = ColumnValue.builder() + .value("") // Replace with the actual value to tokenize + .columnGroup("") // Replace with the column group name + .build(); + ColumnValue value4 = ColumnValue.builder() + .value("") // Replace with another value to tokenize + .columnGroup("") // Replace with the column group name + .build(); + + columnValues2.add(value3); + columnValues2.add(value4); + + // Build the tokenization request for the second vault + TokenizeRequest tokenizeRequest2 = TokenizeRequest.builder() + .values(columnValues2) // Set the column values to tokenize + .build(); + + // Execute tokenization request for the second vault + TokenizeResponse tokenizeResponse2 = skyflowClient.vault("").tokenize(tokenizeRequest2); + System.out.println("Tokenization Response (Vault 2): " + tokenizeResponse2); // Print the tokenization response + } catch (SkyflowException e) { + System.out.println("Error while tokenizing data for Vault 2:"); + e.printStackTrace(); + } } } diff --git a/samples/src/main/java/com/example/vault/UpdateExample.java b/samples/src/main/java/com/example/vault/UpdateExample.java index 1508fc25..1a220bb1 100644 --- a/samples/src/main/java/com/example/vault/UpdateExample.java +++ b/samples/src/main/java/com/example/vault/UpdateExample.java @@ -12,62 +12,88 @@ import java.util.HashMap; +/** + * This example demonstrates how to use the Skyflow SDK to securely update records in a vault. + * It includes: + * 1. Setting up vault configurations. + * 2. Creating a Skyflow client. + * 3. Updating records using different configurations and data. + */ public class UpdateExample { public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the first vault configuration Credentials credentials = new Credentials(); - credentials.setPath(""); + credentials.setPath(""); // Replace with the actual path to the credentials file + // Step 2: Configure the first vault (Blitz) VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); - blitzConfig.setClusterId(""); - blitzConfig.setEnv(Env.DEV); - blitzConfig.setCredentials(credentials); + blitzConfig.setVaultId(""); // Replace with the ID of the first vault + blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault + blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) + blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 3: Configure the second vault (Stage) VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); - stageConfig.setClusterId(""); - stageConfig.setEnv(Env.STAGE); + stageConfig.setVaultId(""); // Replace with the ID of the second vault + stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault + stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault + // Step 4: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); + skyflowCredentials.setPath(""); // Replace with the path to another credentials file + // Step 5: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) - .addVaultConfig(blitzConfig) - .addVaultConfig(stageConfig) - .addSkyflowCredentials(skyflowCredentials) + .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .addVaultConfig(blitzConfig) // Add the first vault configuration + .addVaultConfig(stageConfig) // Add the second vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - HashMap values1 = new HashMap<>(); - values1.put("", ""); - values1.put("", ""); + // Example 1: Update records in the first vault with BYOT (Bring Your Own Token) enabled + try { + HashMap data1 = new HashMap<>(); + data1.put("skyflow_id", ""); // Replace with the Skyflow ID of the record + data1.put("", ""); // Replace with column name and value to update + data1.put("", ""); // Replace with another column name and value - HashMap tokens = new HashMap<>(); - tokens.put("", ""); + HashMap tokens = new HashMap<>(); + tokens.put("", ""); // Replace with the token for COLUMN_NAME_2 - UpdateRequest updateRequest1 = UpdateRequest.builder() - .id("") - .table("") - .tokenStrict(Byot.ENABLE) - .values(values1) - .tokens(tokens) - .returnTokens(true) - .build(); - UpdateResponse updateResponse1 = skyflowClient.vault().update(updateRequest1); - System.out.println(updateResponse1); + UpdateRequest updateRequest1 = UpdateRequest.builder() + .table("") // Replace with the table name + .tokenStrict(Byot.ENABLE) // Enable BYOT for token validation + .data(data1) // Data to update + .tokens(tokens) // Provide tokens for BYOT columns + .returnTokens(true) // Return tokens along with the update response + .build(); - HashMap values2 = new HashMap<>(); - values2.put("", ""); - values2.put("", ""); + UpdateResponse updateResponse1 = skyflowClient.vault().update(updateRequest1); // Perform the update + System.out.println("Update Response (BYOT Enabled): " + updateResponse1); + } catch (SkyflowException e) { + System.out.println("Error during update with BYOT enabled:"); + e.printStackTrace(); + } - UpdateRequest updateRequest2 = UpdateRequest.builder() - .id("") - .table("") - .tokenStrict(Byot.DISABLE) - .values(values2) - .returnTokens(false) - .build(); - UpdateResponse updateResponse2 = skyflowClient.vault("").update(updateRequest2); - System.out.println(updateResponse2); + // Example 2: Update records in the second vault with BYOT disabled + try { + HashMap data2 = new HashMap<>(); + data2.put("skyflow_id", ""); // Replace with the Skyflow ID of the record + data2.put("", ""); // Replace with column name and value to update + data2.put("", ""); // Replace with another column name and value + + UpdateRequest updateRequest2 = UpdateRequest.builder() + .table("") // Replace with the table name + .tokenStrict(Byot.DISABLE) // Disable BYOT + .data(data2) // Data to update + .returnTokens(false) // Do not return tokens + .build(); + + UpdateResponse updateResponse2 = skyflowClient.vault("").update(updateRequest2); // Perform the update + System.out.println("Update Response (BYOT Disabled): " + updateResponse2); + } catch (SkyflowException e) { + System.out.println("Error during update with BYOT disabled:"); + e.printStackTrace(); + } } } diff --git a/src/main/java/com/skyflow/config/VaultConfig.java b/src/main/java/com/skyflow/config/VaultConfig.java index fd36d384..4f61af2a 100644 --- a/src/main/java/com/skyflow/config/VaultConfig.java +++ b/src/main/java/com/skyflow/config/VaultConfig.java @@ -46,13 +46,4 @@ public Credentials getCredentials() { public void setCredentials(Credentials credentials) { this.credentials = credentials; } - - @Override - public String toString() { - return "VaultConfig {" + - "\n\tvaultId: '" + vaultId + "'," + - "\n\tclusterId: '" + clusterId + "'," + - "\n\tenv: " + env + - "\n}"; - } } diff --git a/src/main/java/com/skyflow/utils/validations/Validations.java b/src/main/java/com/skyflow/utils/validations/Validations.java index e1e52581..de265e1a 100644 --- a/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/src/main/java/com/skyflow/utils/validations/Validations.java @@ -28,6 +28,8 @@ import java.util.regex.Pattern; public class Validations { + private Validations() { + } public static void validateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { String vaultId = vaultConfig.getVaultId(); diff --git a/src/test/java/com/skyflow/config/ConnectionConfigTests.java b/src/test/java/com/skyflow/config/ConnectionConfigTests.java index 21b17838..00c16af6 100644 --- a/src/test/java/com/skyflow/config/ConnectionConfigTests.java +++ b/src/test/java/com/skyflow/config/ConnectionConfigTests.java @@ -20,7 +20,7 @@ public class ConnectionConfigTests { public static void setup() { connectionID = "connection123"; connectionURL = "https://connection.url.com"; - invalidConnectionURL = "invalid.connection.url.com"; + invalidConnectionURL = "http://connection.url.com"; credentials = new Credentials(); credentials.setToken("valid-token"); diff --git a/src/test/java/com/skyflow/config/CredentialsTests.java b/src/test/java/com/skyflow/config/CredentialsTests.java index 8093b2c2..ff9fcfda 100644 --- a/src/test/java/com/skyflow/config/CredentialsTests.java +++ b/src/test/java/com/skyflow/config/CredentialsTests.java @@ -220,6 +220,22 @@ public void testEmptyRolesInCredentials() { } } + @Test + public void testNullRoleInRolesInCredentials() { + try { + Credentials credentials = new Credentials(); + credentials.setPath(path); + roles.add(role); + roles.add(null); + credentials.setRoles(roles); + Validations.validateCredentials(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyRoleInRoles.getMessage(), e.getMessage()); + } + } + @Test public void testEmptyRoleInRolesInCredentials() { try { diff --git a/src/test/java/com/skyflow/config/VaultConfigTests.java b/src/test/java/com/skyflow/config/VaultConfigTests.java index 6bffa6d6..b99f6c9b 100644 --- a/src/test/java/com/skyflow/config/VaultConfigTests.java +++ b/src/test/java/com/skyflow/config/VaultConfigTests.java @@ -88,6 +88,7 @@ public void testDefaultEnvInVaultConfigWithoutCredentialsInValidations() { VaultConfig vaultConfig = new VaultConfig(); vaultConfig.setVaultId(vaultID); vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(null); Validations.validateVaultConfig(vaultConfig); Assert.assertEquals(vaultID, vaultConfig.getVaultId()); diff --git a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java index 4baa5ebf..6ac020e1 100644 --- a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java +++ b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java @@ -63,6 +63,30 @@ public void testValidInputInInvokeConnectionRequestValidations() { } } + @Test + public void testValidInputInInvokeConnectionRequestValidationsWithNullRequestBody() { + queryParams.put("query_param", "value"); + pathParams.put("path_param", "value"); + requestHeaders.put("header", "value"); + try { + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .method(null) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(null) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.assertEquals(1, request.getQueryParams().size()); + Assert.assertEquals(1, request.getPathParams().size()); + Assert.assertEquals(1, request.getRequestHeaders().size()); + Assert.assertEquals(RequestMethod.POST.toString(), request.getMethod().toString()); + Assert.assertNull(request.getRequestBody()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + @Test public void testEmptyRequestHeadersInInvokeConnectionRequestValidations() { try { diff --git a/src/test/java/com/skyflow/vault/data/GetTests.java b/src/test/java/com/skyflow/vault/data/GetTests.java index 930d696a..b2c8c454 100644 --- a/src/test/java/com/skyflow/vault/data/GetTests.java +++ b/src/test/java/com/skyflow/vault/data/GetTests.java @@ -75,7 +75,7 @@ public void testValidGetByIdInputInGetRequestValidations() { .ids(ids) .table(table) .returnTokens(true) - .downloadURL(true) + .downloadURL(false) .offset("2") .limit("1") .fields(fields) @@ -88,8 +88,8 @@ public void testValidGetByIdInputInGetRequestValidations() { Assert.assertEquals("2", request.getOffset()); Assert.assertEquals("1", request.getLimit()); Assert.assertEquals(Constants.ORDER_ASCENDING, request.getOrderBy()); - Assert.assertTrue(request.getDownloadURL()); Assert.assertTrue(request.getReturnTokens()); + Assert.assertFalse(request.getDownloadURL()); Assert.assertNull(request.getRedactionType()); } catch (SkyflowException e) { Assert.fail(INVALID_EXCEPTION_THROWN); @@ -106,11 +106,11 @@ public void testValidGetByColumnValuesInputInGetRequestValidations() { .columnName(columnName) .columnValues(columnValues) .redactionType(RedactionType.PLAIN_TEXT) - .downloadURL(true) + .downloadURL(null) .offset("2") .limit("1") .fields(fields) - .orderBy(Constants.ORDER_ASCENDING) + .orderBy(null) .build(); Validations.validateGetRequest(request); Assert.assertEquals(table, request.getTable()); @@ -175,6 +175,23 @@ public void testEmptyIdsInGetRequestValidations() { } } + @Test + public void testNullIdInIdsInGetRequestValidations() { + ids.add(skyflowID); + ids.add(null); + GetRequest request = GetRequest.builder().ids(ids).table(table).build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyIdInIds.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + @Test public void testEmptyIdInIdsInGetRequestValidations() { ids.add(skyflowID); @@ -208,6 +225,24 @@ public void testEmptyFieldsInGetRequestValidations() { } } + @Test + public void testNullFieldInFieldsInGetRequestValidations() { + ids.add(skyflowID); + fields.add(field); + fields.add(null); + GetRequest request = GetRequest.builder().ids(ids).table(table).fields(fields).build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyFieldInFields.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + @Test public void testEmptyFieldInFieldsInGetRequestValidations() { ids.add(skyflowID); diff --git a/src/test/java/com/skyflow/vault/data/InsertTests.java b/src/test/java/com/skyflow/vault/data/InsertTests.java index facdcf60..c604d3df 100644 --- a/src/test/java/com/skyflow/vault/data/InsertTests.java +++ b/src/test/java/com/skyflow/vault/data/InsertTests.java @@ -3,8 +3,8 @@ import com.skyflow.Skyflow; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.TokenMode; import com.skyflow.enums.Env; +import com.skyflow.enums.TokenMode; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; @@ -47,8 +47,6 @@ public static void setup() { vaultConfig.setEnv(Env.DEV); vaultConfig.setCredentials(credentials); -// skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - table = "test_table"; values = new ArrayList<>(); tokens = new ArrayList<>(); @@ -98,6 +96,35 @@ public void testValidInputInInsertRequestValidations() { } } + @Test + public void testValidInputInInsertRequestValidationsWithTokenModeDisable() { + try { + values.add(valueMap); + tokens.add(tokenMap); + InsertRequest request = InsertRequest.builder() + .table(table) + .continueOnError(null) + .returnTokens(null) + .homogeneous(false) + .upsert(upsert) + .values(values) + .tokenMode(null) + .build(); + Validations.validateInsertRequest(request); + + Assert.assertEquals(table, request.getTable()); + Assert.assertEquals(upsert, request.getUpsert()); + Assert.assertEquals(1, request.getValues().size()); + Assert.assertEquals(TokenMode.DISABLE, request.getTokenMode()); + Assert.assertNull(request.getTokens()); + Assert.assertTrue(request.getReturnTokens()); + Assert.assertFalse(request.getContinueOnError()); + Assert.assertFalse(request.getHomogeneous()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + @Test public void testNoTableInInsertRequestValidations() { InsertRequest request = InsertRequest.builder().build(); diff --git a/src/test/java/com/skyflow/vault/data/UpdateTests.java b/src/test/java/com/skyflow/vault/data/UpdateTests.java index 2f2f1247..3253306a 100644 --- a/src/test/java/com/skyflow/vault/data/UpdateTests.java +++ b/src/test/java/com/skyflow/vault/data/UpdateTests.java @@ -3,8 +3,8 @@ import com.skyflow.Skyflow; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.TokenMode; import com.skyflow.enums.Env; +import com.skyflow.enums.TokenMode; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; @@ -79,6 +79,28 @@ public void testValidInputInUpdateRequestValidations() { } } + @Test + public void testValidInputInUpdateRequestValidationsWithTokenModeDisable() { + try { + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); + UpdateRequest request = UpdateRequest.builder() + .table(table) + .data(dataMap) + .returnTokens(null) + .tokenMode(null) + .build(); + Validations.validateUpdateRequest(request); + Assert.assertEquals(table, request.getTable()); + Assert.assertEquals(3, request.getData().size()); + Assert.assertTrue(request.getReturnTokens()); + Assert.assertNull(request.getTokens()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + @Test public void testNoSkyflowIdInUpdateRequestValidations() { dataMap.put("test_column_1", "test_value_1"); @@ -187,6 +209,25 @@ public void testEmptyValuesInUpdateRequestValidations() { } } + @Test + public void testNullKeyInValuesInUpdateRequestValidations() { + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); + dataMap.put(null, "test_value_3"); + UpdateRequest request = UpdateRequest.builder().table(table).data(dataMap).build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyKeyInValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + @Test public void testEmptyKeyInValuesInUpdateRequestValidations() { dataMap.put("skyflow_id", skyflowID); @@ -206,6 +247,25 @@ public void testEmptyKeyInValuesInUpdateRequestValidations() { } } + @Test + public void testNullValueInValuesInUpdateRequestValidations() { + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); + dataMap.put("test_column_3", null); + UpdateRequest request = UpdateRequest.builder().table(table).data(dataMap).build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyValueInValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + @Test public void testEmptyValueInValuesInUpdateRequestValidations() { dataMap.put("skyflow_id", skyflowID); @@ -226,7 +286,7 @@ public void testEmptyValueInValuesInUpdateRequestValidations() { } @Test - public void testTokensWithTokenStrictDisableInUpdateRequestValidations() { + public void testTokensWithTokenModeDisableInUpdateRequestValidations() { dataMap.put("skyflow_id", skyflowID); dataMap.put("test_column_1", "test_value_1"); dataMap.put("test_column_2", "test_value_2"); @@ -247,7 +307,7 @@ public void testTokensWithTokenStrictDisableInUpdateRequestValidations() { } @Test - public void testNoTokensWithTokenStrictEnableInUpdateRequestValidations() { + public void testNoTokensWithTokenModeEnableInUpdateRequestValidations() { dataMap.put("skyflow_id", skyflowID); dataMap.put("test_column_1", "test_value_1"); dataMap.put("test_column_2", "test_value_2"); @@ -267,7 +327,7 @@ public void testNoTokensWithTokenStrictEnableInUpdateRequestValidations() { } @Test - public void testNoTokensWithTokenStrictEnableStrictInUpdateRequestValidations() { + public void testNoTokensWithTokenModeEnableStrictInUpdateRequestValidations() { dataMap.put("skyflow_id", skyflowID); dataMap.put("test_column_1", "test_value_1"); dataMap.put("test_column_2", "test_value_2"); @@ -287,7 +347,7 @@ public void testNoTokensWithTokenStrictEnableStrictInUpdateRequestValidations() } @Test - public void testEmptyTokensWithTokenStrictEnableInUpdateRequestValidations() { + public void testEmptyTokensWithTokenModeEnableInUpdateRequestValidations() { dataMap.put("skyflow_id", skyflowID); dataMap.put("test_column_1", "test_value_1"); dataMap.put("test_column_2", "test_value_2"); @@ -304,7 +364,7 @@ public void testEmptyTokensWithTokenStrictEnableInUpdateRequestValidations() { } @Test - public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestValidations() { + public void testInsufficientTokensWithTokenModeEnableStrictInUpdateRequestValidations() { dataMap.put("skyflow_id", skyflowID); dataMap.put("test_column_1", "test_value_1"); dataMap.put("test_column_2", "test_value_2"); @@ -341,12 +401,12 @@ public void testTokenValueMismatchInUpdateRequestValidations() { } @Test - public void testEmptyKeyInTokensInUpdateRequestValidations() { + public void testNullKeyInTokensInUpdateRequestValidations() { dataMap.put("skyflow_id", skyflowID); dataMap.put("test_column_1", "test_value_1"); dataMap.put("test_column_2", "test_value_2"); tokenMap.put("test_column_1", "test_token_1"); - tokenMap.put("", "test_token_2"); + tokenMap.put(null, "test_token_2"); UpdateRequest request = UpdateRequest.builder() .table(table).data(dataMap).tokens(tokenMap).tokenMode(TokenMode.ENABLE_STRICT) .build(); @@ -360,12 +420,12 @@ public void testEmptyKeyInTokensInUpdateRequestValidations() { } @Test - public void testEmptyValueInTokensInUpdateRequestValidations() { + public void testNullValueInTokensInUpdateRequestValidations() { dataMap.put("skyflow_id", skyflowID); dataMap.put("test_column_1", "test_value_1"); dataMap.put("test_column_2", "test_value_2"); tokenMap.put("test_column_1", "test_token_1"); - tokenMap.put("test_column_2", ""); + tokenMap.put("test_column_2", null); UpdateRequest request = UpdateRequest.builder() .table(table).data(dataMap).tokens(tokenMap).tokenMode(TokenMode.ENABLE_STRICT) .build(); diff --git a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index df8153d9..29633ced 100644 --- a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -41,7 +41,7 @@ public void testValidInputInDetokenizeRequestValidations() { tokens(tokens).redactionType(RedactionType.MASKED).continueOnError(false).build(); Validations.validateDetokenizeRequest(request); Assert.assertEquals(1, tokens.size()); - Assert.assertEquals(RedactionType.MASKED, request.getRedactionType()); + Assert.assertEquals(RedactionType.MASKED.toString(), request.getRedactionType().toString()); Assert.assertFalse(request.getContinueOnError()); } catch (SkyflowException e) { Assert.fail(INVALID_EXCEPTION_THROWN); @@ -101,6 +101,25 @@ public void testEmptyTokenInTokensInDetokenizeRequestValidations() { } } + @Test + public void testNullTokenInTokensInDetokenizeRequestValidations() { + tokens.add(token); + tokens.add(null); + DetokenizeRequest request = DetokenizeRequest.builder().tokens(tokens).build(); + try { + Validations.validateDetokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyTokenInDataTokens.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); + Assert.assertTrue(request.getContinueOnError()); + } + } + @Test public void testRedactionAndContinueOnErrorInDetokenizeRequestValidations() { tokens.add(token); diff --git a/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java index 422cd79e..0ad09735 100644 --- a/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java @@ -95,6 +95,20 @@ public void testEmptyColumnValuesInTokenizeRequestValidations() { } } + @Test + public void testNullColumnValueInColumnValuesInTokenizeRequestValidations() { + try { + columnValue = ColumnValue.builder().value(null).columnGroup(group).build(); + columnValues.add(columnValue); + TokenizeRequest request = TokenizeRequest.builder().values(columnValues).build(); + Validations.validateTokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyValueInColumnValues.getMessage(), e.getMessage()); + } + } + @Test public void testEmptyColumnValueInColumnValuesInTokenizeRequestValidations() { try { @@ -109,6 +123,20 @@ public void testEmptyColumnValueInColumnValuesInTokenizeRequestValidations() { } } + @Test + public void testNullColumnGroupInColumnValuesInTokenizeRequestValidations() { + try { + columnValue = ColumnValue.builder().value(value).columnGroup(null).build(); + columnValues.add(columnValue); + TokenizeRequest request = TokenizeRequest.builder().values(columnValues).build(); + Validations.validateTokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyColumnGroupInColumnValue.getMessage(), e.getMessage()); + } + } + @Test public void testEmptyColumnGroupInColumnValuesInTokenizeRequestValidations() { try { From e094acaaa353ae41135be7ec783d41c7bcd99ef4 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 9 Dec 2024 20:51:35 +0530 Subject: [PATCH 084/126] SK-1802 Renamed github secret --- .github/workflows/main.yml | 2 +- .github/workflows/pr.yml | 2 +- .github/workflows/shared-build-and-deploy.yml | 2 +- .../java/com/skyflow/ConnectionClient.java | 8 +++-- src/main/java/com/skyflow/VaultClient.java | 8 +++-- .../serviceaccount/util/BearerToken.java | 2 +- .../util/SignedDataTokenResponse.java | 25 ++++++++----- .../serviceaccount/util/SignedDataTokens.java | 2 +- .../utils/validations/Validations.java | 2 +- .../controller/ConnectionController.java | 4 +-- .../vault/controller/VaultController.java | 35 +++++++++++-------- .../com/skyflow/vault/data/GetRequest.java | 1 + .../com/skyflow/vault/data/InsertRequest.java | 4 +-- .../com/skyflow/vault/data/QueryResponse.java | 7 ++-- .../com/skyflow/vault/data/UpdateRequest.java | 4 +-- .../skyflow/vault/data/UpdateResponse.java | 7 ++-- .../vault/tokens/DetokenizeRequest.java | 4 +-- .../vault/tokens/TokenizeResponse.java | 13 ++++--- .../com/skyflow/ConnectionClientTests.java | 2 +- .../java/com/skyflow/VaultClientTests.java | 4 +-- .../serviceaccount/util/BearerTokenTests.java | 9 +++-- .../util/SignedDataTokensTests.java | 12 ++++--- .../java/com/skyflow/utils/UtilsTests.java | 5 ++- .../com/skyflow/vault/data/DeleteTests.java | 20 +++++++++-- .../java/com/skyflow/vault/data/GetTests.java | 11 ++++-- .../com/skyflow/vault/data/InsertTests.java | 2 +- .../com/skyflow/vault/data/QueryTests.java | 4 +-- .../com/skyflow/vault/data/UpdateTests.java | 8 ++--- .../skyflow/vault/tokens/DetokenizeTests.java | 10 +++--- .../skyflow/vault/tokens/TokenizeTests.java | 4 ++- 30 files changed, 143 insertions(+), 80 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 6ec8f15b..eb104010 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -23,7 +23,7 @@ jobs: json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - name: Build & Run tests with Maven - run: mvn -B package -DTEST_VAULT_ID=${{ secrets.TEST_VAULT_ID }} -DTEST_VAULT_URL=${{ secrets.TEST_VAULT_URL }} -DTEST_SKYFLOW_ID=${{ secrets.TEST_SKYFLOW_ID }} -DTEST_TOKEN=${{ secrets.TEST_TOKEN }} -DTEST_CREDENTIALS=${{ secrets.TEST_CREDENTIALS_FILE_STRING }} -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -DTEST_HUNDRED_TOKEN=${{ secrets.TEST_HUNDRED_TOKEN }} -f pom.xml + run: mvn -B package -DTEST_VAULT_ID=${{ secrets.TEST_VAULT_ID }} -DTEST_VAULT_URL=${{ secrets.TEST_VAULT_URL }} -DTEST_SKYFLOW_ID=${{ secrets.TEST_SKYFLOW_ID }} -DTEST_TOKEN=${{ secrets.TEST_TOKEN }} -DTEST_CREDENTIALS=${{ secrets.TEST_CREDENTIALS_FILE_STRING }} -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -DTEST_REUSABLE_TOKEN=${{ secrets.TEST_REUSABLE_TOKEN }} -f pom.xml - name: Codecov uses: codecov/codecov-action@v2.1.0 diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 7e0f5abf..ff48495f 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -37,7 +37,7 @@ jobs: touch .env echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env - echo TEST_HUNDRED_TOKEN=${{ secrets.TEST_HUNDRED_TOKEN }} >> .env + echo TEST_REUSABLE_TOKEN=${{ secrets.TEST_REUSABLE_TOKEN }} >> .env - name: Build & Run tests with Maven run: mvn -B package -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -DTEST_DATA_CREDENTIALS_FILE=${{ secrets.TEST_DATA_CREDENTIALS_FILE }} -f pom.xml diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index 845acbd9..e235a83d 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -89,7 +89,7 @@ jobs: touch .env echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env - echo TEST_HUNDRED_TOKEN=${{ secrets.TEST_HUNDRED_TOKEN }} >> .env + echo TEST_REUSABLE_TOKEN=${{ secrets.TEST_REUSABLE_TOKEN }} >> .env - name: Create credentials json id: create-json diff --git a/src/main/java/com/skyflow/ConnectionClient.java b/src/main/java/com/skyflow/ConnectionClient.java index e0a6cf19..7cb10713 100644 --- a/src/main/java/com/skyflow/ConnectionClient.java +++ b/src/main/java/com/skyflow/ConnectionClient.java @@ -41,6 +41,7 @@ protected void updateConnectionConfig(ConnectionConfig connectionConfig) throws } protected void setBearerToken() throws SkyflowException { + prioritiseCredentials(); Validations.validateCredentials(this.finalCredentials); if (this.finalCredentials.getApiKey() != null) { setApiKey(); @@ -62,6 +63,7 @@ private void setApiKey() { private void prioritiseCredentials() throws SkyflowException { try { + Credentials original = this.finalCredentials; if (this.connectionConfig.getCredentials() != null) { this.finalCredentials = this.connectionConfig.getCredentials(); } else if (this.commonCredentials != null) { @@ -77,8 +79,10 @@ private void prioritiseCredentials() throws SkyflowException { this.finalCredentials.setCredentialsString(sysCredentials); } } - token = null; - apiKey = null; + if (original != null && !original.equals(this.finalCredentials)) { + token = null; + apiKey = null; + } } catch (DotenvException e) { throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyCredentials.getMessage()); diff --git a/src/main/java/com/skyflow/VaultClient.java b/src/main/java/com/skyflow/VaultClient.java index 10f89284..f3e29fb2 100644 --- a/src/main/java/com/skyflow/VaultClient.java +++ b/src/main/java/com/skyflow/VaultClient.java @@ -169,6 +169,7 @@ protected V1TokenizePayload getTokenizePayload(TokenizeRequest request) { } protected void setBearerToken() throws SkyflowException { + prioritiseCredentials(); Validations.validateCredentials(this.finalCredentials); if (this.finalCredentials.getApiKey() != null) { setApiKey(); @@ -200,6 +201,7 @@ private void updateVaultURL() { private void prioritiseCredentials() throws SkyflowException { try { + Credentials original = this.finalCredentials; if (this.vaultConfig.getCredentials() != null) { this.finalCredentials = this.vaultConfig.getCredentials(); } else if (this.commonCredentials != null) { @@ -215,8 +217,10 @@ private void prioritiseCredentials() throws SkyflowException { this.finalCredentials.setCredentialsString(sysCredentials); } } - token = null; - apiKey = null; + if (original != null && !original.equals(this.finalCredentials)) { + token = null; + apiKey = null; + } } catch (DotenvException e) { throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyCredentials.getMessage()); diff --git a/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java b/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java index da221458..e6e4b534 100644 --- a/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java +++ b/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java @@ -55,7 +55,7 @@ private static V1GetAuthTokenResponse generateBearerTokenFromCredentials( ) throws SkyflowException { LogUtil.printInfoLog(InfoLogs.GENERATE_BEARER_TOKEN_FROM_CREDENTIALS_TRIGGERED.getLog()); try { - if (credentialsFile == null || !credentialsFile.isFile()) { + if (credentialsFile == null) { LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); } diff --git a/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java index e7e966bc..7c9f4674 100644 --- a/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java +++ b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java @@ -1,22 +1,29 @@ package com.skyflow.serviceaccount.util; +import com.google.gson.Gson; import com.skyflow.utils.Constants; public class SignedDataTokenResponse { private static final String prefix = Constants.SIGNED_DATA_TOKEN_PREFIX; - private final String dataToken; - private final String signedDataToken; + private final String token; + private final String signedToken; - public SignedDataTokenResponse(String dataToken, String signedDataToken) { - this.dataToken = dataToken; - this.signedDataToken = new StringBuilder(prefix).append(signedDataToken).toString(); + public SignedDataTokenResponse(String token, String signedToken) { + this.token = token; + this.signedToken = new StringBuilder(prefix).append(signedToken).toString(); + } + + public String getToken() { + return token; + } + + public String getSignedToken() { + return signedToken; } @Override public String toString() { - return "{" + - "\n\t\"dataToken\":\"" + this.dataToken + "\"," + - "\n\t\"signedDataToken\":\"" + this.signedDataToken + "\"," + - "\n}"; + Gson gson = new Gson(); + return gson.toJson(this); } } diff --git a/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java index 83fd0543..ecdfa89f 100644 --- a/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java +++ b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java @@ -50,7 +50,7 @@ private static List generateSignedTokenFromCredentialsF LogUtil.printInfoLog(InfoLogs.GENERATE_SIGNED_TOKENS_FROM_CREDENTIALS_FILE_TRIGGERED.getLog()); List responseToken; try { - if (credentialsFile == null || !credentialsFile.isFile()) { + if (credentialsFile == null) { LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); } diff --git a/src/main/java/com/skyflow/utils/validations/Validations.java b/src/main/java/com/skyflow/utils/validations/Validations.java index de265e1a..67853bab 100644 --- a/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/src/main/java/com/skyflow/utils/validations/Validations.java @@ -621,7 +621,7 @@ public static void validateDeleteRequest(DeleteRequest deleteRequest) throws Sky } else { for (int index = 0; index < ids.size(); index++) { String id = ids.get(index); - if (id.trim().isEmpty()) { + if (id == null || id.trim().isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_ID_IN_IDS.getLog(), InterfaceName.DELETE.getName(), Integer.toString(index) diff --git a/src/main/java/com/skyflow/vault/controller/ConnectionController.java b/src/main/java/com/skyflow/vault/controller/ConnectionController.java index 851a5dbf..66720521 100644 --- a/src/main/java/com/skyflow/vault/controller/ConnectionController.java +++ b/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -42,13 +42,13 @@ public InvokeConnectionResponse invoke(InvokeConnectionRequest invokeConnectionR Map headers = new HashMap<>(); Map requestHeaders = invokeConnectionRequest.getRequestHeaders(); - if (requestHeaders != null && requestHeaders.containsKey("requestHeader")) { + if (requestHeaders != null) { headers = Utils.constructConnectionHeadersMap(invokeConnectionRequest.getRequestHeaders()); } if (!headers.containsKey(Constants.SDK_AUTH_HEADER_KEY)) { headers.put(Constants.SDK_AUTH_HEADER_KEY, token == null ? apiKey : token); - headers.put(Constants.SDK_METRICS_HEADER_KEY, Utils.getMetrics().toString()); } + headers.put(Constants.SDK_METRICS_HEADER_KEY, Utils.getMetrics().toString()); RequestMethod requestMethod = invokeConnectionRequest.getMethod(); JsonObject requestBody = null; diff --git a/src/main/java/com/skyflow/vault/controller/VaultController.java b/src/main/java/com/skyflow/vault/controller/VaultController.java index 9ef639ff..7744dfd8 100644 --- a/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -20,7 +20,7 @@ import java.util.List; public final class VaultController extends VaultClient { - private static final Gson gson = new Gson(); + private static final Gson gson = new GsonBuilder().serializeNulls().create(); private DetectController detectController; private AuditController auditController; private BinLookupController binLookupController; @@ -42,7 +42,7 @@ private static synchronized HashMap getFormattedBatchInsertRecor if (records != null) { for (JsonElement recordElement : records) { JsonObject recordObject = recordElement.getAsJsonObject(); - insertRecord.put("skyflow_id", recordObject.get("skyflow_id").getAsString()); + insertRecord.put("skyflowId", recordObject.get("skyflow_id").getAsString()); JsonElement tokensElement = recordObject.get("tokens"); if (tokensElement != null) { insertRecord.putAll(tokensElement.getAsJsonObject().asMap()); @@ -53,16 +53,17 @@ private static synchronized HashMap getFormattedBatchInsertRecor if (error != null) { insertRecord.put("error", error.getAsString()); } - insertRecord.put("request_index", requestIndex); + insertRecord.put("requestIndex", requestIndex); return insertRecord; } private static synchronized HashMap getFormattedBulkInsertRecord(V1RecordMetaProperties record) { HashMap insertRecord = new HashMap<>(); String skyflowId = record.getSkyflowId(); - insertRecord.put("skyflow_id", skyflowId); - String tokensString = gson.toJson(record.getTokens()); - if (tokensString != null) { + Object tokens = record.getTokens(); + insertRecord.put("skyflowId", skyflowId); + if (tokens != null) { + String tokensString = gson.toJson(tokens); JsonObject tokensObject = JsonParser.parseString(tokensString).getAsJsonObject(); insertRecord.putAll(tokensObject.asMap()); } @@ -71,12 +72,14 @@ private static synchronized HashMap getFormattedBulkInsertRecord private static synchronized HashMap getFormattedGetRecord(V1FieldRecords record) { HashMap getRecord = new HashMap<>(); - String fieldsString = gson.toJson(record.getFields()); - String tokensString = gson.toJson(record.getTokens()); - if (fieldsString != null) { + Object fields = record.getFields(); + Object tokens = record.getTokens(); + if (fields != null) { + String fieldsString = gson.toJson(fields); JsonObject fieldsObject = JsonParser.parseString(fieldsString).getAsJsonObject(); getRecord.putAll(fieldsObject.asMap()); - } else if (tokensString != null) { + } else if (tokens != null) { + String tokensString = gson.toJson(tokens); JsonObject tokensObject = JsonParser.parseString(tokensString).getAsJsonObject(); getRecord.putAll(tokensObject.asMap()); } @@ -85,8 +88,9 @@ private static synchronized HashMap getFormattedGetRecord(V1Fiel private static synchronized HashMap getFormattedUpdateRecord(V1UpdateRecordResponse record) { HashMap updateTokens = new HashMap<>(); - String tokensString = gson.toJson(record.getTokens()); - if (tokensString != null) { + Object tokens = record.getTokens(); + if (tokens != null) { + String tokensString = gson.toJson(tokens); JsonObject tokensObject = JsonParser.parseString(tokensString).getAsJsonObject(); updateTokens.putAll(tokensObject.asMap()); } @@ -95,8 +99,9 @@ private static synchronized HashMap getFormattedUpdateRecord(V1U private static synchronized HashMap getFormattedQueryRecord(V1FieldRecords record) { HashMap queryRecord = new HashMap<>(); - String fieldsString = gson.toJson(record.getFields()); - if (fieldsString != null) { + Object fields = record.getFields(); + if (fields != null) { + String fieldsString = gson.toJson(fields); JsonObject fieldsObject = JsonParser.parseString(fieldsString).getAsJsonObject(); queryRecord.putAll(fieldsObject.asMap()); } @@ -122,7 +127,7 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio for (int index = 0; index < records.size(); index++) { Object record = records.get(index); HashMap insertRecord = getFormattedBatchInsertRecord(record, index); - if (insertRecord.containsKey("skyflow_id")) { + if (insertRecord.containsKey("skyflowId")) { insertedFields.add(insertRecord); } else { errorFields.add(insertRecord); diff --git a/src/main/java/com/skyflow/vault/data/GetRequest.java b/src/main/java/com/skyflow/vault/data/GetRequest.java index 04626e35..12aef7fa 100644 --- a/src/main/java/com/skyflow/vault/data/GetRequest.java +++ b/src/main/java/com/skyflow/vault/data/GetRequest.java @@ -76,6 +76,7 @@ public static final class GetRequestBuilder { private GetRequestBuilder() { this.downloadURL = true; this.orderBy = Constants.ORDER_ASCENDING; + this.redactionType = RedactionType.PLAIN_TEXT; } public GetRequestBuilder table(String table) { diff --git a/src/main/java/com/skyflow/vault/data/InsertRequest.java b/src/main/java/com/skyflow/vault/data/InsertRequest.java index 55db92e4..54093467 100644 --- a/src/main/java/com/skyflow/vault/data/InsertRequest.java +++ b/src/main/java/com/skyflow/vault/data/InsertRequest.java @@ -59,7 +59,7 @@ public static final class InsertRequestBuilder { private TokenMode tokenMode; private InsertRequestBuilder() { - this.returnTokens = true; + this.returnTokens = false; this.continueOnError = false; this.tokenMode = TokenMode.DISABLE; } @@ -80,7 +80,7 @@ public InsertRequestBuilder tokens(ArrayList> tokens) { } public InsertRequestBuilder returnTokens(Boolean returnTokens) { - this.returnTokens = returnTokens == null || returnTokens; + this.returnTokens = returnTokens != null && returnTokens; return this; } diff --git a/src/main/java/com/skyflow/vault/data/QueryResponse.java b/src/main/java/com/skyflow/vault/data/QueryResponse.java index 020a24c1..1906a218 100644 --- a/src/main/java/com/skyflow/vault/data/QueryResponse.java +++ b/src/main/java/com/skyflow/vault/data/QueryResponse.java @@ -19,13 +19,14 @@ public ArrayList> getFields() { @Override public String toString() { - Gson gson = new Gson(); - JsonObject responseObject = JsonParser.parseString(gson.toJson(this)).getAsJsonObject(); + Gson gson = new GsonBuilder().serializeNulls().create(); + JsonObject responseObject = gson.toJsonTree(this).getAsJsonObject(); JsonArray fieldsArray = responseObject.get("fields").getAsJsonArray(); for (JsonElement fieldElement : fieldsArray) { - fieldElement.getAsJsonObject().add("tokenizedData", null); + fieldElement.getAsJsonObject().add("tokenizedData", new JsonObject()); } responseObject.add("errors", new JsonArray()); + responseObject.remove("tokenizedData"); return responseObject.toString(); } } diff --git a/src/main/java/com/skyflow/vault/data/UpdateRequest.java b/src/main/java/com/skyflow/vault/data/UpdateRequest.java index 03ca8f42..94789121 100644 --- a/src/main/java/com/skyflow/vault/data/UpdateRequest.java +++ b/src/main/java/com/skyflow/vault/data/UpdateRequest.java @@ -43,7 +43,7 @@ public static final class UpdateRequestBuilder { private TokenMode tokenMode; private UpdateRequestBuilder() { - this.returnTokens = true; + this.returnTokens = false; this.tokenMode = TokenMode.DISABLE; } @@ -53,7 +53,7 @@ public UpdateRequestBuilder table(String table) { } public UpdateRequestBuilder returnTokens(Boolean returnTokens) { - this.returnTokens = returnTokens == null || returnTokens; + this.returnTokens = returnTokens != null && returnTokens; return this; } diff --git a/src/main/java/com/skyflow/vault/data/UpdateResponse.java b/src/main/java/com/skyflow/vault/data/UpdateResponse.java index cbeed0f9..4dd32f1b 100644 --- a/src/main/java/com/skyflow/vault/data/UpdateResponse.java +++ b/src/main/java/com/skyflow/vault/data/UpdateResponse.java @@ -1,6 +1,7 @@ package com.skyflow.vault.data; import com.google.gson.Gson; +import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -27,11 +28,13 @@ public HashMap getTokens() { public String toString() { Gson gson = new Gson(); JsonObject responseObject = JsonParser.parseString(gson.toJson(this)).getAsJsonObject(); - responseObject.add("skyflow_id", responseObject.remove("skyflowId")); JsonObject tokensObject = responseObject.remove("tokens").getAsJsonObject(); for (String key : tokensObject.keySet()) { responseObject.add(key, tokensObject.get(key)); } - return responseObject.toString(); + JsonObject finalResponseObject = new JsonObject(); + finalResponseObject.add("updatedField", responseObject); + finalResponseObject.add("errors", new JsonArray()); + return finalResponseObject.toString(); } } diff --git a/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java index 205ecef7..d5b8f072 100644 --- a/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java @@ -34,7 +34,7 @@ public static final class DetokenizeRequestBuilder { private DetokenizeRequestBuilder() { this.redactionType = RedactionType.PLAIN_TEXT; - this.continueOnError = true; + this.continueOnError = false; } public DetokenizeRequestBuilder tokens(ArrayList tokens) { @@ -48,7 +48,7 @@ public DetokenizeRequestBuilder redactionType(RedactionType redactionType) { } public DetokenizeRequestBuilder continueOnError(Boolean continueOnError) { - this.continueOnError = continueOnError == null || continueOnError; + this.continueOnError = continueOnError != null && continueOnError; return this; } diff --git a/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java b/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java index 0b311fbb..a0e48273 100644 --- a/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java +++ b/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java @@ -1,9 +1,6 @@ package com.skyflow.vault.tokens; -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; +import com.google.gson.*; import java.util.List; @@ -22,6 +19,14 @@ public List getTokens() { public String toString() { Gson gson = new Gson(); JsonObject responseObject = JsonParser.parseString(gson.toJson(this)).getAsJsonObject(); + JsonArray tokensArray = responseObject.remove("tokens").getAsJsonArray(); + JsonArray newTokensArray = new JsonArray(); + for (JsonElement token : tokensArray) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("token", token.getAsString()); + newTokensArray.add(jsonObject); + } + responseObject.add("tokens", newTokensArray); responseObject.add("errors", new JsonArray()); return responseObject.toString(); } diff --git a/src/test/java/com/skyflow/ConnectionClientTests.java b/src/test/java/com/skyflow/ConnectionClientTests.java index 533e8a9b..4a69120c 100644 --- a/src/test/java/com/skyflow/ConnectionClientTests.java +++ b/src/test/java/com/skyflow/ConnectionClientTests.java @@ -46,7 +46,7 @@ public void getConnectionConfig() { public void testSetBearerToken() { try { Dotenv dotenv = Dotenv.load(); - String bearerToken = dotenv.get("TEST_HUNDRED_TOKEN"); + String bearerToken = dotenv.get("TEST_REUSABLE_TOKEN"); Credentials credentials = new Credentials(); credentials.setToken(bearerToken); connectionConfig.setCredentials(credentials); diff --git a/src/test/java/com/skyflow/VaultClientTests.java b/src/test/java/com/skyflow/VaultClientTests.java index 58cbf08a..8a02caaf 100644 --- a/src/test/java/com/skyflow/VaultClientTests.java +++ b/src/test/java/com/skyflow/VaultClientTests.java @@ -119,7 +119,7 @@ public void testGetDetokenizePayload() { tokens.add(token); DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder().tokens(tokens).build(); V1DetokenizePayload payload = vaultClient.getDetokenizePayload(detokenizeRequest); - Assert.assertTrue(payload.getContinueOnError()); + Assert.assertFalse(payload.getContinueOnError()); Assert.assertEquals(2, payload.getDetokenizationParameters().size()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); @@ -250,7 +250,7 @@ public void testGetTokenizePayload() { public void testSetBearerToken() { try { Dotenv dotenv = Dotenv.load(); - String bearerToken = dotenv.get("TEST_HUNDRED_TOKEN"); + String bearerToken = dotenv.get("TEST_REUSABLE_TOKEN"); Credentials credentials = new Credentials(); credentials.setToken(bearerToken); vaultConfig.setCredentials(credentials); diff --git a/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java b/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java index 52272933..4bfb697c 100644 --- a/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java +++ b/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java @@ -63,7 +63,9 @@ public void testEmptyCredentialsFilePath() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), ""), e.getMessage() + ); } } @@ -76,7 +78,10 @@ public void testInvalidFilePath() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), invalidFilePath), + e.getMessage() + ); } } diff --git a/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java index 50b97e11..42ad9bc7 100644 --- a/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java +++ b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java @@ -69,7 +69,7 @@ public void testEmptyCredentialsFilePath() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); + Assert.assertEquals(Utils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), ""), e.getMessage()); } } @@ -82,7 +82,9 @@ public void testInvalidFilePath() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), invalidFilePath), + e.getMessage()); } } @@ -212,9 +214,11 @@ public void testSignedDataTokenResponse() { try { String signedToken = "test_signed_data_token"; SignedDataTokenResponse response = new SignedDataTokenResponse(dataToken, signedToken); - String responseString = "{\n\t\"dataToken\":\"" + dataToken + "\"," + - "\n\t\"signedDataToken\":\"signed_token_" + signedToken + "\",\n}"; + String responseString = "{\"token\":\"" + dataToken + "\"," + + "\"signedToken\":\"signed_token_" + signedToken + "\"}"; Assert.assertEquals(responseString, response.toString()); + Assert.assertEquals(dataToken, response.getToken()); + Assert.assertEquals("signed_token_" + signedToken, response.getSignedToken()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } diff --git a/src/test/java/com/skyflow/utils/UtilsTests.java b/src/test/java/com/skyflow/utils/UtilsTests.java index 930a44f1..83e5a6ff 100644 --- a/src/test/java/com/skyflow/utils/UtilsTests.java +++ b/src/test/java/com/skyflow/utils/UtilsTests.java @@ -117,7 +117,10 @@ public void testGenerateBearerTokenWithCredentialsFile() { Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); - Assert.assertEquals(ErrorMessage.InvalidCredentials.getMessage(), e.getMessage()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), filePath), + e.getMessage() + ); } } diff --git a/src/test/java/com/skyflow/vault/data/DeleteTests.java b/src/test/java/com/skyflow/vault/data/DeleteTests.java index c261cfd1..6749e31d 100644 --- a/src/test/java/com/skyflow/vault/data/DeleteTests.java +++ b/src/test/java/com/skyflow/vault/data/DeleteTests.java @@ -79,7 +79,6 @@ public void testNoIdsInDeleteRequestValidations() { @Test public void testEmptyIdsInDeleteRequestValidations() { -// ids.clear(); DeleteRequest request = DeleteRequest.builder().ids(ids).table(table).build(); try { Validations.validateDeleteRequest(request); @@ -93,6 +92,23 @@ public void testEmptyIdsInDeleteRequestValidations() { } } + @Test + public void testNullIdInIdsInDeleteRequestValidations() { + ids.add(skyflowID); + ids.add(null); + DeleteRequest request = DeleteRequest.builder().ids(ids).table(table).build(); + try { + Validations.validateDeleteRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyIdInIds.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + @Test public void testEmptyIdInIdsInDeleteRequestValidations() { ids.add(skyflowID); @@ -112,7 +128,6 @@ public void testEmptyIdInIdsInDeleteRequestValidations() { @Test public void testNoTableInDeleteRequestValidations() { -// ids.clear(); ids.add(skyflowID); DeleteRequest request = DeleteRequest.builder().ids(ids).build(); try { @@ -129,7 +144,6 @@ public void testNoTableInDeleteRequestValidations() { @Test public void testEmptyTableInDeleteRequestValidations() { -// ids.clear(); ids.add(skyflowID); DeleteRequest request = DeleteRequest.builder().ids(ids).table("").build(); try { diff --git a/src/test/java/com/skyflow/vault/data/GetTests.java b/src/test/java/com/skyflow/vault/data/GetTests.java index b2c8c454..43b3f132 100644 --- a/src/test/java/com/skyflow/vault/data/GetTests.java +++ b/src/test/java/com/skyflow/vault/data/GetTests.java @@ -75,6 +75,7 @@ public void testValidGetByIdInputInGetRequestValidations() { .ids(ids) .table(table) .returnTokens(true) + .redactionType(null) .downloadURL(false) .offset("2") .limit("1") @@ -263,7 +264,7 @@ public void testEmptyFieldInFieldsInGetRequestValidations() { @Test public void testNoRedactionInGetRequestValidations() { - GetRequest request = GetRequest.builder().table(table).build(); + GetRequest request = GetRequest.builder().table(table).returnTokens(false).redactionType(null).build(); try { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); @@ -295,7 +296,9 @@ public void testReturnTokensWithRedactionInGetRequestValidations() { @Test public void testReturnTokensWithColumnNameInGetRequestValidations() { - GetRequest request = GetRequest.builder().table(table).returnTokens(true).columnName(columnName).build(); + GetRequest request = GetRequest.builder() + .table(table).returnTokens(true).redactionType(null).columnName(columnName) + .build(); try { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); @@ -310,7 +313,9 @@ public void testReturnTokensWithColumnNameInGetRequestValidations() { @Test public void testReturnTokensWithColumnValuesInGetRequestValidations() { - GetRequest request = GetRequest.builder().table(table).returnTokens(true).columnValues(columnValues).build(); + GetRequest request = GetRequest.builder() + .table(table).returnTokens(true).redactionType(null).columnValues(columnValues) + .build(); try { Validations.validateGetRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); diff --git a/src/test/java/com/skyflow/vault/data/InsertTests.java b/src/test/java/com/skyflow/vault/data/InsertTests.java index c604d3df..573ac5e4 100644 --- a/src/test/java/com/skyflow/vault/data/InsertTests.java +++ b/src/test/java/com/skyflow/vault/data/InsertTests.java @@ -117,7 +117,7 @@ public void testValidInputInInsertRequestValidationsWithTokenModeDisable() { Assert.assertEquals(1, request.getValues().size()); Assert.assertEquals(TokenMode.DISABLE, request.getTokenMode()); Assert.assertNull(request.getTokens()); - Assert.assertTrue(request.getReturnTokens()); + Assert.assertFalse(request.getReturnTokens()); Assert.assertFalse(request.getContinueOnError()); Assert.assertFalse(request.getHomogeneous()); } catch (SkyflowException e) { diff --git a/src/test/java/com/skyflow/vault/data/QueryTests.java b/src/test/java/com/skyflow/vault/data/QueryTests.java index fdf51482..7a8cca5e 100644 --- a/src/test/java/com/skyflow/vault/data/QueryTests.java +++ b/src/test/java/com/skyflow/vault/data/QueryTests.java @@ -95,8 +95,8 @@ public void testQueryResponse() { fields.add(queryRecord); QueryResponse response = new QueryResponse(fields); String responseString = "{\"fields\":" + - "[{\"card_number\":\"test_card_number\",\"name\":\"test_name\",\"tokenizedData\":null}," + - "{\"card_number\":\"test_card_number\",\"name\":\"test_name\",\"tokenizedData\":null}]," + + "[{\"card_number\":\"test_card_number\",\"name\":\"test_name\",\"tokenizedData\":{}}," + + "{\"card_number\":\"test_card_number\",\"name\":\"test_name\",\"tokenizedData\":{}}]," + "\"errors\":[]}"; Assert.assertEquals(2, response.getFields().size()); Assert.assertEquals(responseString, response.toString()); diff --git a/src/test/java/com/skyflow/vault/data/UpdateTests.java b/src/test/java/com/skyflow/vault/data/UpdateTests.java index 3253306a..7032fcb0 100644 --- a/src/test/java/com/skyflow/vault/data/UpdateTests.java +++ b/src/test/java/com/skyflow/vault/data/UpdateTests.java @@ -94,7 +94,7 @@ public void testValidInputInUpdateRequestValidationsWithTokenModeDisable() { Validations.validateUpdateRequest(request); Assert.assertEquals(table, request.getTable()); Assert.assertEquals(3, request.getData().size()); - Assert.assertTrue(request.getReturnTokens()); + Assert.assertFalse(request.getReturnTokens()); Assert.assertNull(request.getTokens()); } catch (SkyflowException e) { Assert.fail(INVALID_EXCEPTION_THROWN); @@ -446,9 +446,9 @@ public void testUpdateResponse() { tokenMap.put("test_column_1", "test_token_1"); tokenMap.put("test_column_2", "test_token_2"); UpdateResponse response = new UpdateResponse(skyflowID, tokenMap); - String responseString = "{\"skyflow_id\":\"" + skyflowID + "\"," - + "\"test_column_1\":\"test_token_1\"," - + "\"test_column_2\":\"test_token_2\"}"; + String responseString = "{\"updatedField\":{\"skyflowId\":\"" + skyflowID + "\"," + + "\"test_column_1\":\"test_token_1\",\"test_column_2\":\"test_token_2\"}" + + ",\"errors\":[]}"; Assert.assertEquals(skyflowID, response.getSkyflowId()); Assert.assertEquals(2, response.getTokens().size()); Assert.assertEquals(responseString, response.toString()); diff --git a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index 29633ced..3577f7db 100644 --- a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -61,7 +61,7 @@ public void testNoTokensInDetokenizeRequestValidations() { e.getMessage() ); Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); - Assert.assertTrue(request.getContinueOnError()); + Assert.assertFalse(request.getContinueOnError()); } } @@ -78,7 +78,7 @@ public void testEmptyTokensInDetokenizeRequestValidations() { e.getMessage() ); Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); - Assert.assertTrue(request.getContinueOnError()); + Assert.assertFalse(request.getContinueOnError()); } } @@ -97,7 +97,7 @@ public void testEmptyTokenInTokensInDetokenizeRequestValidations() { e.getMessage() ); Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); - Assert.assertTrue(request.getContinueOnError()); + Assert.assertFalse(request.getContinueOnError()); } } @@ -116,7 +116,7 @@ public void testNullTokenInTokensInDetokenizeRequestValidations() { e.getMessage() ); Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); - Assert.assertTrue(request.getContinueOnError()); + Assert.assertFalse(request.getContinueOnError()); } } @@ -128,7 +128,7 @@ public void testRedactionAndContinueOnErrorInDetokenizeRequestValidations() { try { Validations.validateDetokenizeRequest(request); Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); - Assert.assertTrue(request.getContinueOnError()); + Assert.assertFalse(request.getContinueOnError()); } catch (SkyflowException e) { Assert.fail(INVALID_EXCEPTION_THROWN); } diff --git a/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java index 0ad09735..821ad844 100644 --- a/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java @@ -157,7 +157,9 @@ public void testTokenizeResponse() { tokens.add("1234-5678-9012-3456"); tokens.add("5678-9012-3456-7890"); TokenizeResponse response = new TokenizeResponse(tokens); - String responseString = "{\"tokens\":[\"1234-5678-9012-3456\",\"5678-9012-3456-7890\"],\"errors\":[]}"; + String responseString = "{\"tokens\":[" + + "{\"token\":\"1234-5678-9012-3456\"},{\"token\":\"5678-9012-3456-7890\"}]" + + ",\"errors\":[]}"; Assert.assertEquals(2, response.getTokens().size()); Assert.assertEquals(responseString, response.toString()); } catch (Exception e) { From 038bd748c7ed26580d8741a0d3119342b3c63f28 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 10 Dec 2024 17:23:30 +0530 Subject: [PATCH 085/126] SK-1737 Fix inconsistencies in Java SDK --- src/main/java/com/skyflow/Skyflow.java | 18 +++++++--- .../java/com/skyflow/utils/HttpUtility.java | 7 ++-- .../utils/validations/Validations.java | 7 ++-- .../connection/InvokeConnectionResponse.java | 24 +++++++------ .../controller/ConnectionController.java | 5 ++- src/test/java/com/skyflow/SkyflowTests.java | 34 +++++++++++++++++++ .../connection/InvokeConnectionTests.java | 17 ++++++---- .../controller/ConnectionControllerTests.java | 2 +- 8 files changed, 86 insertions(+), 28 deletions(-) diff --git a/src/main/java/com/skyflow/Skyflow.java b/src/main/java/com/skyflow/Skyflow.java index 2a2e42cc..6866bd43 100644 --- a/src/main/java/com/skyflow/Skyflow.java +++ b/src/main/java/com/skyflow/Skyflow.java @@ -82,13 +82,23 @@ public LogLevel getLogLevel() { return this.builder.logLevel; } - public VaultController vault() { - String vaultId = (String) this.builder.vaultClientsMap.keySet().toArray()[0]; + public VaultController vault() throws SkyflowException { + Object[] array = this.builder.vaultClientsMap.keySet().toArray(); + if (array.length < 1) { + LogUtil.printErrorLog(ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultIdNotInConfigList.getMessage()); + } + String vaultId = (String) array[0]; return this.vault(vaultId); } - public VaultController vault(String vaultId) { - return this.builder.vaultClientsMap.get(vaultId); + public VaultController vault(String vaultId) throws SkyflowException { + VaultController controller = this.builder.vaultClientsMap.get(vaultId); + if (controller == null) { + LogUtil.printErrorLog(ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultIdNotInConfigList.getMessage()); + } + return controller; } public ConnectionController connection() { diff --git a/src/main/java/com/skyflow/utils/HttpUtility.java b/src/main/java/com/skyflow/utils/HttpUtility.java index 93cbdd31..664cc9da 100644 --- a/src/main/java/com/skyflow/utils/HttpUtility.java +++ b/src/main/java/com/skyflow/utils/HttpUtility.java @@ -13,14 +13,13 @@ public final class HttpUtility { + private static final String LINE_FEED = "\r\n"; private static String requestID; public static String getRequestID() { return requestID; } - private static final String LINE_FEED = "\r\n"; - public static String sendRequest(String method, URL url, JsonObject params, Map headers) throws IOException, SkyflowException { HttpURLConnection connection = null; @@ -55,7 +54,7 @@ public static String sendRequest(String method, URL url, JsonObject params, Map< input = formatJsonToFormEncodedString(params).getBytes(StandardCharsets.UTF_8); } else if (requestContentType.contains("multipart/form-data")) { input = formatJsonToMultiPartFormDataString(params, boundary).getBytes(StandardCharsets.UTF_8); - }else { + } else { input = params.toString().getBytes(StandardCharsets.UTF_8); } @@ -66,7 +65,7 @@ public static String sendRequest(String method, URL url, JsonObject params, Map< int status = connection.getResponseCode(); String requestID = connection.getHeaderField("x-request-id"); - HttpUtility.requestID = requestID; + HttpUtility.requestID = requestID.split(",")[0]; Reader streamReader; if (status > 299) { diff --git a/src/main/java/com/skyflow/utils/validations/Validations.java b/src/main/java/com/skyflow/utils/validations/Validations.java index 67853bab..2876c15d 100644 --- a/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/src/main/java/com/skyflow/utils/validations/Validations.java @@ -1,5 +1,7 @@ package com.skyflow.utils.validations; +import com.google.gson.Gson; +import com.google.gson.JsonObject; import com.skyflow.config.ConnectionConfig; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; @@ -132,8 +134,9 @@ public static void validateInvokeConnectionRequest(InvokeConnectionRequest invok } if (requestBody != null) { - Map requestBodyMap = (Map) requestBody; - if (requestBodyMap.isEmpty()) { + Gson gson = new Gson(); + JsonObject bodyObject = gson.toJsonTree(requestBody).getAsJsonObject(); + if (bodyObject.isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_REQUEST_BODY.getLog(), InterfaceName.INVOKE_CONNECTION.getName())); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestBody.getMessage()); diff --git a/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java b/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java index 76f8823f..a30a44c9 100644 --- a/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java +++ b/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java @@ -1,25 +1,29 @@ package com.skyflow.vault.connection; import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; -import com.google.gson.JsonParser; public class InvokeConnectionResponse { - private JsonObject response; + private final JsonObject data; + private final JsonObject metadata; - public InvokeConnectionResponse(JsonObject response) { - this.response = response; + public InvokeConnectionResponse(JsonObject data, JsonObject metadata) { + this.data = data; + this.metadata = metadata; } - public JsonObject getResponse() { - return response; + public JsonObject getData() { + return data; + } + + public JsonObject getMetadata() { + return metadata; } @Override public String toString() { - Gson gson = new Gson(); - JsonObject responseObject = JsonParser.parseString(gson.toJson(this)).getAsJsonObject(); - responseObject = responseObject.remove("response").getAsJsonObject(); - return responseObject.toString(); + Gson gson = new GsonBuilder().serializeNulls().create(); + return gson.toJson(this); } } diff --git a/src/main/java/com/skyflow/vault/controller/ConnectionController.java b/src/main/java/com/skyflow/vault/controller/ConnectionController.java index 66720521..0bb2251e 100644 --- a/src/main/java/com/skyflow/vault/controller/ConnectionController.java +++ b/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -64,7 +64,10 @@ public InvokeConnectionResponse invoke(InvokeConnectionRequest invokeConnectionR } String response = HttpUtility.sendRequest(requestMethod.name(), new URL(filledURL), requestBody, headers); - connectionResponse = new InvokeConnectionResponse((JsonObject) JsonParser.parseString(response)); + JsonObject data = JsonParser.parseString(response).getAsJsonObject(); + JsonObject metadata = new JsonObject(); + metadata.addProperty("requestId", HttpUtility.getRequestID()); + connectionResponse = new InvokeConnectionResponse(data, metadata); LogUtil.printInfoLog(InfoLogs.INVOKE_CONNECTION_REQUEST_RESOLVED.getLog()); } catch (IOException e) { LogUtil.printErrorLog(ErrorLogs.INVOKE_CONNECTION_REQUEST_REJECTED.getLog()); diff --git a/src/test/java/com/skyflow/SkyflowTests.java b/src/test/java/com/skyflow/SkyflowTests.java index f7385af1..8ccff81d 100644 --- a/src/test/java/com/skyflow/SkyflowTests.java +++ b/src/test/java/com/skyflow/SkyflowTests.java @@ -198,6 +198,40 @@ public void testGettingNonExistentVaultConfigInSkyflowClient() { } } + @Test + public void testGettingAlreadyRemovedVaultFromEmptyConfigs() { + try { + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.vault(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testGettingAlreadyRemovedVaultFromNonEmptyConfigs() { + try { + VaultConfig primaryConfig = new VaultConfig(); + primaryConfig.setVaultId(vaultID); + primaryConfig.setClusterId(clusterID); + primaryConfig.setEnv(Env.SANDBOX); + + VaultConfig secondaryConfig = new VaultConfig(); + secondaryConfig.setVaultId(vaultID + "123"); + secondaryConfig.setClusterId(clusterID); + secondaryConfig.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().addVaultConfig(primaryConfig).addVaultConfig(secondaryConfig).build(); + skyflowClient.removeVaultConfig(vaultID); + skyflowClient.vault(vaultID); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + @Test public void testAddingInvalidConnectionConfigInSkyflowBuilder() { diff --git a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java index 6ac020e1..90bc4c1e 100644 --- a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java +++ b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java @@ -420,12 +420,17 @@ public void testEmptyRequestBodyInInvokeConnectionRequestValidations() { @Test public void testInvokeConnectionResponse() { try { - JsonObject responseObject = new JsonObject(); - responseObject.addProperty("test_key_1", "test_value_1"); - responseObject.addProperty("test_key_2", "test_value_2"); - InvokeConnectionResponse connectionResponse = new InvokeConnectionResponse(responseObject); - Assert.assertEquals(2, connectionResponse.getResponse().size()); - Assert.assertEquals(responseObject.toString(), connectionResponse.toString()); + JsonObject data = new JsonObject(); + data.addProperty("test_key_1", "test_value_1"); + data.addProperty("test_key_2", "test_value_2"); + JsonObject metadata = new JsonObject(); + metadata.addProperty("requestId", "12345"); + InvokeConnectionResponse connectionResponse = new InvokeConnectionResponse(data, metadata); + String responseString = "{\"data\":{\"test_key_1\":\"test_value_1\",\"test_key_2\":\"test_value_2\"}," + + "\"metadata\":{\"requestId\":\"12345\"}}"; + Assert.assertEquals(2, connectionResponse.getData().size()); + Assert.assertEquals(responseString, connectionResponse.toString()); + Assert.assertEquals(1, connectionResponse.getMetadata().size()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } diff --git a/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java b/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java index 102eb9d7..b121280a 100644 --- a/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java +++ b/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java @@ -39,7 +39,7 @@ public static void setup() { @Test public void testInvalidRequestInInvokeConnectionMethod() { try { - HashMap requestBody = new HashMap<>(); + HashMap requestBody = new HashMap<>(); InvokeConnectionRequest connectionRequest = InvokeConnectionRequest.builder().requestBody(requestBody).build(); Skyflow skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addConnectionConfig(connectionConfig).build(); skyflowClient.connection().invoke(connectionRequest); From 7938fa6403c2c7253e60ba84508ca94cca6b3044 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 10 Dec 2024 12:27:28 +0000 Subject: [PATCH 086/126] [AUTOMATED] Private Release 1.15.0-dev-8339ce7 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2801b615..c56da584 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0-dev.4ea53e6 + 1.15.0-dev.8339ce7 jar ${project.groupId}:${project.artifactId} From f146b51a64c31242e78fd57828444a8043e958a2 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 11 Dec 2024 12:39:22 +0530 Subject: [PATCH 087/126] SK-1737 Update workflow to fix build issue --- .github/workflows/pr.yml | 10 +++++----- .github/workflows/shared-build-and-deploy.yml | 18 ++++++++++-------- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index ff48495f..5554efe3 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -11,11 +11,11 @@ jobs: uses: gsactions/commit-message-checker@v1 with: pattern: '(\[?[A-Z]{1,5}-[1-9][0-9]*)|(\[AUTOMATED\])|(Merge)|(Release).+$' - flags: 'gm' - excludeDescription: 'true' - checkAllCommitMessages: 'true' + flags: "gm" + excludeDescription: "true" + checkAllCommitMessages: "true" accessToken: ${{ secrets.PAT_ACTIONS }} - error: 'One of your your commit messages is not matching the format with JIRA ID Ex: ( SDK-123 commit message )' + error: "One of your your commit messages is not matching the format with JIRA ID Ex: ( SDK-123 commit message )" Test: runs-on: ubuntu-latest steps: @@ -40,7 +40,7 @@ jobs: echo TEST_REUSABLE_TOKEN=${{ secrets.TEST_REUSABLE_TOKEN }} >> .env - name: Build & Run tests with Maven - run: mvn -B package -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -DTEST_DATA_CREDENTIALS_FILE=${{ secrets.TEST_DATA_CREDENTIALS_FILE }} -f pom.xml + run: mvn -B package -f pom.xml - name: Codecov uses: codecov/codecov-action@v2.1.0 diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index e235a83d..b8a3186f 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -3,22 +3,22 @@ on: workflow_call: inputs: ref: - description: 'Git reference to use (e.g., main or branch name)' + description: "Git reference to use (e.g., main or branch name)" required: true type: string is-internal: - description: 'Flag for internal release' + description: "Flag for internal release" required: true type: boolean server-id: - description: 'Id of the repository' + description: "Id of the repository" required: true type: string - + profile: - description: 'Profile to pick from pom.xml' + description: "Profile to pick from pom.xml" required: true type: string secrets: @@ -34,6 +34,9 @@ on: gpg-passphrase: required: true +env: + TEST_REUSABLE_TOKEN: ${{ secrets.TEST_REUSABLE_TOKEN }} + jobs: publish: runs-on: ubuntu-latest @@ -46,8 +49,8 @@ jobs: - name: Set up maven or jfrog repository uses: actions/setup-java@v1 with: - java-version: '1.8' - distribution: 'adopt' + java-version: "1.8" + distribution: "adopt" server-id: ${{ inputs.server-id }} server-username: SERVER_USERNAME server-password: SERVER_PASSWORD @@ -89,7 +92,6 @@ jobs: touch .env echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env - echo TEST_REUSABLE_TOKEN=${{ secrets.TEST_REUSABLE_TOKEN }} >> .env - name: Create credentials json id: create-json From 09fb1e8bf11290732c1c60dc4dd1dbce9a7c881e Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 11 Dec 2024 07:10:59 +0000 Subject: [PATCH 088/126] [AUTOMATED] Private Release 1.15.0-dev-f146b51 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c56da584..50021123 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0-dev.8339ce7 + 1.15.0-dev.f146b51 jar ${project.groupId}:${project.artifactId} From ad9b710af44ec93891d24f725b894337032a9b1d Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 11 Dec 2024 12:49:44 +0530 Subject: [PATCH 089/126] SK-1737 add stack trace to debug failures --- src/test/java/com/skyflow/ConnectionClientTests.java | 1 + src/test/java/com/skyflow/VaultClientTests.java | 1 + 2 files changed, 2 insertions(+) diff --git a/src/test/java/com/skyflow/ConnectionClientTests.java b/src/test/java/com/skyflow/ConnectionClientTests.java index 4a69120c..ab514844 100644 --- a/src/test/java/com/skyflow/ConnectionClientTests.java +++ b/src/test/java/com/skyflow/ConnectionClientTests.java @@ -58,6 +58,7 @@ public void testSetBearerToken() { // re-use scenario connectionClient.setBearerToken(); } catch (Exception e) { + e.printStackTrace(); Assert.fail(INVALID_EXCEPTION_THROWN); } } diff --git a/src/test/java/com/skyflow/VaultClientTests.java b/src/test/java/com/skyflow/VaultClientTests.java index 8a02caaf..66495140 100644 --- a/src/test/java/com/skyflow/VaultClientTests.java +++ b/src/test/java/com/skyflow/VaultClientTests.java @@ -264,6 +264,7 @@ public void testSetBearerToken() { HttpBearerAuth auth = (HttpBearerAuth) vaultClient.getApiClient().getAuthentication("Bearer"); Assert.assertEquals(bearerToken, auth.getBearerToken()); } catch (Exception e) { + e.printStackTrace(); Assert.fail(INVALID_EXCEPTION_THROWN); } } From deddbcffc79e0d6d634a01621a0731ea92373794 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 11 Dec 2024 07:20:16 +0000 Subject: [PATCH 090/126] [AUTOMATED] Private Release 1.15.0-dev-ad9b710 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 50021123..10c37658 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0-dev.f146b51 + 1.15.0-dev.ad9b710 jar ${project.groupId}:${project.artifactId} From d2e7155415d71a392f9bd273c0c8cb0c8a42ccb1 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 11 Dec 2024 13:02:18 +0530 Subject: [PATCH 091/126] SK-1737 Fix spelling in error message --- .github/workflows/shared-build-and-deploy.yml | 4 +--- src/main/java/com/skyflow/errors/ErrorMessage.java | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index b8a3186f..faadc389 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -34,9 +34,6 @@ on: gpg-passphrase: required: true -env: - TEST_REUSABLE_TOKEN: ${{ secrets.TEST_REUSABLE_TOKEN }} - jobs: publish: runs-on: ubuntu-latest @@ -92,6 +89,7 @@ jobs: touch .env echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + echo TEST_REUSABLE_TOKEN=${{ secrets.TEST_REUSABLE_TOKEN }} >> .env - name: Create credentials json id: create-json diff --git a/src/main/java/com/skyflow/errors/ErrorMessage.java b/src/main/java/com/skyflow/errors/ErrorMessage.java index e1034976..d6af06aa 100644 --- a/src/main/java/com/skyflow/errors/ErrorMessage.java +++ b/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -28,7 +28,7 @@ public enum ErrorMessage { NoTokenGenerationMeansPassed("%s0 Initialization failed. Invalid credentials. Specify any one from 'path', 'credentialsString', 'token' or 'apiKey'."), EmptyCredentialFilePath("%s0 Initialization failed. Invalid credentials. Credentials file path must not be empty."), EmptyCredentialsString("%s0 Initialization failed. Invalid credentials. Credentials string must not be empty."), - EmptyToken("%s0 Initialization failed. Invalid credentials. Token mut not be empty."), + EmptyToken("%s0 Initialization failed. Invalid credentials. Token must not be empty."), EmptyApikey("%s0 Initialization failed. Invalid credentials. Api key must not be empty."), InvalidApikey("%s0 Initialization failed. Invalid credentials. Specify valid api key."), EmptyRoles("%s0 Initialization failed. Invalid roles. Specify at least one role."), From a3f5f23ff9573f3be609c39be067705baa2c7b36 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 11 Dec 2024 07:32:49 +0000 Subject: [PATCH 092/126] [AUTOMATED] Private Release 1.15.0-dev-d2e7155 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 10c37658..81c59c51 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0-dev.ad9b710 + 1.15.0-dev.d2e7155 jar ${project.groupId}:${project.artifactId} From a0537e8df29d0e115527c373e81f494379880992 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 11 Dec 2024 13:22:33 +0530 Subject: [PATCH 093/126] SK-1737 Added secrets for shared workflow --- .github/workflows/internal-release.yml | 5 +++-- .github/workflows/release.yml | 4 +++- .github/workflows/shared-build-and-deploy.yml | 15 ++++++++++++--- .../java/com/skyflow/ConnectionClientTests.java | 1 - src/test/java/com/skyflow/VaultClientTests.java | 1 - 5 files changed, 18 insertions(+), 8 deletions(-) diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index a354c5cc..6aea0e52 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -21,5 +21,6 @@ jobs: server-password: ${{ secrets.ARTIFACTORY_PASSWORD }} gpg-key: ${{ secrets.JFROG_GPG_KEY }} gpg-passphrase: ${{ secrets.JFROG_GPG_PASSPHRASE }} - - + skyflow-credentials: ${{ secrets.SKYFLOW_CREDENTIALS }} >> .env + test-expired-token: ${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + test-reusable-token: ${{ secrets.TEST_REUSABLE_TOKEN }} >> .env diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7b6c57de..a4c7bfd9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,4 +15,6 @@ jobs: server-password: ${{ secrets.OSSRH_PASSWORD }} gpg-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} gpg-passphrase: ${{ secrets.MAVEN_GPG_PASSPHRASE }} - \ No newline at end of file + skyflow-credentials: ${{ secrets.SKYFLOW_CREDENTIALS }} >> .env + test-expired-token: ${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + test-reusable-token: ${{ secrets.TEST_REUSABLE_TOKEN }} >> .env diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index faadc389..4bd80367 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -34,6 +34,15 @@ on: gpg-passphrase: required: true + skyflow-credentials: + required: true + + test-expired-token: + required: true + + test-reusable-token: + required: true + jobs: publish: runs-on: ubuntu-latest @@ -87,9 +96,9 @@ jobs: id: create-env run: | touch .env - echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env - echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env - echo TEST_REUSABLE_TOKEN=${{ secrets.TEST_REUSABLE_TOKEN }} >> .env + echo SKYFLOW_CREDENTIALS=${{ secrets.skyflow-credentials }} >> .env + echo TEST_EXPIRED_TOKEN=${{ secrets.test-expired-token }} >> .env + echo TEST_REUSABLE_TOKEN=${{ secrets.test-reusable-token }} >> .env - name: Create credentials json id: create-json diff --git a/src/test/java/com/skyflow/ConnectionClientTests.java b/src/test/java/com/skyflow/ConnectionClientTests.java index ab514844..4a69120c 100644 --- a/src/test/java/com/skyflow/ConnectionClientTests.java +++ b/src/test/java/com/skyflow/ConnectionClientTests.java @@ -58,7 +58,6 @@ public void testSetBearerToken() { // re-use scenario connectionClient.setBearerToken(); } catch (Exception e) { - e.printStackTrace(); Assert.fail(INVALID_EXCEPTION_THROWN); } } diff --git a/src/test/java/com/skyflow/VaultClientTests.java b/src/test/java/com/skyflow/VaultClientTests.java index 66495140..8a02caaf 100644 --- a/src/test/java/com/skyflow/VaultClientTests.java +++ b/src/test/java/com/skyflow/VaultClientTests.java @@ -264,7 +264,6 @@ public void testSetBearerToken() { HttpBearerAuth auth = (HttpBearerAuth) vaultClient.getApiClient().getAuthentication("Bearer"); Assert.assertEquals(bearerToken, auth.getBearerToken()); } catch (Exception e) { - e.printStackTrace(); Assert.fail(INVALID_EXCEPTION_THROWN); } } From 3231ca87aef4153608eaf1f643c47f8cd2101825 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 11 Dec 2024 07:53:00 +0000 Subject: [PATCH 094/126] [AUTOMATED] Private Release 1.15.0-dev-a0537e8 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 81c59c51..63dfe263 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0-dev.d2e7155 + 1.15.0-dev.a0537e8 jar ${project.groupId}:${project.artifactId} From b4dd8bddb64f01fb9c21e974e571477c61ae34e8 Mon Sep 17 00:00:00 2001 From: skyflow-shravan <121150537+skyflow-shravan@users.noreply.github.com> Date: Wed, 15 Jan 2025 13:34:41 +0530 Subject: [PATCH 095/126] SK-1815 workflow for beta release (#152) * SK-1815 workflow for beta release * SK-1815 workflow for beta release * SK-1815 workflow for beta release * SK-1815 workflow for beta release --- .github/workflows/beta-release.yml | 20 ++++++++++++++++++ .github/workflows/internal-release.yml | 5 +++-- .github/workflows/release.yml | 4 ++-- .github/workflows/shared-build-and-deploy.yml | 21 ++++++++++--------- 4 files changed, 36 insertions(+), 14 deletions(-) create mode 100644 .github/workflows/beta-release.yml diff --git a/.github/workflows/beta-release.yml b/.github/workflows/beta-release.yml new file mode 100644 index 00000000..c723914a --- /dev/null +++ b/.github/workflows/beta-release.yml @@ -0,0 +1,20 @@ +name: Public beta release +on: + push: + tags: '*.*.*-beta.*' +jobs: + build-and-deploy: + uses: ./.github/workflows/shared-build-and-deploy.yml + with: + ref: ${{ github.ref_name }} + server-id: ossrh + profile: maven-central + tag: 'beta' + secrets: + server-username: ${{ secrets.OSSRH_USERNAME }} + server-password: ${{ secrets.OSSRH_PASSWORD }} + gpg-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} + gpg-passphrase: ${{ secrets.MAVEN_GPG_PASSPHRASE }} + skyflow-credentials: ${{ secrets.SKYFLOW_CREDENTIALS }} >> .env + test-expired-token: ${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + test-reusable-token: ${{ secrets.TEST_REUSABLE_TOKEN }} >> .env diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index 6aea0e52..f87afc29 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -1,7 +1,8 @@ name: Publish package to the JFROG Artifactory on: push: - tags: '*.*.*' + tags-ignore: + - '*.*' paths-ignore: - "pom.xml" - "*.md" @@ -13,9 +14,9 @@ jobs: uses: ./.github/workflows/shared-build-and-deploy.yml with: ref: ${{ github.ref_name }} - is-internal: true server-id: central profile: jfrog + tag: 'internal' secrets: server-username: ${{ secrets.ARTIFACTORY_USERNAME }} server-password: ${{ secrets.ARTIFACTORY_PASSWORD }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a4c7bfd9..855b7b4c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,4 +1,4 @@ -name: Publish package to the Maven Central Repository +name: Public release on: push: tags: '*.*.*' @@ -7,9 +7,9 @@ jobs: uses: ./.github/workflows/shared-build-and-deploy.yml with: ref: ${{ github.ref_name }} - is-internal: false server-id: ossrh profile: maven-central + tag: 'public' secrets: server-username: ${{ secrets.OSSRH_USERNAME }} server-password: ${{ secrets.OSSRH_PASSWORD }} diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index 4bd80367..28b4d01f 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -7,11 +7,6 @@ on: required: true type: string - is-internal: - description: "Flag for internal release" - required: true - type: boolean - server-id: description: "Id of the repository" required: true @@ -21,6 +16,11 @@ on: description: "Profile to pick from pom.xml" required: true type: string + + tag: + description: 'Release Tag' + required: true + type: string secrets: server-username: required: true @@ -49,7 +49,6 @@ jobs: steps: - uses: actions/checkout@v2 with: - ref: ${{ inputs.ref }} fetch-depth: 0 - name: Set up maven or jfrog repository @@ -72,27 +71,29 @@ jobs: - name: Bump Version run: | chmod +x ./scripts/bump_version.sh - if ${{ inputs.is-internal }}; then + if ${{ inputs.tag == 'internal' }}; then ./scripts/bump_version.sh "${{ steps.previoustag.outputs.tag }}" "$(git rev-parse --short "$GITHUB_SHA")" else ./scripts/bump_version.sh "${{ steps.previoustag.outputs.tag }}" fi - name: Commit changes + if: ${{ inputs.tag == 'internal' || inputs.tag == 'public' }} run: | git config user.name ${{ github.actor }} git config user.email ${{ github.actor }}@users.noreply.github.com git add pom.xml - if ${{ inputs.is-internal }}; then + if ${{ inputs.tag == 'internal' }}; then git commit -m "[AUTOMATED] Private Release ${{ steps.previoustag.outputs.tag }}-dev-$(git rev-parse --short $GITHUB_SHA)" git push origin ${{ github.ref_name }} -f - else + fi + if ${{ inputs.tag == 'public' }}; then git commit -m "[AUTOMATED] Public Release - ${{ steps.previoustag.outputs.tag }}" git push origin fi - name: Create env - if: ${{ inputs.is-internal }} + if: ${{ inputs.tag == 'internal' }} id: create-env run: | touch .env From 35ba49f9fb0beff80334a07f61fe9b056af1b762 Mon Sep 17 00:00:00 2001 From: skyflow-vivek <121149418+skyflow-vivek@users.noreply.github.com> Date: Thu, 16 Jan 2025 19:58:51 +0530 Subject: [PATCH 096/126] SK-1829/Release/25.1.1 (#155) * SK-1829 Fix http status for validation errors in Java SDK v2 * SK-1829 Fix errors in Invoke connection flow in Java SDK v2 * [AUTOMATED] Private Release 1.15.0-dev-27ca248 --------- Co-authored-by: skyflow-vivek --- pom.xml | 2 +- .../java/com/skyflow/errors/HttpStatus.java | 15 ++++++ .../com/skyflow/errors/SkyflowException.java | 41 ++++++++-------- .../java/com/skyflow/utils/HttpUtility.java | 48 +++++++------------ .../connection/InvokeConnectionResponse.java | 13 ++--- .../controller/ConnectionController.java | 6 +-- .../com/skyflow/utils/HttpUtilityTests.java | 8 +++- .../connection/InvokeConnectionTests.java | 6 +-- .../controller/VaultControllerTests.java | 5 +- 9 files changed, 75 insertions(+), 69 deletions(-) create mode 100644 src/main/java/com/skyflow/errors/HttpStatus.java diff --git a/pom.xml b/pom.xml index 63dfe263..99d337e7 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0-dev.a0537e8 + 1.15.0-dev.27ca248 jar ${project.groupId}:${project.artifactId} diff --git a/src/main/java/com/skyflow/errors/HttpStatus.java b/src/main/java/com/skyflow/errors/HttpStatus.java new file mode 100644 index 00000000..2cdadbb0 --- /dev/null +++ b/src/main/java/com/skyflow/errors/HttpStatus.java @@ -0,0 +1,15 @@ +package com.skyflow.errors; + +public enum HttpStatus { + BAD_REQUEST("Bad Request"); + + private final String httpStatus; + + HttpStatus(String httpStatus) { + this.httpStatus = httpStatus; + } + + public String getHttpStatus() { + return httpStatus; + } +} diff --git a/src/main/java/com/skyflow/errors/SkyflowException.java b/src/main/java/com/skyflow/errors/SkyflowException.java index 6cff3cdd..1db1ed19 100644 --- a/src/main/java/com/skyflow/errors/SkyflowException.java +++ b/src/main/java/com/skyflow/errors/SkyflowException.java @@ -1,13 +1,9 @@ package com.skyflow.errors; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; +import com.google.gson.*; import java.util.List; import java.util.Map; -import java.util.Objects; public class SkyflowException extends Exception { private String requestId; @@ -37,28 +33,27 @@ public SkyflowException(int code, String message) { super(message); this.httpCode = code; this.message = message; + this.httpStatus = HttpStatus.BAD_REQUEST.getHttpStatus(); + this.details = new JsonArray(); } public SkyflowException(int httpCode, Throwable cause, Map> responseHeaders, String responseBody) { - this(cause); + super(cause); this.httpCode = httpCode; - String contentType = responseHeaders.get("content-type").get(0); setRequestId(responseHeaders); - if (Objects.equals(contentType, "application/json")) { - setResponseBody(responseBody); - } else if (Objects.equals(contentType, "text/plain")) { - this.message = responseBody; - } + setResponseBody(responseBody); } private void setResponseBody(String responseBody) { try { if (responseBody != null) { this.responseBody = JsonParser.parseString(responseBody).getAsJsonObject(); - setGrpcCode(); - setHttpStatus(); - setMessage(); - setDetails(); + if (this.responseBody.get("error") != null) { + setGrpcCode(); + setHttpStatus(); + setMessage(); + setDetails(); + } } } catch (JsonSyntaxException e) { throw new RuntimeException(e); @@ -72,24 +67,28 @@ public String getRequestId() { private void setRequestId(Map> responseHeaders) { if (responseHeaders != null) { List ids = responseHeaders.get("x-request-id"); - this.requestId = ids.get(0); + this.requestId = ids == null ? null : ids.get(0); } } private void setMessage() { - this.message = ((JsonObject) responseBody.get("error")).get("message").getAsString(); + JsonElement messageElement = ((JsonObject) responseBody.get("error")).get("message"); + this.message = messageElement == null ? null : messageElement.getAsString(); } private void setGrpcCode() { - this.grpcCode = ((JsonObject) responseBody.get("error")).get("grpc_code").getAsInt(); + JsonElement grpcElement = ((JsonObject) responseBody.get("error")).get("grpc_code"); + this.grpcCode = grpcElement == null ? null : grpcElement.getAsInt(); } private void setHttpStatus() { - this.httpStatus = ((JsonObject) responseBody.get("error")).get("http_status").getAsString(); + JsonElement statusElement = ((JsonObject) responseBody.get("error")).get("http_status"); + this.httpStatus = statusElement == null ? null : statusElement.getAsString(); } private void setDetails() { - this.details = ((JsonObject) responseBody.get("error")).get("details").getAsJsonArray(); + JsonElement detailsElement = ((JsonObject) responseBody.get("error")).get("details"); + this.details = detailsElement == null ? null : detailsElement.getAsJsonArray(); } public int getHttpCode() { diff --git a/src/main/java/com/skyflow/utils/HttpUtility.java b/src/main/java/com/skyflow/utils/HttpUtility.java index 664cc9da..b8e9283b 100644 --- a/src/main/java/com/skyflow/utils/HttpUtility.java +++ b/src/main/java/com/skyflow/utils/HttpUtility.java @@ -1,7 +1,7 @@ package com.skyflow.utils; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import com.skyflow.errors.SkyflowException; import java.io.*; @@ -9,7 +9,9 @@ import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.Objects; public final class HttpUtility { @@ -33,18 +35,18 @@ public static String sendRequest(String method, URL url, JsonObject params, Map< connection.setRequestProperty("content-type", "application/json"); connection.setRequestProperty("Accept", "*/*"); - if (headers != null && headers.size() > 0) { + if (headers != null && !headers.isEmpty()) { for (Map.Entry entry : headers.entrySet()) connection.setRequestProperty(entry.getKey(), entry.getValue()); // append dynamic boundary if content-type is multipart/form-data if (headers.containsKey("content-type")) { - if (headers.get("content-type") == "multipart/form-data") { + if (Objects.equals(headers.get("content-type"), "multipart/form-data")) { connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary); } } } - if (params != null && params.size() > 0) { + if (params != null && !params.isEmpty()) { connection.setDoOutput(true); try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { byte[] input = null; @@ -63,12 +65,12 @@ public static String sendRequest(String method, URL url, JsonObject params, Map< } } - int status = connection.getResponseCode(); + int httpCode = connection.getResponseCode(); String requestID = connection.getHeaderField("x-request-id"); HttpUtility.requestID = requestID.split(",")[0]; - + Map> responseHeaders = connection.getHeaderFields(); Reader streamReader; - if (status > 299) { + if (httpCode > 299) { if (connection.getErrorStream() != null) streamReader = new InputStreamReader(connection.getErrorStream()); else { @@ -86,9 +88,8 @@ public static String sendRequest(String method, URL url, JsonObject params, Map< response.append(inputLine); } - if (status > 299) { - String errorMsg = appendRequestIdToErrorObj(status, response.toString(), requestID); - throw new SkyflowException(errorMsg); + if (httpCode > 299) { + throw new SkyflowException(httpCode, new Throwable(), responseHeaders, response.toString()); } } finally { if (in != null) { @@ -127,13 +128,14 @@ public static String formatJsonToMultiPartFormDataString(JsonObject requestBody, private static HashMap convertJsonToMap(JsonObject json, String rootKey) { HashMap currentMap = new HashMap<>(); - for (Object key : json.keySet()) { - Object currentValue = json.get((String) key); - String currentKey = rootKey.length() != 0 ? rootKey + '[' + key.toString() + ']' : rootKey + key.toString(); - if (currentValue instanceof JsonObject) { + Map jsonMap = json.asMap(); + for (String key : jsonMap.keySet()) { + JsonElement currentValue = jsonMap.get(key); + String currentKey = !rootKey.isEmpty() ? rootKey + '[' + key + ']' : rootKey + key; + if (currentValue.isJsonObject()) { currentMap.putAll(convertJsonToMap((JsonObject) currentValue, currentKey)); } else { - currentMap.put(currentKey, currentValue.toString()); + currentMap.put(currentKey, currentValue.getAsString()); } } return currentMap; @@ -156,22 +158,6 @@ public static String appendRequestId(String message, String requestId) { return message; } - public static String appendRequestIdToErrorObj(int status, String error, String requestId) throws SkyflowException { - if (requestId != null && !requestId.isEmpty()) { - JsonObject errorObject = (JsonObject) new JsonParser().parse(error); - JsonObject tempError = (JsonObject) errorObject.get("error"); - if (tempError != null) { - String message = String.valueOf(tempError.get("message")); - message = message + " - requestId: " + requestId; - - tempError.addProperty("message", message); - errorObject.add("error", tempError); - } - error = errorObject.toString(); - } - return error; - } - private static String makeFormEncodeKeyValuePair(String key, String value) { return key + "=" + value + "&"; } diff --git a/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java b/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java index a30a44c9..a2d44d99 100644 --- a/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java +++ b/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java @@ -2,22 +2,23 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; + +import java.util.HashMap; public class InvokeConnectionResponse { - private final JsonObject data; - private final JsonObject metadata; + private final Object data; + private final HashMap metadata; - public InvokeConnectionResponse(JsonObject data, JsonObject metadata) { + public InvokeConnectionResponse(Object data, HashMap metadata) { this.data = data; this.metadata = metadata; } - public JsonObject getData() { + public Object getData() { return data; } - public JsonObject getMetadata() { + public HashMap getMetadata() { return metadata; } diff --git a/src/main/java/com/skyflow/vault/controller/ConnectionController.java b/src/main/java/com/skyflow/vault/controller/ConnectionController.java index 0bb2251e..68a39751 100644 --- a/src/main/java/com/skyflow/vault/controller/ConnectionController.java +++ b/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -26,7 +26,7 @@ import java.util.HashMap; import java.util.Map; -public class ConnectionController extends ConnectionClient { +public final class ConnectionController extends ConnectionClient { public ConnectionController(ConnectionConfig connectionConfig, Credentials credentials) { super(connectionConfig, credentials); } @@ -65,8 +65,8 @@ public InvokeConnectionResponse invoke(InvokeConnectionRequest invokeConnectionR String response = HttpUtility.sendRequest(requestMethod.name(), new URL(filledURL), requestBody, headers); JsonObject data = JsonParser.parseString(response).getAsJsonObject(); - JsonObject metadata = new JsonObject(); - metadata.addProperty("requestId", HttpUtility.getRequestID()); + HashMap metadata = new HashMap<>(); + metadata.put("requestId", HttpUtility.getRequestID()); connectionResponse = new InvokeConnectionResponse(data, metadata); LogUtil.printInfoLog(InfoLogs.INVOKE_CONNECTION_REQUEST_RESOLVED.getLog()); } catch (IOException e) { diff --git a/src/test/java/com/skyflow/utils/HttpUtilityTests.java b/src/test/java/com/skyflow/utils/HttpUtilityTests.java index 816f1504..f7214690 100644 --- a/src/test/java/com/skyflow/utils/HttpUtilityTests.java +++ b/src/test/java/com/skyflow/utils/HttpUtilityTests.java @@ -43,7 +43,7 @@ public class HttpUtilityTests { @Before public void setup() throws IOException { expected = "{\"status\":\"success\"}"; - expectedError = "{\"status\":\"something went wrong\"}"; + expectedError = "{\"error\":{\"grpc_code\":123,\"http_code\":500,\"message\":\"something went wrong\",\"http_status\":\"internal server error\",\"details\":[]}}\n"; mockConnection = Mockito.mock(HttpURLConnection.class); given(mockConnection.getInputStream()).willReturn(new ByteArrayInputStream(expected.getBytes())); given(mockConnection.getErrorStream()).willReturn(new ByteArrayInputStream(expectedError.getBytes())); @@ -115,7 +115,11 @@ public void testSendRequestError() { given(mockConnection.getResponseCode()).willReturn(500); String response = httpUtility.sendRequest("GET", url, null, null); } catch (SkyflowException e) { - Assert.assertEquals(expectedError, e.getMessage()); + Assert.assertEquals(500, e.getHttpCode()); + Assert.assertEquals(new Integer(123), e.getGrpcCode()); + Assert.assertEquals("internal server error", e.getHttpStatus()); + Assert.assertEquals("something went wrong", e.getMessage()); + Assert.assertTrue(e.getDetails().isEmpty()); } catch (Exception e) { fail(INVALID_EXCEPTION_THROWN); } diff --git a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java index 90bc4c1e..a29a3335 100644 --- a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java +++ b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java @@ -423,12 +423,12 @@ public void testInvokeConnectionResponse() { JsonObject data = new JsonObject(); data.addProperty("test_key_1", "test_value_1"); data.addProperty("test_key_2", "test_value_2"); - JsonObject metadata = new JsonObject(); - metadata.addProperty("requestId", "12345"); + HashMap metadata = new HashMap<>(); + metadata.put("requestId", "12345"); InvokeConnectionResponse connectionResponse = new InvokeConnectionResponse(data, metadata); String responseString = "{\"data\":{\"test_key_1\":\"test_value_1\",\"test_key_2\":\"test_value_2\"}," + "\"metadata\":{\"requestId\":\"12345\"}}"; - Assert.assertEquals(2, connectionResponse.getData().size()); + Assert.assertNotNull(connectionResponse.getData()); Assert.assertEquals(responseString, connectionResponse.toString()); Assert.assertEquals(1, connectionResponse.getMetadata().size()); } catch (Exception e) { diff --git a/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java index ca2e85d9..66621003 100644 --- a/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java +++ b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java @@ -7,6 +7,7 @@ import com.skyflow.enums.LogLevel; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.HttpStatus; import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.ApiClient; import com.skyflow.generated.rest.api.TokensApi; @@ -155,8 +156,8 @@ public void testInvalidRequestInTokenizeMethod() { ); Assert.assertNull(e.getRequestId()); Assert.assertNull(e.getGrpcCode()); - Assert.assertNull(e.getHttpStatus()); - Assert.assertNull(e.getDetails()); + Assert.assertTrue(e.getDetails().isEmpty()); + Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); } } From c7ba710426851013e5171fe6bfd0b49a730b846d Mon Sep 17 00:00:00 2001 From: skyflow-shravan <121150537+skyflow-shravan@users.noreply.github.com> Date: Mon, 20 Jan 2025 15:29:39 +0530 Subject: [PATCH 097/126] SK-1820 refactor release pipeline (#157) --- .github/workflows/shared-build-and-deploy.yml | 28 +++++++++++++++---- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index 28b4d01f..89332762 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -61,6 +61,19 @@ jobs: server-password: SERVER_PASSWORD gpg-private-key: ${{ secrets.gpg-key }} # Value of the GPG private key to import gpg-passphrase: GPG_PASSPHRASE # env variable for GPG private key passphrase + + - name: Resolve Branch for the Tagged Commit + id: resolve-branch + if: ${{ inputs.tag == 'beta' || inputs.tag == 'public' }} + run: | + TAG_COMMIT=$(git rev-list -n 1 ${{ github.ref_name }}) + BRANCH_NAME=$(git branch -r --contains $TAG_COMMIT | grep -o 'origin/.*' | sed 's|origin/||' | head -n 1) + if [ -z "$BRANCH_NAME" ]; then + echo "Error: Could not resolve branch for the tag." + exit 1 + fi + echo "Resolved Branch Name: $BRANCH_NAME" + echo "branch_name=$BRANCH_NAME" >> $GITHUB_ENV - name: Get Previous tag id: previoustag @@ -78,22 +91,25 @@ jobs: fi - name: Commit changes - if: ${{ inputs.tag == 'internal' || inputs.tag == 'public' }} run: | git config user.name ${{ github.actor }} git config user.email ${{ github.actor }}@users.noreply.github.com + + if [[ "${{ inputs.tag }}" == "beta" || "${{ inputs.tag }}" == "public" ]]; then + git checkout ${{ env.branch_name }} + fi + git add pom.xml - if ${{ inputs.tag == 'internal' }}; then + if [[ "${{ inputs.tag }}" == "internal" ]]; then git commit -m "[AUTOMATED] Private Release ${{ steps.previoustag.outputs.tag }}-dev-$(git rev-parse --short $GITHUB_SHA)" git push origin ${{ github.ref_name }} -f fi - if ${{ inputs.tag == 'public' }}; then + if [[ "${{ inputs.tag }}" == "beta" || "${{ inputs.tag }}" == "public" ]]; then git commit -m "[AUTOMATED] Public Release - ${{ steps.previoustag.outputs.tag }}" - git push origin + git push origin ${{ env.branch_name }} fi - name: Create env - if: ${{ inputs.tag == 'internal' }} id: create-env run: | touch .env @@ -109,7 +125,7 @@ jobs: json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - name: Publish package - run: mvn clean deploy -P ${{ inputs.profile }} + run: mvn --batch-mode deploy -P ${{ inputs.profile }} env: SERVER_USERNAME: ${{ secrets.server-username }} SERVER_PASSWORD: ${{ secrets.server-password }} From 5ca3ba4292693f3b40b7560e5828f7200484fce5 Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow <156889717+saileshwar-skyflow@users.noreply.github.com> Date: Fri, 7 Feb 2025 12:53:57 +0530 Subject: [PATCH 098/126] SK-1863: Added a migration guide section in the README for transitioning from v1 to v2. (#158) * SK-1863: Added migration from v1 to v2 section in readme --- README.md | 246 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 246 insertions(+) diff --git a/README.md b/README.md index 9c873157..5ed7d604 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ The Skyflow Java SDK is designed to help with integrating Skyflow into a Java ba - [Service Account Bearer Token with Context Generation](#service-account-bearer-token-with-context-generation) - [Service Account Scoped Bearer Token Generation](#service-account-scoped-bearer-token-generation) - [Signed Data Tokens Generation](#signed-data-tokens-generation) + - [Migrate from v1 to v2](#migrate-from-v1-to-v2) - [Vault APIs](#vault-apis) - [Insert](#insert-data-into-the-vault) - [Detokenize](#detokenize) @@ -300,6 +301,251 @@ Notes: - Time to live value expects time as seconds. - The default time to live value is 60 seconds. +## Migrate from v1 to v2 + +Below are the steps to migrate the java sdk from v1 to v2. + +### 1. Authentication Options +In V2, we have introduced multiple authentication options. +You can now provide credentials in the following ways: + +- **API Key (Recommended)** +- **Passing credentials as ENV.** (`SKYFLOW_CREDENTIALS`) (**Recommended**) +- **Path to your credentials JSON file** +- **Stringified JSON of your credentials** +- **Bearer token** + +These options allow you to choose the authentication method that best suits your use case. + +### V1 (Old) +```java +static class DemoTokenProvider implements TokenProvider { + @Override + public String getBearerToken() throws Exception { + ResponseToken res = null; + try { + String filePath = ""; + res = Token.generateBearerToken(filePath); + } catch (SkyflowException e) { + e.printStackTrace(); + } + return res.getAccessToken(); + } +} +``` + +### V2 (New): Passing one of the following: +```java +// Option 1: API Key (Recommended) +Credentials skyflowCredentials = new Credentials(); +skyflowCredentials.setApiKey(""); // Replace with your actual API key + +// Option 2: Environment Variables (Recommended) +// Set SKYFLOW_CREDENTIALS in your environment + +// Option 3: Credentials File +skyflowCredentials.setPath(""); // Replace with the path to credentials file + +// Option 4: Stringified JSON +skyflowCredentials.setCredentialsString(""); // Replace with the credentials string + +// Option 5: Bearer Token +skyflowCredentials.setToken(""); // Replace with your actual authentication token. +``` + +**Notes:** +- Use only ONE authentication method. +- API Key or Environment Variables are recommended for production use. +- Secure storage of credentials is essential. +- For overriding behavior and priority order of credentials, refer to the README. + +--- + +### 2. Client Initialization +In V2, we have introduced a Builder design pattern for client initialization and added support for multi-vault. This allows you to configure multiple vaults during client initialization. + +In V2, the log level is tied to each individual client instance. + +During client initialization, you can pass the following parameters: +- `vaultId` and `clusterId`: These values are derived from the vault ID & vault URL. +- `env`: Specify the environment (e.g., SANDBOX or PROD). +- `credentials`: The necessary authentication credentials. + +### V1 (Old) +```java +// DemoTokenProvider class is an implementation of the TokenProvider interface +DemoTokenProvider demoTokenProvider = new DemoTokenProvider(); +SkyflowConfiguration skyflowConfig = new SkyflowConfiguration("","", demoTokenProvider); +Skyflow skyflowClient = Skyflow.init(skyflowConfig); +``` + +### V2 (New) +```java +Credentials credentials = new Credentials(); +credentials.setPath(""); // Replace with the path to the credentials file + +// Configure the first vault (Blitz) +VaultConfig config = new VaultConfig(); +config.setVaultId(""); // Replace with the ID of the first vault +config.setClusterId(""); // Replace with the cluster ID of the first vault +config.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) +config.setCredentials(credentials); // Associate the credentials with the vault + +// Set up credentials for the Skyflow client +Credentials skyflowCredentials = new Credentials(); +skyflowCredentials.setPath(""); // Replace with the path to another credentials file + +// Create a Skyflow client and add vault configurations +Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .addVaultConfig(config) // Add the first vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials + .build(); +``` + +**Key Changes:** +- `vaultUrl` replaced with `clusterId`. +- Added environment specification (`env`). +- Instance-specific log levels. + +--- + +### 3. Request & Response Structure +In V2, we have removed the use of JSON objects from a third-party package. Instead, we have transitioned to accepting native ArrayList and HashMap data structures and adopted the Builder pattern for request creation. This request need +- `table`: The name of the table. +- `values`: An array of objects containing the data to be inserted. +The response will be of type InsertResponse class, which contains insertedFields and errors. + +### V1 (Old) Request Building +```java +JSONObject recordsJson = new JSONObject(); +JSONArray recordsArrayJson = new JSONArray(); + +JSONObject recordJson = new JSONObject(); +recordJson.put("table", "cards"); + +JSONObject fieldsJson = new JSONObject(); +fields.put("cardNumber", "41111111111"); +fields.put("cvv", "123"); + +recordJson.put("fields", fieldsJson); +recordsArrayJson.add(record); +recordsJson.put("records", recordsArrayJson); +try { + JSONObject insertResponse = skyflowClient.insert(records); + System.out.println(insertResponse); +} catch (SkyflowException exception) { + System.out.println(exception); +} +``` + +### V2 (New) Request Building +```java +ArrayList> values = new ArrayList<>(); +HashMap value = new HashMap<>(); +value.put("", ""); // Replace with column name and value +value.put("", ""); // Replace with another column name and value +values.add(values); + +ArrayList> tokens = new ArrayList<>(); +HashMap token = new HashMap<>(); +token.put("", ""); // Replace with the token for COLUMN_NAME_2 +tokens.add(token); + +InsertRequest insertRequest = InsertRequest.builder() + .table("") // Replace with the table name + .continueOnError(true) // Continue inserting even if some records fail + .tokenMode(TokenMode.ENABLE) // Enable BYOT for token validation + .values(values) // Data to insert + .tokens(tokens) // Provide tokens for BYOT columns + .returnTokens(true) // Return tokens along with the response + .build(); +``` + +### V1 (Old) Response Structure +```json +{ + "records": [ + { + "table": "cards", + "fields": { + "skyflow_id": "16419435-aa63-4823-aae7-19c6a2d6a19f", + "cardNumber": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", + "cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5" + } + } + ] +} +``` + +### V2 (New) Response Structure +```json +{ + "insertedFields": [ + { + "card_number": "5484-7829-1702-9110", + "request_index": "0", + "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", + "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b" + } + ], + "errors": [] +} +``` + +--- + +## 4. Request Options +In V2, with the introduction of the Builder design pattern has made handling optional fields in Java more efficient and straightforward. + + +### V1 (Old) +```java +InsertOptions insertOptions = new InsertOptions(true); +``` + +### V2 (New) +```java +InsertRequest upsertRequest = new InsertRequest.builder() + .table("") // Replace with the table name + .continueOnError(false) // Stop inserting if any record fails + .tokenMode(TokenMode.DISABLE) // Disable BYOT + .values(values) // Data to insert + .returnTokens(false) // Do not return tokens + .upsert("") // Replace with the column name used for upsert logic + .build(); +``` + +--- + +## 5. Enhanced Error Details +The V2 error response includes: + +- `httpStatus`: The HTTP status code. +- `grpcCode`: The gRPC code associated with the error. +- `details` & `message`: A detailed description of the error. +- `requestId`: A unique request identifier for easier debugging. + +### V1 (Old) Error Structure +```json +{ + "code": "", + "description": "" +} +``` + +### V2 (New) Error Structure +```json +{ + "httpStatus": "", + "grpcCode": "", + "httpCode": "", + "message": "", + "requestId": "", + "details": [ "

" ] +} +``` + ## Vault APIs The [Vault](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault) module is used to From 012d58c92beef833b0e193cb328d7db6d572c208 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 13 Feb 2025 14:30:59 +0530 Subject: [PATCH 099/126] SK-1875 Add separate redaction types for tokens in Detokenize --- src/main/java/com/skyflow/VaultClient.java | 8 ++- .../utils/validations/Validations.java | 11 ++-- .../skyflow/vault/tokens/DetokenizeData.java | 26 +++++++++ .../vault/tokens/DetokenizeRequest.java | 32 +++++------ .../java/com/skyflow/VaultClientTests.java | 15 +++-- .../skyflow/vault/tokens/DetokenizeTests.java | 57 +++++++++++-------- 6 files changed, 95 insertions(+), 54 deletions(-) create mode 100644 src/main/java/com/skyflow/vault/tokens/DetokenizeData.java diff --git a/src/main/java/com/skyflow/VaultClient.java b/src/main/java/com/skyflow/VaultClient.java index f3e29fb2..eb1cc3fa 100644 --- a/src/main/java/com/skyflow/VaultClient.java +++ b/src/main/java/com/skyflow/VaultClient.java @@ -20,6 +20,7 @@ import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.UpdateRequest; import com.skyflow.vault.tokens.ColumnValue; +import com.skyflow.vault.tokens.DetokenizeData; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; import io.github.cdimascio.dotenv.Dotenv; @@ -85,10 +86,11 @@ protected void updateVaultConfig() throws SkyflowException { protected V1DetokenizePayload getDetokenizePayload(DetokenizeRequest request) { V1DetokenizePayload payload = new V1DetokenizePayload(); payload.setContinueOnError(request.getContinueOnError()); - for (String token : request.getTokens()) { + payload.setDownloadURL(request.getDownloadURL()); + for (DetokenizeData detokenizeDataRecord : request.getDetokenizeData()) { V1DetokenizeRecordRequest recordRequest = new V1DetokenizeRecordRequest(); - recordRequest.setToken(token); - recordRequest.setRedaction(request.getRedactionType().getRedaction()); + recordRequest.setToken(detokenizeDataRecord.getToken()); + recordRequest.setRedaction(detokenizeDataRecord.getRedactionType().getRedaction()); payload.addDetokenizationParametersItem(recordRequest); } return payload; diff --git a/src/main/java/com/skyflow/utils/validations/Validations.java b/src/main/java/com/skyflow/utils/validations/Validations.java index 2876c15d..8b7b6fef 100644 --- a/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/src/main/java/com/skyflow/utils/validations/Validations.java @@ -18,6 +18,7 @@ import com.skyflow.vault.connection.InvokeConnectionRequest; import com.skyflow.vault.data.*; import com.skyflow.vault.tokens.ColumnValue; +import com.skyflow.vault.tokens.DetokenizeData; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; @@ -212,20 +213,20 @@ public static void validateCredentials(Credentials credentials) throws SkyflowEx } public static void validateDetokenizeRequest(DetokenizeRequest detokenizeRequest) throws SkyflowException { - ArrayList tokens = detokenizeRequest.getTokens(); - if (tokens == null) { + ArrayList detokenizeData = detokenizeRequest.getDetokenizeData(); + if (detokenizeData == null) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.TOKENS_REQUIRED.getLog(), InterfaceName.DETOKENIZE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidDataTokens.getMessage()); - } else if (tokens.isEmpty()) { + } else if (detokenizeData.isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_TOKENS.getLog(), InterfaceName.DETOKENIZE.getName() )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyDataTokens.getMessage()); } else { - for (int index = 0; index < tokens.size(); index++) { - String token = tokens.get(index); + for (int index = 0; index < detokenizeData.size(); index++) { + String token = detokenizeData.get(index).getToken(); if (token == null || token.trim().isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( ErrorLogs.EMPTY_OR_NULL_TOKEN_IN_TOKENS.getLog(), diff --git a/src/main/java/com/skyflow/vault/tokens/DetokenizeData.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeData.java new file mode 100644 index 00000000..33bba2b9 --- /dev/null +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeData.java @@ -0,0 +1,26 @@ +package com.skyflow.vault.tokens; + +import com.skyflow.enums.RedactionType; + +public class DetokenizeData { + private final String token; + private final RedactionType redactionType; + + public DetokenizeData(String token) { + this.token = token; + this.redactionType = RedactionType.PLAIN_TEXT; + } + + public DetokenizeData(String token, RedactionType redactionType) { + this.token = token; + this.redactionType = redactionType == null ? RedactionType.PLAIN_TEXT : redactionType; + } + + public String getToken() { + return this.token; + } + + public RedactionType getRedactionType() { + return this.redactionType; + } +} diff --git a/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java index d5b8f072..186a18d2 100644 --- a/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java @@ -1,7 +1,5 @@ package com.skyflow.vault.tokens; -import com.skyflow.enums.RedactionType; - import java.util.ArrayList; public class DetokenizeRequest { @@ -15,40 +13,40 @@ public static DetokenizeRequestBuilder builder() { return new DetokenizeRequestBuilder(); } - public ArrayList getTokens() { - return this.builder.tokens; - } - - public RedactionType getRedactionType() { - return this.builder.redactionType; + public ArrayList getDetokenizeData() { + return this.builder.detokenizeData; } public Boolean getContinueOnError() { return this.builder.continueOnError; } + public Boolean getDownloadURL() { + return this.builder.downloadURL; + } + public static final class DetokenizeRequestBuilder { - private ArrayList tokens; - private RedactionType redactionType; + private ArrayList detokenizeData; private Boolean continueOnError; + private Boolean downloadURL; private DetokenizeRequestBuilder() { - this.redactionType = RedactionType.PLAIN_TEXT; this.continueOnError = false; + this.downloadURL = false; } - public DetokenizeRequestBuilder tokens(ArrayList tokens) { - this.tokens = tokens; + public DetokenizeRequestBuilder detokenizeData(ArrayList detokenizeData) { + this.detokenizeData = detokenizeData; return this; } - public DetokenizeRequestBuilder redactionType(RedactionType redactionType) { - this.redactionType = redactionType == null ? RedactionType.PLAIN_TEXT : redactionType; + public DetokenizeRequestBuilder continueOnError(Boolean continueOnError) { + this.continueOnError = continueOnError != null && continueOnError; return this; } - public DetokenizeRequestBuilder continueOnError(Boolean continueOnError) { - this.continueOnError = continueOnError != null && continueOnError; + public DetokenizeRequestBuilder downloadURL(Boolean downloadURL) { + this.downloadURL = downloadURL; return this; } diff --git a/src/test/java/com/skyflow/VaultClientTests.java b/src/test/java/com/skyflow/VaultClientTests.java index 8a02caaf..0cd99614 100644 --- a/src/test/java/com/skyflow/VaultClientTests.java +++ b/src/test/java/com/skyflow/VaultClientTests.java @@ -9,6 +9,7 @@ import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.UpdateRequest; import com.skyflow.vault.tokens.ColumnValue; +import com.skyflow.vault.tokens.DetokenizeData; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; import io.github.cdimascio.dotenv.Dotenv; @@ -31,7 +32,7 @@ public class VaultClientTests { private static String value = null; private static String columnGroup = null; private static String apiKey = null; - private static ArrayList tokens = null; + private static ArrayList detokenizeData = null; private static ArrayList> insertValues = null; private static ArrayList> insertTokens = null; private static HashMap valueMap = null; @@ -43,7 +44,7 @@ public static void setup() { vaultID = "vault123"; clusterID = "cluster123"; token = "test_token"; - tokens = new ArrayList<>(); + detokenizeData = new ArrayList<>(); table = "test_table"; value = "test_value"; columnGroup = "test_column_group"; @@ -115,11 +116,15 @@ public void testVaultClientGetVaultConfig() { @Test public void testGetDetokenizePayload() { try { - tokens.add(token); - tokens.add(token); - DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder().tokens(tokens).build(); + DetokenizeData detokenizeDataRecord1 = new DetokenizeData(token); + DetokenizeData detokenizeDataRecord2 = new DetokenizeData(token); + detokenizeData.add(detokenizeDataRecord1); + detokenizeData.add(detokenizeDataRecord2); + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .detokenizeData(detokenizeData).downloadURL(true).build(); V1DetokenizePayload payload = vaultClient.getDetokenizePayload(detokenizeRequest); Assert.assertFalse(payload.getContinueOnError()); + Assert.assertTrue(payload.getDownloadURL()); Assert.assertEquals(2, payload.getDetokenizationParameters().size()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); diff --git a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index 3577f7db..722a6c59 100644 --- a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -19,30 +19,33 @@ public class DetokenizeTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; - private static String token = null; - private static ArrayList tokens = null; + private static ArrayList detokenizeData = null; + private static DetokenizeData maskedRedactionRecord = null; + private static DetokenizeData plainRedactionRecord = null; @BeforeClass public static void setup() throws SkyflowException, NoSuchMethodException { - tokens = new ArrayList<>(); - token = "test_token_1"; + detokenizeData = new ArrayList<>(); + maskedRedactionRecord = new DetokenizeData("test_token_1", RedactionType.MASKED); + plainRedactionRecord = new DetokenizeData("test_token_2"); } @Before public void setupTest() { - tokens.clear(); + detokenizeData.clear(); } @Test public void testValidInputInDetokenizeRequestValidations() { try { - tokens.add(token); - DetokenizeRequest request = DetokenizeRequest.builder(). - tokens(tokens).redactionType(RedactionType.MASKED).continueOnError(false).build(); + detokenizeData.add(maskedRedactionRecord); + DetokenizeRequest request = DetokenizeRequest.builder() + .detokenizeData(detokenizeData).continueOnError(false).downloadURL(true).build(); Validations.validateDetokenizeRequest(request); - Assert.assertEquals(1, tokens.size()); - Assert.assertEquals(RedactionType.MASKED.toString(), request.getRedactionType().toString()); + Assert.assertEquals(1, request.getDetokenizeData().size()); + Assert.assertEquals(RedactionType.MASKED.toString(), request.getDetokenizeData().get(0).getRedactionType().toString()); Assert.assertFalse(request.getContinueOnError()); + Assert.assertTrue(request.getDownloadURL()); } catch (SkyflowException e) { Assert.fail(INVALID_EXCEPTION_THROWN); } @@ -60,14 +63,14 @@ public void testNoTokensInDetokenizeRequestValidations() { Utils.parameterizedString(ErrorMessage.InvalidDataTokens.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); - Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); Assert.assertFalse(request.getContinueOnError()); + Assert.assertFalse(request.getDownloadURL()); } } @Test public void testEmptyTokensInDetokenizeRequestValidations() { - DetokenizeRequest request = DetokenizeRequest.builder().tokens(tokens).build(); + DetokenizeRequest request = DetokenizeRequest.builder().detokenizeData(detokenizeData).build(); try { Validations.validateDetokenizeRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); @@ -77,16 +80,18 @@ public void testEmptyTokensInDetokenizeRequestValidations() { Utils.parameterizedString(ErrorMessage.EmptyDataTokens.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); - Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); Assert.assertFalse(request.getContinueOnError()); + Assert.assertFalse(request.getDownloadURL()); } } @Test public void testEmptyTokenInTokensInDetokenizeRequestValidations() { - tokens.add(token); - tokens.add(""); - DetokenizeRequest request = DetokenizeRequest.builder().tokens(tokens).build(); + DetokenizeData detokenizeDataRecord = new DetokenizeData(""); + detokenizeData.add(maskedRedactionRecord); + detokenizeData.add(detokenizeDataRecord); + + DetokenizeRequest request = DetokenizeRequest.builder().detokenizeData(detokenizeData).build(); try { Validations.validateDetokenizeRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); @@ -96,16 +101,18 @@ public void testEmptyTokenInTokensInDetokenizeRequestValidations() { Utils.parameterizedString(ErrorMessage.EmptyTokenInDataTokens.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); - Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); Assert.assertFalse(request.getContinueOnError()); + Assert.assertFalse(request.getDownloadURL()); } } @Test public void testNullTokenInTokensInDetokenizeRequestValidations() { - tokens.add(token); - tokens.add(null); - DetokenizeRequest request = DetokenizeRequest.builder().tokens(tokens).build(); + DetokenizeData detokenizeDataRecord = new DetokenizeData(null); + detokenizeData.add(maskedRedactionRecord); + detokenizeData.add(detokenizeDataRecord); + + DetokenizeRequest request = DetokenizeRequest.builder().detokenizeData(detokenizeData).build(); try { Validations.validateDetokenizeRequest(request); Assert.fail(EXCEPTION_NOT_THROWN); @@ -115,20 +122,22 @@ public void testNullTokenInTokensInDetokenizeRequestValidations() { Utils.parameterizedString(ErrorMessage.EmptyTokenInDataTokens.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); - Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); Assert.assertFalse(request.getContinueOnError()); + Assert.assertFalse(request.getDownloadURL()); } } @Test public void testRedactionAndContinueOnErrorInDetokenizeRequestValidations() { - tokens.add(token); + detokenizeData.add(plainRedactionRecord); + DetokenizeRequest request = DetokenizeRequest.builder(). - tokens(tokens).redactionType(null).continueOnError(null).build(); + detokenizeData(detokenizeData).continueOnError(null).build(); try { Validations.validateDetokenizeRequest(request); - Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getRedactionType()); + Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getDetokenizeData().get(0).getRedactionType()); Assert.assertFalse(request.getContinueOnError()); + Assert.assertFalse(request.getDownloadURL()); } catch (SkyflowException e) { Assert.fail(INVALID_EXCEPTION_THROWN); } From fe43c66cf784521092079d00ed3fe803ac61c729 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 13 Feb 2025 16:58:42 +0530 Subject: [PATCH 100/126] SK-1875 Add separate redaction types for tokens in Detokenize - Update error messages and logs according to changes - Update detokenize sample to work with new changes --- .../com/example/vault/DetokenizeExample.java | 27 +++++++++++-------- .../java/com/skyflow/errors/ErrorMessage.java | 6 ++--- src/main/java/com/skyflow/logs/ErrorLogs.java | 5 ++-- .../utils/validations/Validations.java | 12 ++++----- .../controller/VaultControllerTests.java | 2 +- .../skyflow/vault/tokens/DetokenizeTests.java | 12 ++++----- 6 files changed, 35 insertions(+), 29 deletions(-) diff --git a/samples/src/main/java/com/example/vault/DetokenizeExample.java b/samples/src/main/java/com/example/vault/DetokenizeExample.java index f25d2be0..78f102a3 100644 --- a/samples/src/main/java/com/example/vault/DetokenizeExample.java +++ b/samples/src/main/java/com/example/vault/DetokenizeExample.java @@ -7,6 +7,7 @@ import com.skyflow.enums.LogLevel; import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.DetokenizeData; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.DetokenizeResponse; @@ -52,13 +53,15 @@ public static void main(String[] args) throws SkyflowException { // Example 1: Detokenize tokens from the first vault try { - ArrayList tokens1 = new ArrayList<>(); - tokens1.add(""); // Replace with the first token to detokenize - tokens1.add(""); // Replace with the second token to detokenize + ArrayList detokenizeData1 = new ArrayList<>(); + DetokenizeData detokenizeDataRecord1 = new DetokenizeData("", RedactionType.MASKED); // Replace with a token to detokenize with MASKED redaction + DetokenizeData detokenizeDataRecord2 = new DetokenizeData(""); // Replace with another token to detokenize with PLAIN_TEXT redaction + detokenizeData1.add(detokenizeDataRecord1); + detokenizeData1.add(detokenizeDataRecord2); DetokenizeRequest detokenizeRequest1 = DetokenizeRequest.builder() - .tokens(tokens1) // Specify the tokens to detokenize - .continueOnError(true) // Continue processing even if an error occurs for some tokens + .detokenizeData(detokenizeData1) // Specify the tokens to detokenize with specified redaction types + .continueOnError(true) // Continue processing even if an error occurs for some tokens .build(); DetokenizeResponse detokenizeResponse1 = skyflowClient.vault().detokenize(detokenizeRequest1); // Perform detokenization @@ -70,14 +73,16 @@ public static void main(String[] args) throws SkyflowException { // Example 2: Detokenize tokens from the second vault try { - ArrayList tokens2 = new ArrayList<>(); - tokens2.add(""); // Replace with the first token to detokenize - tokens2.add(""); // Replace with the second token to detokenize + ArrayList detokenizeData2 = new ArrayList<>(); + DetokenizeData detokenizeDataRecord3 = new DetokenizeData("", RedactionType.DEFAULT); // Replace with a token to detokenize + DetokenizeData detokenizeDataRecord4 = new DetokenizeData(""); // Replace with another token to detokenize + detokenizeData2.add(detokenizeDataRecord3); + detokenizeData2.add(detokenizeDataRecord4); DetokenizeRequest detokenizeRequest2 = DetokenizeRequest.builder() - .tokens(tokens2) // Specify the tokens to detokenize - .continueOnError(false) // Stop processing on the first error - .redactionType(RedactionType.DEFAULT) // Use the default redaction type for detokenization + .detokenizeData(detokenizeData2) // Specify the tokens to detokenize with specified redaction types + .continueOnError(false) // Stop processing on the first error + .downloadURL(true) // Specify whether to return URLs for file data type .build(); DetokenizeResponse detokenizeResponse2 = skyflowClient.vault("").detokenize(detokenizeRequest2); // Perform detokenization diff --git a/src/main/java/com/skyflow/errors/ErrorMessage.java b/src/main/java/com/skyflow/errors/ErrorMessage.java index d6af06aa..da992da2 100644 --- a/src/main/java/com/skyflow/errors/ErrorMessage.java +++ b/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -73,9 +73,9 @@ public enum ErrorMessage { BatchInsertFailure("%s0 Insert operation failed."), // detokenize - InvalidDataTokens("%s0 Validation error. Invalid data tokens. Specify valid data tokens."), - EmptyDataTokens("%s0 Validation error. Invalid data tokens. Specify at least one data token."), - EmptyTokenInDataTokens("%s0 Validation error. Invalid data tokens. Specify a valid data token."), + InvalidDetokenizeData("%s0 Validation error. Invalid detokenize data. Specify valid detokenize data."), + EmptyDetokenizeData("%s0 Validation error. Invalid data tokens. Specify at least one data token."), + EmptyTokenInDetokenizeData("%s0 Validation error. Invalid data tokens. Specify a valid data token."), // get interface IdsKeyError("%s0 Validation error. 'ids' key is missing from the payload. Specify an 'ids' key."), diff --git a/src/main/java/com/skyflow/logs/ErrorLogs.java b/src/main/java/com/skyflow/logs/ErrorLogs.java index 64e40c82..ad588aa0 100644 --- a/src/main/java/com/skyflow/logs/ErrorLogs.java +++ b/src/main/java/com/skyflow/logs/ErrorLogs.java @@ -61,8 +61,9 @@ public enum ErrorLogs { INSUFFICIENT_TOKENS_PASSED_FOR_TOKEN_MODE_ENABLE_STRICT("Invalid %s1 request. For tokenMode as ENABLE_STRICT, tokens should be passed for all fields."), MISMATCH_OF_FIELDS_AND_TOKENS("Invalid %s1 request. Keys for values and tokens are not matching."), INSERT_RECORDS_REJECTED("Insert request resulted in failure."), - TOKENS_REQUIRED("Invalid %s1 request. Tokens are required."), - EMPTY_OR_NULL_TOKEN_IN_TOKENS("Invalid %s1 request. Token can not be null or empty in tokens at index %s2."), + DETOKENIZE_DATA_REQUIRED("Invalid %s1 request. Detokenize data is required."), + EMPTY_DETOKENIZE_DATA("Invalid %s1 request. Detokenize data can not be empty."), + EMPTY_OR_NULL_TOKEN_IN_DETOKENIZE_DATA("Invalid %s1 request. Token can not be null or empty in detokenize data at index %s2."), REDACTION_IS_REQUIRED("Invalid %s1 request. Redaction is required."), DETOKENIZE_REQUEST_REJECTED("Detokenize request resulted in failure."), IDS_IS_REQUIRED("Invalid %s1 request. Ids are required."), diff --git a/src/main/java/com/skyflow/utils/validations/Validations.java b/src/main/java/com/skyflow/utils/validations/Validations.java index 8b7b6fef..5e192349 100644 --- a/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/src/main/java/com/skyflow/utils/validations/Validations.java @@ -216,23 +216,23 @@ public static void validateDetokenizeRequest(DetokenizeRequest detokenizeRequest ArrayList detokenizeData = detokenizeRequest.getDetokenizeData(); if (detokenizeData == null) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.TOKENS_REQUIRED.getLog(), InterfaceName.DETOKENIZE.getName() + ErrorLogs.DETOKENIZE_DATA_REQUIRED.getLog(), InterfaceName.DETOKENIZE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidDataTokens.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidDetokenizeData.getMessage()); } else if (detokenizeData.isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.EMPTY_TOKENS.getLog(), InterfaceName.DETOKENIZE.getName() + ErrorLogs.EMPTY_DETOKENIZE_DATA.getLog(), InterfaceName.DETOKENIZE.getName() )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyDataTokens.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyDetokenizeData.getMessage()); } else { for (int index = 0; index < detokenizeData.size(); index++) { String token = detokenizeData.get(index).getToken(); if (token == null || token.trim().isEmpty()) { LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.EMPTY_OR_NULL_TOKEN_IN_TOKENS.getLog(), + ErrorLogs.EMPTY_OR_NULL_TOKEN_IN_DETOKENIZE_DATA.getLog(), InterfaceName.DETOKENIZE.getName(), Integer.toString(index) )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTokenInDataTokens.getMessage()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTokenInDetokenizeData.getMessage()); } } } diff --git a/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java index 66621003..6084e9c3 100644 --- a/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java +++ b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java @@ -71,7 +71,7 @@ public void testInvalidRequestInDetokenizeMethod() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.InvalidDataTokens.getMessage(), Constants.SDK_PREFIX), + Utils.parameterizedString(ErrorMessage.InvalidDetokenizeData.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); } diff --git a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index 722a6c59..aea06095 100644 --- a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -60,7 +60,7 @@ public void testNoTokensInDetokenizeRequestValidations() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.InvalidDataTokens.getMessage(), Constants.SDK_PREFIX), + Utils.parameterizedString(ErrorMessage.InvalidDetokenizeData.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); Assert.assertFalse(request.getContinueOnError()); @@ -77,7 +77,7 @@ public void testEmptyTokensInDetokenizeRequestValidations() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.EmptyDataTokens.getMessage(), Constants.SDK_PREFIX), + Utils.parameterizedString(ErrorMessage.EmptyDetokenizeData.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); Assert.assertFalse(request.getContinueOnError()); @@ -86,7 +86,7 @@ public void testEmptyTokensInDetokenizeRequestValidations() { } @Test - public void testEmptyTokenInTokensInDetokenizeRequestValidations() { + public void testEmptyTokenInDetokenizeRequestValidations() { DetokenizeData detokenizeDataRecord = new DetokenizeData(""); detokenizeData.add(maskedRedactionRecord); detokenizeData.add(detokenizeDataRecord); @@ -98,7 +98,7 @@ public void testEmptyTokenInTokensInDetokenizeRequestValidations() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.EmptyTokenInDataTokens.getMessage(), Constants.SDK_PREFIX), + Utils.parameterizedString(ErrorMessage.EmptyTokenInDetokenizeData.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); Assert.assertFalse(request.getContinueOnError()); @@ -107,7 +107,7 @@ public void testEmptyTokenInTokensInDetokenizeRequestValidations() { } @Test - public void testNullTokenInTokensInDetokenizeRequestValidations() { + public void testNullTokenInDetokenizeRequestValidations() { DetokenizeData detokenizeDataRecord = new DetokenizeData(null); detokenizeData.add(maskedRedactionRecord); detokenizeData.add(detokenizeDataRecord); @@ -119,7 +119,7 @@ public void testNullTokenInTokensInDetokenizeRequestValidations() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.EmptyTokenInDataTokens.getMessage(), Constants.SDK_PREFIX), + Utils.parameterizedString(ErrorMessage.EmptyTokenInDetokenizeData.getMessage(), Constants.SDK_PREFIX), e.getMessage() ); Assert.assertFalse(request.getContinueOnError()); From 6f64d7a957746101fe79052c95c677884b7e766e Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 14 Feb 2025 19:53:20 +0530 Subject: [PATCH 101/126] SK-1893 Update README for v2 --- README.md | 2101 ++++++++++++++++++++++++++++++++++------------------- 1 file changed, 1343 insertions(+), 758 deletions(-) diff --git a/README.md b/README.md index 5ed7d604..1f6563b9 100644 --- a/README.md +++ b/README.md @@ -8,63 +8,74 @@ The Skyflow Java SDK is designed to help with integrating Skyflow into a Java ba # Table of Contents -- [Skyflow Java](#skyflow-java) - [Table of Contents](#table-of-contents) - - [Features](#features) - - [Installation](#installation) - - [Requirements](#requirements) - - [Configuration](#configuration) - - [Gradle users](#gradle-users) - - [Maven users](#maven-users) - - [Service Account Bearer Token Generation](#service-account-bearer-token-generation) - - [Service Account Bearer Token with Context Generation](#service-account-bearer-token-with-context-generation) - - [Service Account Scoped Bearer Token Generation](#service-account-scoped-bearer-token-generation) - - [Signed Data Tokens Generation](#signed-data-tokens-generation) - - [Migrate from v1 to v2](#migrate-from-v1-to-v2) - - [Vault APIs](#vault-apis) - - [Insert](#insert-data-into-the-vault) - - [Detokenize](#detokenize) - - [Get](#get) - - [Use Skyflow IDs](#get-by-skyflow-ids) - - [Use column name and values](#get-by-column-name-and-column-values) - - [Redaction types](#redaction-types) - - [Update](#update) - - [Delete](#delete) - - [Query](#query) - - [Connections](#connections) - - [Invoke Connection](#invoke-connection) - - [Logging](#logging) - - [Reporting a Vulnerability](#reporting-a-vulnerability) - -## Features - -- Authentication with a Skyflow Service Account and generation of a bearer token -- Vault API operations to insert, retrieve and tokenize sensitive data -- Invoking connections to call downstream third party APIs without directly handling sensitive data - -## Installation - -### Requirements - -- Java 1.8 and above - -### Configuration +- [Overview](#overview) +- [Install](#install) + - [Requirements](#requirements) + - [Configuration](#configuration) + - [Gradle users](#gradle-users) + - [Maven users](#maven-users) +- [Migration from v1 to v2](#migration-from-v1-to-v2) + - [Authentication options](#authentication-options) + - [Initializing the client](#initializing-the-client) + - [Request & response structure](#request--response-structure) + - [Request options](#request-options) + - [Error structure](#error-structure) +- [Quickstart](#quickstart) + - [Authenticate](#authenticate) + - [Initialize the client](#initialize-the-client) + - [Insert data into the vault](#insert-data-into-the-vault) +- [Vault](#vault) + - [Insert data into the vault](#insert-data-into-the-vault-1) + - [Detokenize](#detokenize) + - [Tokenize](#tokenize) + - [Get](#get) + - [Get by skyflow IDS](#get-by-skyflow-ids) + - [Get tokens](#get-tokens) + - [Get by column name and column values](#get-by-column-name-and-column-values) + - [Redaction types](#redaction-types) + - [Update](#update) + - [Delete](#delete) + - [Query](#query) +- [Connections](#connections) + - [Invoke a connection](#invoke-a-connection) +- [Authenticate with bearer tokens](#authenticate-with-bearer-tokens) + - [Generate a bearer token](#generate-a-bearer-token) + - [Generate bearer tokens with context](#generate-bearer-tokens-with-context) + - [Generate scoped bearer tokens](#generate-scoped-bearer-tokens) + - [Generate signed data tokens](#generate-signed-data-tokens) +- [Logging](#logging) +- [Reporting a Vulnerability](#reporting-a-vulnerability) + +# Overview + +- Authenticate using a Skyflow service account and generate bearer tokens for secure access. +- Perform Vault API operations such as inserting, retrieving, and tokenizing sensitive data with ease. +- Invoke connections to third-party APIs without directly handling sensitive data, ensuring compliance and data protection. + +# Install + +## Requirements + +- Java 8 and above (tested with Java 8) + +## Configuration + --- -#### Gradle users +### Gradle users -Add this dependency to your project's build file: +Add this dependency to your project's `build.gradle` file: ``` implementation 'com.skyflow:skyflow-java:2.0.0' ``` -#### Maven users +### Maven users -Add this dependency to your project's POM: +Add this dependency to your project's `pom.xml` file: ```xml - com.skyflow skyflow-java @@ -74,250 +85,24 @@ Add this dependency to your project's POM: --- -## Service Account Bearer Token Generation - -The [Service Account](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/serviceaccount/util) -java module is used to generate service account tokens from service account credentials file which is downloaded upon -creation of service account. The token generated from this module is valid for 60 minutes and can be used to make API -calls to vault services as well as management API(s) based on the permissions of the service account. - -The `BearerToken` utility class allows to generate bearer token with the help of credentials json file. Alternatively, -you can also send the entire credentials as a string. - -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java -): - -```java -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.BearerToken; -import com.skyflow.serviceaccount.util.Token; - -import java.io.File; - -public class BearerTokenGenerationExample { - public static void main(String[] args) { - String token = null; - // Generate BearerToken by specifying credentials.json file path - try { - String filePath = ""; - if (Token.isExpired(token)) { - BearerToken bearerToken = BearerToken.builder().setCredentials(new File(filePath)).build(); - token = bearerToken.getBearerToken(); - } - System.out.println(token); - } catch (SkyflowException e) { - e.printStackTrace(); - } - - // Generate BearerToken by specifying credentials.json as string - try { - String fileContents = ""; - if (Token.isExpired(token)) { - BearerToken bearerToken = BearerToken.builder().setCredentials(fileContents).build(); - token = bearerToken.getBearerToken(); - } - System.out.println(token); - } catch (SkyflowException e) { - e.printStackTrace(); - } - } -} -``` - -## Service Account Bearer Token with Context Generation - -Context-Aware Authorization enables you to embed context values into a Bearer token when you generate it, and reference -those values in your policies for more dynamic access control of data in the vault or validating signed data tokens -during detokenization. It can be used to track end user identity when making API calls using service accounts. - -The service account generated with `context_id` identifier enabled can be used to generate bearer tokens with `context`, -which is a `jwt` claim for a skyflow generated bearer token. The token generated from this service account will have a -`context_identifier` claim and is valid for 60 minutes and can be used to make API calls to vault services as well as -management API(s) based on the permissions of the service account. - -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java): - -``` java -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.BearerToken; - -import java.io.File; - -public class BearerTokenGenerationWithContextExample { - public static void main(String[] args) { - String bearerToken = null; - // Generate BearerToken with context by specifying credentials.json file path - try { - String filePath = ""; - BearerToken token = BearerToken.builder() - .setCredentials(new File(filePath)) - .setCtx("abc") - .build(); - - bearerToken = token.getBearerToken(); - System.out.println(bearerToken); - } catch (SkyflowException e) { - e.printStackTrace(); - } - - // Generate BearerToken with context by specifying credentials.json as string - try { - String fileContents = ""; - BearerToken token = BearerToken.builder() - .setCredentials(fileContents) - .setCtx("abc") - .build(); - - bearerToken = token.getBearerToken(); - System.out.println(bearerToken); - } catch (SkyflowException e) { - e.printStackTrace(); - } - } -} -``` - -## Service Account Scoped Bearer Token Generation - -A service account that has multiple roles can generate bearer tokens with access restricted to a specific role by -providing the appropriate `roleID`. Generated bearer tokens are valid for 60 minutes and can only perform operations -with the permissions associated with the specified role. - -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java): - -```java -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.BearerToken; - -import java.io.File; -import java.util.ArrayList; - -public class ScopedTokenGenerationExample { - public static void main(String[] args) { - String scopedToken = null; - // Generate Scoped Token by specifying credentials.json file path - try { - ArrayList roles = new ArrayList<>(); - roles.add("ROLE_ID"); - String filePath = ""; - BearerToken bearerToken = BearerToken.builder() - .setCredentials(new File(filePath)) - .setRoles(roles) - .build(); - - scopedToken = bearerToken.getBearerToken(); - System.out.println(scopedToken); - } catch (SkyflowException e) { - e.printStackTrace(); - } - } -} -``` - -Notes: - -- You can pass either a service account key credentials file path or a service account key credentials as string to the - `setCredentials` method of the BearerTokenBuilder class. -- If you pass both a file path and string to the `setCredentials` method, the last method used takes precedence. -- To generate multiple bearer tokens using a thread, see - this [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java) - -## Signed Data Tokens Generation - -Skyflow generates data tokens when sensitive data is inserted into the vault. These data tokens can be digitally signed -with the private key of the service account credentials, which adds an additional layer of protection. Signed tokens can -be detokenized by passing the signed data token and a bearer token generated from service account credentials. The -service account must have appropriate permissions and context to detokenize the signed data tokens. - -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java): - -``` java -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.SignedDataTokenResponse; -import com.skyflow.serviceaccount.util.SignedDataTokens; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -public class SignedTokenGenerationExample { - public static void main(String[] args) { - List signedTokenValues; - // Generate Signed data token with context by specifying credentials.json file path - try { - String filePath = ""; - String context = "abc"; - ArrayList dataTokens = new ArrayList<>(); - dataTokens.add("YOUR_DATA_TOKEN_1"); - SignedDataTokens signedToken = SignedDataTokens.builder() - .setCredentials(new File(filePath)) - .setCtx(context) - .setTimeToLive(30) // in seconds - .setDataTokens(dataTokens) - .build(); - signedTokenValues = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValues); - } catch (SkyflowException e) { - e.printStackTrace(); - } - - // Generate Signed data token with context by specifying credentials.json as string - try { - String fileContents = ""; - String context = "abc"; - ArrayList dataTokens = new ArrayList<>(); - dataTokens.add("YOUR_DATA_TOKEN_1"); - SignedDataTokens signedToken = SignedDataTokens.builder() - .setCredentials(fileContents) - .setCtx(context) - .setTimeToLive(30) // in seconds - .setDataTokens(dataTokens) - .build(); - signedTokenValues = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValues); - } catch (SkyflowException e) { - e.printStackTrace(); - } - } -} -``` - -Response: - -``` java -[ - { - "dataToken":"5530-4316-0674-5748", - "signedDataToken":"signed_token_eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJzLCpZjA" - } -] -``` - -Notes: - -- You can pass either a service account key credentials file path or a service account key credentials as string to the - `setCredentials` method of the SignedDataTokensBuilder class. -- If you pass both a file path and string to the `setCredentials` method, the last method used takes precedence. -- Time to live value expects time as seconds. -- The default time to live value is 60 seconds. - -## Migrate from v1 to v2 +# Migrate from v1 to v2 Below are the steps to migrate the java sdk from v1 to v2. -### 1. Authentication Options -In V2, we have introduced multiple authentication options. -You can now provide credentials in the following ways: +### Authentication options -- **API Key (Recommended)** -- **Passing credentials as ENV.** (`SKYFLOW_CREDENTIALS`) (**Recommended**) -- **Path to your credentials JSON file** -- **Stringified JSON of your credentials** -- **Bearer token** +In V2, we have introduced multiple authentication options. You can now provide credentials in the following ways: + +- Passing credentials in ENV. (`SKYFLOW_CREDENTIALS`) _(Recommended)_ +- API Key +- Path to your credentials JSON file +- Stringified JSON of your credentials +- Bearer token These options allow you to choose the authentication method that best suits your use case. -### V1 (Old) +**V1 (Old)** + ```java static class DemoTokenProvider implements TokenProvider { @Override @@ -334,7 +119,8 @@ static class DemoTokenProvider implements TokenProvider { } ``` -### V2 (New): Passing one of the following: +**V2 (New): Passing one of the following:** + ```java // Option 1: API Key (Recommended) Credentials skyflowCredentials = new Credentials(); @@ -353,25 +139,25 @@ skyflowCredentials.setCredentialsString(""); // Replace skyflowCredentials.setToken(""); // Replace with your actual authentication token. ``` -**Notes:** +Notes: + - Use only ONE authentication method. -- API Key or Environment Variables are recommended for production use. +- API Key or environment variables are recommended for production use. - Secure storage of credentials is essential. -- For overriding behavior and priority order of credentials, refer to the README. +- For overriding behavior and priority order of credentials, please refer to [Initialize the client](#initialize-the-client) section in [Quickstart](#quickstart). --- -### 2. Client Initialization -In V2, we have introduced a Builder design pattern for client initialization and added support for multi-vault. This allows you to configure multiple vaults during client initialization. +### Initializing the client -In V2, the log level is tied to each individual client instance. +In V2, we have introduced a builder design pattern for client initialization and added support for multi-vault. This allows you to configure multiple vaults during client initialization. In V2, the log level is tied to each individual client instance. During client initialization, you can pass the following parameters: -During client initialization, you can pass the following parameters: -- `vaultId` and `clusterId`: These values are derived from the vault ID & vault URL. -- `env`: Specify the environment (e.g., SANDBOX or PROD). +- `vaultId` and `clusterId`: These values are derived from the vault ID & vault URL. +- `env`: Specify the environment (e.g., SANDBOX or PROD). - `credentials`: The necessary authentication credentials. -### V1 (Old) +**V1 (Old)** + ```java // DemoTokenProvider class is an implementation of the TokenProvider interface DemoTokenProvider demoTokenProvider = new DemoTokenProvider(); @@ -379,7 +165,8 @@ SkyflowConfiguration skyflowConfig = new SkyflowConfiguration("",""); // Replace with the path to the credentials file @@ -404,19 +191,24 @@ Skyflow skyflowClient = Skyflow.builder() ``` **Key Changes:** + - `vaultUrl` replaced with `clusterId`. - Added environment specification (`env`). - Instance-specific log levels. --- -### 3. Request & Response Structure -In V2, we have removed the use of JSON objects from a third-party package. Instead, we have transitioned to accepting native ArrayList and HashMap data structures and adopted the Builder pattern for request creation. This request need -- `table`: The name of the table. -- `values`: An array of objects containing the data to be inserted. -The response will be of type InsertResponse class, which contains insertedFields and errors. +### Request & response structure + +In V2, we have removed the use of JSON objects from a third-party package. Instead, we have transitioned to accepting native ArrayList and HashMap data structures and adopted the builder pattern for request creation. This request needs: + +- `table`: The name of the table. +- `values`: An array list of objects containing the data to be inserted. + +The response will be of type `InsertResponse` class, which contains `insertedFields` and `errors`. + +**V1 (Old):** Request building -### V1 (Old) Request Building ```java JSONObject recordsJson = new JSONObject(); JSONArray recordsArrayJson = new JSONArray(); @@ -439,7 +231,8 @@ try { } ``` -### V2 (New) Request Building +**V2 (New):** Request building + ```java ArrayList> values = new ArrayList<>(); HashMap value = new HashMap<>(); @@ -462,7 +255,8 @@ InsertRequest insertRequest = InsertRequest.builder() .build(); ``` -### V1 (Old) Response Structure +**V1 (Old):** Response structure + ```json { "records": [ @@ -478,7 +272,8 @@ InsertRequest insertRequest = InsertRequest.builder() } ``` -### V2 (New) Response Structure +**V2 (New):** Response structure + ```json { "insertedFields": [ @@ -495,16 +290,18 @@ InsertRequest insertRequest = InsertRequest.builder() --- -## 4. Request Options -In V2, with the introduction of the Builder design pattern has made handling optional fields in Java more efficient and straightforward. +### Request options + +In V2, with the introduction of the builder design pattern has made handling optional fields in Java more efficient and straightforward. +**V1 (Old)** -### V1 (Old) ```java InsertOptions insertOptions = new InsertOptions(true); ``` -### V2 (New) +**V2 (New)** + ```java InsertRequest upsertRequest = new InsertRequest.builder() .table("") // Replace with the table name @@ -518,40 +315,69 @@ InsertRequest upsertRequest = new InsertRequest.builder() --- -## 5. Enhanced Error Details -The V2 error response includes: +### Error structure + +In V2, we have enriched the error details to provide better debugging capabilities. +The error response now includes: - `httpStatus`: The HTTP status code. - `grpcCode`: The gRPC code associated with the error. - `details` & `message`: A detailed description of the error. - `requestId`: A unique request identifier for easier debugging. -### V1 (Old) Error Structure +**V1 (Old):** Error structure + ```json { - "code": "", - "description": "" + "code": "", + "description": "" } ``` -### V2 (New) Error Structure -```json +**V2 (New):** Error structure + +```js { - "httpStatus": "", - "grpcCode": "", - "httpCode": "", - "message": "", - "requestId": "", - "details": [ "
" ] + "httpStatus": "", + "grpcCode": , + "httpCode": , + "message": "", + "requestId": "", + "details": ["
"] } ``` -## Vault APIs +# Quickstart + +Get started quickly with the essential steps: authenticate, initialize the client, and perform a basic vault operation. This section provides a minimal setup to help you integrate the SDK efficiently. + +### Authenticate + +You can use an API key to authenticate and authorize requests to an API. For authenticating via bearer tokens and different supported bearer token types, refer to the [Authenticate with bearer tokens](#authenticate-with-bearer-tokens) section. + +```java +// create a new credentials object +Credentials credentials = new Credentials(); +credentials.setApiKey(""); // add your API key in credentials +``` + +### Initialize the client + +To get started, you must first initialize the skyflow client. While initializing the skyflow client, you can specify different types of credentials. + +1. **API keys** + A unique identifier used to authenticate and authorize requests to an API. + +2. **Bearer tokens** + A temporary access token used to authenticate API requests, typically included in the Authorization header. + +3. **Service account credentials file path** + The file path pointing to a JSON file containing credentials for a service account, used for secure API access. -The [Vault](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault) module is used to -perform operations on the vault such as inserting records, detokenizing tokens and retrieving tokens for a skyflow_id. +4. **Service account credentials string (JSON formatted)** + A JSON-formatted string containing service account credentials, often used as an alternative to a file for programmatic authentication. -To use this module, the skyflow client must first be initialized as follows. +Note: Only one type of credential can be used at a time. If multiple credentials are provided, the last one added will take precedence. ```java import com.skyflow.Skyflow; @@ -561,52 +387,100 @@ import com.skyflow.enums.Env; import com.skyflow.enums.LogLevel; import com.skyflow.errors.SkyflowException; +/** + * Example program to initialize the Skyflow client with various configurations. + * The Skyflow client facilitates secure interactions with the Skyflow vault, + * such as securely managing sensitive data. + */ public class InitSkyflowClient { public static void main(String[] args) throws SkyflowException { - // Pass only one of apiKey, token, credentialsString or path in credentials - Credentials credentials = new Credentials(); - credentials.setToken(""); - - VaultConfig config = new VaultConfig(); - config.setVaultId(""); // Primary vault - config.setClusterId(""); // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - config.setEnv(Env.PROD); // Env by default is set to PROD - config.setCredentials(credentials); // Individual credentials - + // Step 1: Define the primary credentials for authentication. + // Note: Only one type of credential can be used at a time. You can choose between: + // - API key + // - Bearer token + // - A credentials string (JSON-formatted) + // - A file path to a credentials file. + + // Initialize primary credentials using a Bearer token for authentication. + Credentials primaryCredentials = new Credentials(); + primaryCredentials.setToken(""); // Replace with your actual authentication token. + + // Step 2: Configure the primary vault details. + // VaultConfig stores all necessary details to connect to a specific Skyflow vault. + VaultConfig primaryConfig = new VaultConfig(); + primaryConfig.setVaultId(""); // Replace with your primary vault's ID. + primaryConfig.setClusterId(""); // Replace with the cluster ID (part of the vault URL, e.g., https://{clusterId}.vault.skyflowapis.com). + primaryConfig.setEnv(Env.PROD); // Set the environment (PROD, SANDBOX, STAGE, DEV). + primaryConfig.setCredentials(primaryCredentials); // Attach the primary credentials to this vault configuration. + + // Step 3: Create credentials as a JSON object (if a Bearer Token is not provided). + // Demonstrates an alternate approach to authenticate with Skyflow using a credentials object. JsonObject credentialsObject = new JsonObject(); - credentialsObject.addProperty("clientID", ""); - credentialsObject.addProperty("clientName", ""); - credentialsObject.addProperty("TokenURI", ""); - credentialsObject.addProperty("keyID", ""); - credentialsObject.addProperty("privateKey", ""); - - // To generate Bearer Token from credentials string. + credentialsObject.addProperty("clientID", ""); // Replace with your Client ID. + credentialsObject.addProperty("clientName", ""); // Replace with your Client Name. + credentialsObject.addProperty("TokenURI", ""); // Replace with the Token URI. + credentialsObject.addProperty("keyID", ""); // Replace with your Key ID. + credentialsObject.addProperty("privateKey", ""); // Replace with your Private Key. + + // Step 4: Convert the JSON object to a string and use it as credentials. + // This approach allows the use of dynamically generated or pre-configured credentials. Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setCredentialsString(credentialsObject.toString()); - + skyflowCredentials.setCredentialsString(credentialsObject.toString()); // Converts JSON object to string for use as credentials. + + // Step 5: Define secondary credentials (API key-based authentication as an example). + // Demonstrates a different type of authentication mechanism for Skyflow vaults. + Credentials secondaryCredentials = new Credentials(); + secondaryCredentials.setApiKey(""); // Replace with your API Key for authentication. + + // Step 6: Configure the secondary vault details. + // A secondary vault configuration can be used for operations involving multiple vaults. + VaultConfig secondaryConfig = new VaultConfig(); + secondaryConfig.setVaultId(""); // Replace with your secondary vault's ID. + secondaryConfig.setClusterId(""); // Replace with the corresponding cluster ID. + secondaryConfig.setEnv(Env.SANDBOX); // Set the environment for this vault. + secondaryConfig.setCredentials(secondaryCredentials); // Attach the secondary credentials to this configuration. + + // Step 7: Define tertiary credentials using a path to a credentials JSON file. + // This method demonstrates an alternative authentication method. + Credentials tertiaryCredentials = new Credentials(); + tertiaryCredentials.setPath(""); // Replace with the path to your credentials file. + + // Step 8: Configure the tertiary vault details. + VaultConfig tertiaryConfig = new VaultConfig(); + tertiaryConfig.setVaultId(""); // Replace with the tertiary vault ID. + tertiaryConfig.setClusterId(""); // Replace with the corresponding cluster ID. + tertiaryConfig.setEnv(Env.STAGE); // Set the environment for this vault. + tertiaryConfig.setCredentials(tertiaryCredentials); // Attach the tertiary credentials. + + // Step 9: Build and initialize the Skyflow client. + // Skyflow client is configured with multiple vaults and credentials. Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.INFO) // Set log level. By default, it is set to ERROR - .addVaultConfig(config) // Add vault config - .addSkyflowCredentials(skyflowCredentials) // Skyflow credentials will be used if no individual credentials are passed + .setLogLevel(LogLevel.INFO) // Set log level for debugging or monitoring purposes. + .addVaultConfig(primaryConfig) // Add the primary vault configuration. + .addVaultConfig(secondaryConfig) // Add the secondary vault configuration. + .addVaultConfig(tertiaryConfig) // Add the tertiary vault configuration. + .addSkyflowCredentials(skyflowCredentials) // Add JSON-formatted credentials if applicable. .build(); + + // The Skyflow client is now fully initialized. + // Use the `skyflowClient` object to perform secure operations such as: + // - Inserting data + // - Retrieving data + // - Deleting data + // within the configured Skyflow vaults. } } ``` Notes: -- If both Skyflow common credentials and individual credentials at the configuration level are provided, the individual - credentials at the configuration level will take priority. - -All Vault APIs must be invoked using a client instance. - -## Insert data into the vault +- If both Skyflow common credentials and individual credentials at the configuration level are specified, the individual credentials at the configuration level will take precedence. +- If neither Skyflow common credentials nor individual configuration-level credentials are provided, the SDK attempts to retrieve credentials from the `SKYFLOW_CREDENTIALS` environment variable. +- All Vault operations require a client instance. -To insert data into your vault, use the `insert` method. The `InsertRequest` class is used to create an insert request, -which contains the values to be inserted in the form of a list of records. Additionally, you can provide options in the -insert request, such as returning tokenized data, upserting records, and continuing on error. +### Insert data into the vault -Insert call schema +To insert data into your vault, use the `insert` method. The `InsertRequest` class creates an insert request, which includes the values to be inserted as a list of records. Below is a simple example to get started. For advanced options, check out [Insert data into the vault](#insert-data-into-the-vault-1) section. ```java import com.skyflow.errors.SkyflowException; @@ -616,36 +490,76 @@ import com.skyflow.vault.data.InsertResponse; import java.util.ArrayList; import java.util.HashMap; -public class InsertSchema { +/** + * This example demonstrates how to insert sensitive data (e.g., card information) into a Skyflow vault using the Skyflow client. + * + * 1. Initializes the Skyflow client. + * 2. Prepares a record with sensitive data (e.g., card number and cardholder name). + * 3. Creates an insert request for inserting the data into the Skyflow vault. + * 4. Prints the response of the insert operation. + */ +public class InsertExample { public static void main(String[] args) { try { - // Initialize skyflow client + // Initialize Skyflow client + // Step 1: Initialize data to be inserted into the Skyflow vault ArrayList> insertData = new ArrayList<>(); - HashMap insertRecord1 = new HashMap<>(); - insertRecord1.put("", ""); - insertRecord1.put("", ""); + // Create a HashMap for a single record with card number and cardholder name as fields + HashMap insertRecord = new HashMap<>(); + insertRecord.put("card_number", "4111111111111111"); // Replace with actual card number (sensitive data) + insertRecord.put("cardholder_name", "john doe"); // Replace with actual cardholder name (sensitive data) - HashMap insertRecord2 = new HashMap<>(); - insertRecord2.put("", ""); - insertRecord2.put("", ""); + // Add the created record to the list of data to be inserted + insertData.add(insertRecord); - insertData.add(insertRecord1); - insertData.add(insertRecord2); + // Step 2: Build the InsertRequest object with the table name and data to insert + InsertRequest insertRequest = InsertRequest.builder() + .table("table1") // Specify the table in the vault where the data will be inserted + .values(insertData) // Attach the data (records) to be inserted + .returnTokens(true) // Specify if tokens should be returned upon successful insertion + .build(); // Build the insert request object - InsertRequest insertRequest = InsertRequest.builder().table("").values(insertData).build(); - InsertResponse insertResponse = skyflowClient.vault("").insert(); - System.out.println("Insert Response: " + insertResponse); + // Step 3: Perform the insert operation using the Skyflow client + InsertResponse insertResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").insert(insertRequest); + // Replace the vault ID "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + // Step 4: Print the response from the insert operation + System.out.println(insertResponse); } catch (SkyflowException e) { + // Step 5: Handle any exceptions that may occur during the insert operation System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the stack trace for debugging purposes } } } ``` -Insert -call [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/InsertExample.java) +Skyflow returns tokens for the record that was just inserted. + +```json +{ + "insertedFields": [ + { + "card_number": "5484-7829-1702-9110", + "request_index": "0", + "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", + "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b" + } + ], + "errors": [] +} +``` + +# Vault + +The [Vault](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault) module performs operations on the vault, including inserting records, detokenizing tokens, and retrieving tokens associated with a `skyflow_id`. + +## Insert data into the vault + +Apart from using the `insert` method to insert data into your vault covered in [Quickstart](#quickstart), you can also specify options in `InsertRequest`, such as returning tokenized data, upserting records, or continuing the operation in case of errors. + +### Construct an insert request ```java import com.skyflow.errors.SkyflowException; @@ -655,46 +569,55 @@ import com.skyflow.vault.data.InsertResponse; import java.util.ArrayList; import java.util.HashMap; -public class InsertExample { +/** + * Example program to demonstrate inserting data into a Skyflow vault, along with corresponding InsertRequest schema. + * + */ +public class InsertSchema { public static void main(String[] args) { try { - // Initialize skyflow client + // Initialize Skyflow client + // Step 1: Prepare the data to be inserted into the Skyflow vault ArrayList> insertData = new ArrayList<>(); - HashMap insertRecord = new HashMap<>(); - insertRecord.put("card_number", "4111111111111111"); - insertRecord.put("cardholder_name", "john doe"); - insertData.add(insertRecord); + // Create the first record with field names and their respective values + HashMap insertRecord1 = new HashMap<>(); + insertRecord1.put("", ""); // Replace with actual field name and value + insertRecord1.put("", ""); // Replace with actual field name and value + + // Create the second record with field names and their respective values + HashMap insertRecord2 = new HashMap<>(); + insertRecord2.put("", ""); // Replace with actual field name and value + insertRecord2.put("", ""); // Replace with actual field name and value + + // Add the records to the list of data to be inserted + insertData.add(insertRecord1); + insertData.add(insertRecord2); + + // Step 2: Build an InsertRequest object with the table name and the data to insert InsertRequest insertRequest = InsertRequest.builder() - .table("table1") - .values(insertData) - .returnTokens(true) + .table("") // Replace with the actual table name in your Skyflow vault + .values(insertData) // Attach the data to be inserted .build(); - InsertResponse insertResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").insert(); + + // Step 3: Use the Skyflow client to perform the insert operation + InsertResponse insertResponse = skyflowClient.vault("").insert(insertRequest); + // Replace with your actual vault ID + + // Print the response from the insert operation System.out.println("Insert Response: " + insertResponse); } catch (SkyflowException e) { - System.out.println("Error occurred: "); - System.out.println(e); + // Step 4: Handle any exceptions that occur during the insert operation + System.out.println("Error occurred while inserting data: "); + e.printStackTrace(); // Print the stack trace for debugging } } } ``` -Skyflow returns tokens for the record you just inserted. +### Insert call [example](https://github.com/skyflowapi/skyflow-java/blob/SK-1893-update-readme-for-v2/samples/src/main/java/com/example/vault/InsertExample.java) with `continueOnError` option -```js -Insert Response: { - "insertedFields": [{ - "card_number": "5484-7829-1702-9110", - "request_index": "0", - "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", - "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b", - }], - "errors": [] -} -``` - -Insert call example with `continueOnError` option +The `continueOnError` flag is a boolean that determines whether insert operation should proceed despite encountering partial errors. Set to `true` to allow the process to continue even if some errors occur. ```java import com.skyflow.errors.SkyflowException; @@ -704,34 +627,54 @@ import com.skyflow.vault.data.InsertResponse; import java.util.ArrayList; import java.util.HashMap; +/** + * This example demonstrates how to insert multiple records into a Skyflow vault using the Skyflow client. + * + * 1. Initializes the Skyflow client. + * 2. Prepares multiple records with sensitive data (e.g., card number and cardholder name). + * 3. Creates an insert request with the records to insert into the Skyflow vault. + * 4. Specifies options to continue on error and return tokens. + * 5. Prints the response of the insert operation. + */ public class InsertExample { public static void main(String[] args) { try { - // Initialize skyflow client + // Initialize Skyflow client + // Step 1: Initialize a list to hold the data records to be inserted into the vault ArrayList> insertData = new ArrayList<>(); + // Step 2: Create the first record with card number and cardholder name HashMap insertRecord1 = new HashMap<>(); - insertRecord1.put("card_number", "4111111111111111"); - insertRecord1.put("cardholder_name", "john doe"); + insertRecord1.put("card_number", "4111111111111111"); // Replace with actual card number (sensitive data) + insertRecord1.put("cardholder_name", "john doe"); // Replace with actual cardholder name (sensitive data) + // Step 3: Create the second record with card number and cardholder name HashMap insertRecord2 = new HashMap<>(); - insertRecord2.put("card_numbe", "4111111111111111"); - insertRecord2.put("cardholder_name", "jane doe"); + insertRecord2.put("card_number", "4111111111111111"); // Ensure field name matches ("card_number") + insertRecord2.put("cardholder_name", "jane doe"); // Replace with actual cardholder name (sensitive data) + // Step 4: Add the records to the insertData list insertData.add(insertRecord1); insertData.add(insertRecord2); + // Step 5: Build the InsertRequest object with the data records to insert InsertRequest insertRequest = InsertRequest.builder() - .table("table1") - .values(insertData) - .returnTokens(true) - .continueOnError(true) - .build(); - InsertResponse insertResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").insert(); - System.out.println("Insert Response: " + insertResponse); + .table("table1") // Specify the table in the vault where data will be inserted + .values(insertData) // Attach the data records to be inserted + .returnTokens(true) // Specify if tokens should be returned upon successful insertion + .continueOnError(true) // Specify to continue inserting records even if an error occurs for some records + .build(); // Build the insert request object + + // Step 6: Perform the insert operation using the Skyflow client + InsertResponse insertResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").insert(insertRequest); + // Replace the vault ID "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + // Step 7: Print the response from the insert operation + System.out.println(insertResponse); } catch (SkyflowException e) { + // Step 8: Handle any exceptions that may occur during the insert operation System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the stack trace for debugging purposes } } } @@ -739,22 +682,28 @@ public class InsertExample { Sample response: -```js +```json { - "insertedFields": [{ - "card_number": "5484-7829-1702-9110", - "request_index": "0", - "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", - "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b", - }], - "errors": [{ - "request_index": "1", - "error": "Insert failed. Column card_numbe is invalid. Specify a valid column.", - }] + "insertedFields": [ + { + "card_number": "5484-7829-1702-9110", + "request_index": "0", + "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", + "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b" + } + ], + "errors": [ + { + "request_index": "1", + "error": "Insert failed. Column card_numbe is invalid. Specify a valid column." + } + ] } ``` -Insert call example with `upsert` option +### Insert call example with `upsert` option + +An upsert operation checks for a record based on a unique column's value. If a match exists, the record is updated; otherwise, a new record is inserted. ```java import com.skyflow.errors.SkyflowException; @@ -764,26 +713,47 @@ import com.skyflow.vault.data.InsertResponse; import java.util.ArrayList; import java.util.HashMap; -public class InsertExample { +/** + * This example demonstrates how to insert or upsert a record into a Skyflow vault using the Skyflow client, with the option to return tokens. + * + * 1. Initializes the Skyflow client. + * 2. Prepares a record to insert or upsert (e.g., cardholder name). + * 3. Creates an insert request with the data to be inserted or upserted into the Skyflow vault. + * 4. Specifies the field (cardholder_name) for upsert operations. + * 5. Prints the response of the insert or upsert operation. + */ +public class UpsertExample { public static void main(String[] args) { try { - // Initialize skyflow client + // Initialize Skyflow client + // Step 1: Initialize a list to hold the data records for the insert/upsert operation ArrayList> upsertData = new ArrayList<>(); + + // Step 2: Create a record with the field 'cardholder_name' to insert or upsert HashMap upsertRecord = new HashMap<>(); - upsertRecord.put("cardholder_name", "jane doe"); + upsertRecord.put("cardholder_name", "jane doe"); // Replace with the actual cardholder name + + // Step 3: Add the record to the upsertData list upsertData.add(upsertRecord); + // Step 4: Build the InsertRequest object with the upsertData InsertRequest insertRequest = InsertRequest.builder() - .table("table1") - .values(upsertData) - .returnTokens(true) - .upsert("cardholder_name") - .build(); - InsertResponse insertResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").insert(); - System.out.println("Insert Response: " + insertResponse); + .table("table1") // Specify the table in the vault where data will be inserted/upserted + .values(upsertData) // Attach the data records to be inserted/upserted + .returnTokens(true) // Specify if tokens should be returned upon successful operation + .upsert("cardholder_name") // Specify the field to be used for upsert operations (e.g., cardholder_name) + .build(); // Build the insert request object + + // Step 5: Perform the insert/upsert operation using the Skyflow client + InsertResponse insertResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").insert(insertRequest); + // Replace the vault ID "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + // Step 6: Print the response from the insert/upsert operation + System.out.println(insertResponse); } catch (SkyflowException e) { + // Step 7: Handle any exceptions that may occur during the insert/upsert operation System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the stack trace for debugging purposes } } } @@ -791,21 +761,23 @@ public class InsertExample { Skyflow returns tokens, with `upsert` support, for the record you just inserted. -```js +```json { - "insertedFields": [{ - "skyflowId": "9fac9201-7b8a-4446-93f8-5244e1213bd1", - "cardholder_name": "73ce45ce-20fd-490e-9310-c1d4f603ee83" - }], - "errors": [] + "insertedFields": [ + { + "skyflowId": "9fac9201-7b8a-4446-93f8-5244e1213bd1", + "cardholder_name": "73ce45ce-20fd-490e-9310-c1d4f603ee83" + } + ], + "errors": [] } ``` ## Detokenize -To retrieve tokens from your vault, you can use the `detokenize` method. The `DetokenizeRequest` class requires a list -of detokenization data to be provided as input. Additionally, the redaction type and continue on error are optional -parameters. +To retrieve tokens from your vault, use the `detokenize` method. The `DetokenizeRequest` class requires a list of detokenization data as input. Additionally, you can provide optional parameters, such as the redaction type and the option to continue on error. + +### Construct a detokenize request ```java import com.skyflow.enums.RedactionType; @@ -815,24 +787,37 @@ import com.skyflow.vault.tokens.DetokenizeResponse; import java.util.ArrayList; +/** + * This example demonstrates how to detokenize sensitive data from tokens stored in a Skyflow vault, along with corresponding DetokenizeRequest schema. + * + */ public class DetokenizeSchema { public static void main(String[] args) { try { - // Initialize skyflow client + // Initialize Skyflow client + // Step 1: Initialize a list of tokens to be detokenized (replace with actual tokens) ArrayList tokens = new ArrayList<>(); - tokens.add(""); - tokens.add(""); - tokens.add(""); + tokens.add(""); // Replace with your actual token value + tokens.add(""); // Replace with your actual token value + tokens.add(""); // Replace with your actual token value + + // Step 2: Create the DetokenizeRequest object with the tokens and redaction type DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() - .tokens(tokens) - .continueOnError(true) - .redactionType(RedactionType.PLAIN_TEXT) - .build(); + .tokens(tokens) // Provide the list of tokens to be detokenized + .continueOnError(true) // Continue even if one token cannot be detokenized + .redactionType(RedactionType.PLAIN_TEXT) // Specify how the detokenized data should be returned (plain text) + .build(); // Build the detokenization request + + // Step 3: Call the Skyflow vault to detokenize the provided tokens DetokenizeResponse detokenizeResponse = skyflowClient.vault("").detokenize(detokenizeRequest); + // Replace with your actual Skyflow vault ID + + // Step 4: Print the detokenization response, which contains the detokenized data System.out.println(detokenizeResponse); } catch (SkyflowException e) { + // Step 5: Handle any errors that occur during the detokenization process System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception for debugging purposes } } } @@ -843,8 +828,7 @@ Notes: - `redactionType` defaults to [`RedactionType.PLAIN_TEXT`](#redaction-types). - `continueOnError` defaults to `true`. -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/DetokenizeExample.java) -of a detokenize call: +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/DetokenizeExample.java) of a detokenize call: ```java import com.skyflow.enums.RedactionType; @@ -854,24 +838,42 @@ import com.skyflow.vault.tokens.DetokenizeResponse; import java.util.ArrayList; +/** + * This example demonstrates how to detokenize sensitive data from tokens stored in a Skyflow vault. + * + * 1. Initializes the Skyflow client. + * 2. Creates a list of tokens (e.g., credit card tokens) that represent the sensitive data. + * 3. Builds a detokenization request using the provided tokens and specifies how the redacted data should be returned. + * 4. Calls the Skyflow vault to detokenize the tokens and retrieves the detokenized data. + * 5. Prints the detokenization response, which contains the detokenized values or errors. + */ public class DetokenizeExample { public static void main(String[] args) { try { - // Initialize skyflow client + // Initialize Skyflow client + // Step 1: Initialize a list of tokens to be detokenized (replace with actual token values) ArrayList tokens = new ArrayList<>(); - tokens.add("9738-1683-0486-1480"); - tokens.add("6184-6357-8409-6668"); - tokens.add("4914-9088-2814-3840"); + tokens.add("9738-1683-0486-1480"); // Replace with your actual token value + tokens.add("6184-6357-8409-6668"); // Replace with your actual token value + tokens.add("4914-9088-2814-3840"); // Replace with your actual token value + + // Step 2: Create the DetokenizeRequest object with the tokens and redaction type DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() - .tokens(tokens) - .continueOnError(false) - .redactionType(RedactionType.PLAIN_TEXT) - .build(); + .tokens(tokens) // Provide the list of tokens to be detokenized + .continueOnError(false) // Stop the process if any token cannot be detokenized + .redactionType(RedactionType.PLAIN_TEXT) // Specify how the detokenized data should be returned (plain text) + .build(); // Build the detokenization request + + // Step 3: Call the Skyflow vault to detokenize the provided tokens DetokenizeResponse detokenizeResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").detokenize(detokenizeRequest); + // Replace "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + // Step 4: Print the detokenization response, which contains the detokenized data System.out.println(detokenizeResponse); } catch (SkyflowException e) { + // Step 5: Handle any errors that occur during the detokenization process System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception for debugging purposes } } } @@ -879,7 +881,7 @@ public class DetokenizeExample { Sample response: -```js +```json { "detokenizedFields": [{ "token": "9738-1683-0486-1480", @@ -899,7 +901,7 @@ Sample response: ``` -An example of a detokenize call with `continueOnError` option: +### An example of a detokenize call with `continueOnError` option: ```java import com.skyflow.enums.RedactionType; @@ -909,24 +911,42 @@ import com.skyflow.vault.tokens.DetokenizeResponse; import java.util.ArrayList; +/** + * This example demonstrates how to detokenize sensitive data (e.g., credit card numbers) from tokens in a Skyflow vault. + * + * 1. Initializes the Skyflow client. + * 2. Creates a list of tokens (e.g., credit card tokens) to be detokenized. + * 3. Builds a detokenization request with the tokens and specifies the redaction type for the detokenized data. + * 4. Calls the Skyflow vault to detokenize the tokens and retrieves the detokenized data. + * 5. Prints the detokenization response, which includes the detokenized values or errors. + */ public class DetokenizeExample { public static void main(String[] args) { try { - // Initialize skyflow client + // Initialize Skyflow client + // Step 1: Initialize a list of tokens to be detokenized (replace with actual token values) ArrayList tokens = new ArrayList<>(); - tokens.add("9738-1683-0486-1480"); - tokens.add("6184-6357-8409-6668"); - tokens.add("4914-9088-2814-384"); + tokens.add("9738-1683-0486-1480"); // Example token value 1 + tokens.add("6184-6357-8409-6668"); // Example token value 2 + tokens.add("4914-9088-2814-384"); // Example token value 3 + + // Step 2: Create the DetokenizeRequest object with the tokens and redaction type DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() - .tokens(tokens) - .continueOnError(true) - .redactionType(RedactionType.PLAIN_TEXT) - .build(); + .tokens(tokens) // Provide the list of tokens to detokenize + .continueOnError(true) // Continue even if some tokens cannot be detokenized + .redactionType(RedactionType.PLAIN_TEXT) // Specify the format for the detokenized data (plain text) + .build(); // Build the detokenization request + + // Step 3: Call the Skyflow vault to detokenize the provided tokens DetokenizeResponse detokenizeResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").detokenize(detokenizeRequest); + // Replace "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + // Step 4: Print the detokenization response, which contains the detokenized data or errors System.out.println(detokenizeResponse); } catch (SkyflowException e) { + // Step 5: Handle any errors that occur during the detokenization process System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception for debugging purposes } } } @@ -934,7 +954,7 @@ public class DetokenizeExample { Sample response: -```js +```json { "detokenizedFields": [{ "token": "9738-1683-0486-1480", @@ -954,11 +974,11 @@ Sample response: ## Tokenize -To tokenize data, use the `tokenize` method. The `TokenizeRequest` class is utilized to create a tokenize request. In -this request, you specify the `values` parameter, which is a list of `ColumnValue`. Each `ColumnValue` contains two -properties: `value` and `columnGroup`. +Tokenization replaces sensitive data with unique identifier tokens. This approach protects sensitive information by securely storing the original data while allowing the use of tokens within your application. + +To tokenize data, use the `tokenize` method. The `TokenizeRequest` class creates a tokenize request. In this request, you specify the `values` parameter, which is a list of `ColumnValue` objects. Each `ColumnValue` contains two properties: `value` and `columnGroup`. -Tokenize Schema +### Construct a tokenize request ```java import com.skyflow.errors.SkyflowException; @@ -968,31 +988,44 @@ import com.skyflow.vault.tokens.TokenizeResponse; import java.util.ArrayList; +/** + * This example demonstrates how to tokenize sensitive data (e.g., credit card information) using the Skyflow client, along with corresponding TokenizeRequest schema. + * + */ public class TokenizeSchema { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client + // Step 1: Initialize a list of column values to be tokenized (replace with actual sensitive data) ArrayList columnValues = new ArrayList<>(); - ColumnValue columnValue1 = ColumnValue.builder().value("").columnGroup("").build(); - ColumnValue columnValue2 = ColumnValue.builder().value("").columnGroup("").build(); + // Step 2: Create column values for each sensitive data field (e.g., card number and cardholder name) + ColumnValue columnValue1 = ColumnValue.builder().value("").columnGroup("").build(); // Replace and with actual data + ColumnValue columnValue2 = ColumnValue.builder().value("").columnGroup("").build(); // Replace and with actual data + // Add the created column values to the list columnValues.add(columnValue1); columnValues.add(columnValue2); + // Step 3: Build the TokenizeRequest with the column values TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); + + // Step 4: Call the Skyflow vault to tokenize the sensitive data TokenizeResponse tokenizeResponse = skyflowClient.vault("").tokenize(tokenizeRequest); + // Replace with your actual Skyflow vault ID + + // Step 5: Print the tokenization response, which contains the generated tokens or errors System.out.println(tokenizeResponse); } catch (SkyflowException e) { + // Step 6: Handle any errors that occur during the tokenization process System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception for debugging purposes } } } ``` -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/TokenizeExample.java) -of Tokenize call: +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/TokenizeExample.java) of Tokenize call: ```java import com.skyflow.errors.SkyflowException; @@ -1002,20 +1035,44 @@ import com.skyflow.vault.tokens.TokenizeResponse; import java.util.ArrayList; -public class TokenizeSchema { +/** + * This example demonstrates how to tokenize sensitive data (e.g., credit card information) using the Skyflow client. + * + * 1. Initializes the Skyflow client. + * 2. Creates a column value for sensitive data (e.g., credit card number). + * 3. Builds a tokenize request with the column value to be tokenized. + * 4. Sends the request to the Skyflow vault for tokenization. + * 5. Prints the tokenization response, which includes the token or errors. + */ +public class TokenizeExample { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client + // Step 1: Initialize a list of column values to be tokenized (replace with actual sensitive data) ArrayList columnValues = new ArrayList<>(); - ColumnValue columnValue = ColumnValue.builder().value("4111111111111111").columnGroup("card_number_cg").build(); + + // Step 2: Create a column value for the sensitive data (e.g., card number with its column group) + ColumnValue columnValue = ColumnValue.builder() + .value("4111111111111111") // Replace with the actual sensitive data (e.g., card number) + .columnGroup("card_number_cg") // Replace with the actual column group name + .build(); + + // Add the created column value to the list columnValues.add(columnValue); + // Step 3: Build the TokenizeRequest with the column value TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); + + // Step 4: Call the Skyflow vault to tokenize the sensitive data TokenizeResponse tokenizeResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").tokenize(tokenizeRequest); + // Replace "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + // Step 5: Print the tokenization response, which contains the generated token or any errors System.out.println(tokenizeResponse); } catch (SkyflowException e) { + // Step 6: Handle any errors that occur during the tokenization process System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception for debugging purposes } } } @@ -1023,7 +1080,7 @@ public class TokenizeSchema { Sample response: -```js +```json { "tokens": [5479-4229-4622-1393] } @@ -1031,12 +1088,9 @@ Sample response: ## Get -To retrieve data using Skyflow IDs or unique column values, use the `get` method. The `GetRequest` class is used to -create a get request, where you specify parameters such as the table name, redaction type, Skyflow IDs, column names, -column values, and return tokens. If Skyflow IDs are provided, column names and column values cannot be used. Similarly, -if column names or column values are provided, Skyflow IDs cannot be used. +To retrieve data using Skyflow IDs or unique column values, use the `get` method. The `GetRequest` class creates a get request, where you specify parameters such as the table name, redaction type, Skyflow IDs, column names, column values, and whether to return tokens. If you specify Skyflow IDs, you can't use column names and column values, and the inverse is true—if you specify column names and column values, you can't use Skyflow IDs. -Get Schema +### Construct a get request ```java import com.skyflow.enums.RedactionType; @@ -1046,44 +1100,61 @@ import com.skyflow.vault.data.GetResponse; import java.util.ArrayList; +/** + * This example demonstrates how to retrieve data from the Skyflow vault using different methods, along with corresponding GetRequest schema. + * + */ public class GetSchema { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client + // Step 1: Initialize a list of Skyflow IDs to retrieve records (replace with actual Skyflow IDs) ArrayList ids = new ArrayList<>(); - ids.add(""); - ids.add(""); + ids.add(""); // Replace with actual Skyflow ID + ids.add(""); // Replace with actual Skyflow ID + + // Step 2: Create a GetRequest to retrieve records by Skyflow ID without returning tokens GetRequest getByIdRequest = GetRequest.builder() .ids(ids) - .table("") - .returnTokens(false) - .redactionType(RedactionType.PLAIN_TEXT) + .table("") // Replace with the actual table name + .returnTokens(false) // Set to false to avoid returning tokens + .redactionType(RedactionType.PLAIN_TEXT) // Redact data as plain text .build(); - GetResponse getByIdResponse = skyflowClient.vault("").get(getByIdRequest); + + // Send the request to the Skyflow vault and retrieve the records + GetResponse getByIdResponse = skyflowClient.vault("").get(getByIdRequest); // Replace with actual Vault ID System.out.println(getByIdResponse); + // Step 3: Create another GetRequest to retrieve records by Skyflow ID with tokenized values GetRequest getTokensRequest = GetRequest.builder() .ids(ids) - .table("") - .returnTokens(true) + .table("") // Replace with the actual table name + .returnTokens(true) // Set to true to return tokenized values .build(); - GetResponse getTokensResponse = skyflowClient.vault("").get(getTokensRequest); + + // Send the request to the Skyflow vault and retrieve the tokenized records + GetResponse getTokensResponse = skyflowClient.vault("").get(getTokensRequest); // Replace with actual Vault ID System.out.println(getTokensResponse); + // Step 4: Create a GetRequest to retrieve records based on specific column values ArrayList columnValues = new ArrayList<>(); - columnValues.add(""); - columnValues.add(""); + columnValues.add(""); // Replace with the actual column value + columnValues.add(""); // Replace with the actual column value + GetRequest getByColumnRequest = GetRequest.builder() - .table("") - .columnName("") - .columnValues(columnValues) - .redactionType(RedactionType.PLAIN_TEXT) + .table("") // Replace with the actual table name + .columnName("") // Replace with the column name + .columnValues(columnValues) // Add the list of column values to filter by + .redactionType(RedactionType.PLAIN_TEXT) // Redact data as plain text .build(); - GetResponse getByColumnResponse = skyflowClient.vault("").get(getByColumnRequest); + + // Send the request to the Skyflow vault and retrieve the records filtered by column values + GetResponse getByColumnResponse = skyflowClient.vault("").get(getByColumnRequest); // Replace with actual Vault ID System.out.println(getByColumnResponse); } catch (SkyflowException e) { + // Step 5: Handle any errors that occur during the retrieval process System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception for debugging purposes } } } @@ -1091,10 +1162,9 @@ public class GetSchema { ### Get by skyflow IDs -- +Retrieve specific records using `skyflow_ids`. Ideal for fetching exact records when IDs are known. -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/GetExample.java) -of a get call to retrieve data using Redaction type: +An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/GetExample.java) of a get call to retrieve data using Redaction type: ```java import com.skyflow.enums.RedactionType; @@ -1104,24 +1174,45 @@ import com.skyflow.vault.data.GetResponse; import java.util.ArrayList; +/** + * This example demonstrates how to retrieve data from the Skyflow vault using a list of Skyflow IDs. + * + * 1. Initializes the Skyflow client with a given vault ID. + * 2. Creates a request to retrieve records based on Skyflow IDs. + * 3. Specifies that the response should not return tokens. + * 4. Uses plain text redaction type for the retrieved records. + * 5. Prints the response to display the retrieved records. + */ public class GetExample { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client + // Step 1: Initialize a list of Skyflow IDs (replace with actual Skyflow IDs) ArrayList ids = new ArrayList<>(); - ids.add("a581d205-1969-4350-acbe-a2a13eb871a6"); - ids.add("5ff887c3-b334-4294-9acc-70e78ae5164a"); + ids.add("a581d205-1969-4350-acbe-a2a13eb871a6"); // Replace with actual Skyflow ID + ids.add("5ff887c3-b334-4294-9acc-70e78ae5164a"); // Replace with actual Skyflow ID + + // Step 2: Create a GetRequest to retrieve records based on Skyflow IDs + // The request specifies: + // - `ids`: The list of Skyflow IDs to retrieve + // - `table`: The table from which the records will be retrieved + // - `returnTokens`: Set to false, meaning tokens will not be returned in the response + // - `redactionType`: Set to PLAIN_TEXT, meaning the retrieved records will have data redacted as plain text GetRequest getByIdRequest = GetRequest.builder() .ids(ids) - .table("table1") - .returnTokens(false) - .redactionType(RedactionType.PLAIN_TEXT) + .table("table1") // Replace with the actual table name + .returnTokens(false) // Set to false to avoid returning tokens + .redactionType(RedactionType.PLAIN_TEXT) // Redact data as plain text .build(); - GetResponse getByIdResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").get(getByIdRequest); - System.out.println(getByIdResponse); + + // Step 3: Send the request to the Skyflow vault and retrieve the records + GetResponse getByIdResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").get(getByIdRequest); // Replace with actual Vault ID + System.out.println(getByIdResponse); // Print the response to the console + } catch (SkyflowException e) { + // Step 4: Handle any errors that occur during the data retrieval process System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception for debugging purposes } } } @@ -1129,27 +1220,31 @@ public class GetExample { Sample response: -```js +```json { - "data": [{ - "card_number": "4555555555555553", - "email": "john.doe@gmail.com", - "name": "john doe", - "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6", - }, { - "card_number": "4555555555555559", - "email": "jane.doe@gmail.com", - "name": "jane doe", - "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a", - }], - "errors": [] + "data": [ + { + "card_number": "4555555555555553", + "email": "john.doe@gmail.com", + "name": "john doe", + "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6" + }, + { + "card_number": "4555555555555559", + "email": "jane.doe@gmail.com", + "name": "jane doe", + "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a" + } + ], + "errors": [] } ``` -- +### Get tokens + +Return tokens for records. Ideal for securely processing sensitive data while maintaining data privacy. -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/getExample.java) -of get call to retrieve tokens using Skyflow IDs: +An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/getExample.java) of get call to retrieve tokens using Skyflow IDs: ```java import com.skyflow.enums.RedactionType; @@ -1159,23 +1254,41 @@ import com.skyflow.vault.data.GetResponse; import java.util.ArrayList; +/** + * This example demonstrates how to retrieve data from the Skyflow vault and return tokens along with the records. + * + * 1. Initializes the Skyflow client with a given vault ID. + * 2. Creates a request to retrieve records based on Skyflow IDs and ensures tokens are returned. + * 3. Prints the response to display the retrieved records along with the tokens. + */ public class GetExample { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client + // Step 1: Initialize a list of Skyflow IDs (replace with actual Skyflow IDs) ArrayList ids = new ArrayList<>(); - ids.add("a581d205-1969-4350-acbe-a2a13eb871a6"); - ids.add("5ff887c3-b334-4294-9acc-70e78ae5164a"); + ids.add("a581d205-1969-4350-acbe-a2a13eb871a6"); // Replace with actual Skyflow ID + ids.add("5ff887c3-b334-4294-9acc-70e78ae5164a"); // Replace with actual Skyflow ID + + // Step 2: Create a GetRequest to retrieve records based on Skyflow IDs + // The request specifies: + // - `ids`: The list of Skyflow IDs to retrieve + // - `table`: The table from which the records will be retrieved + // - `returnTokens`: Set to true, meaning tokens will be included in the response GetRequest getTokensRequest = GetRequest.builder() .ids(ids) - .table("table1") - .returnTokens(true) + .table("table1") // Replace with the actual table name + .returnTokens(true) // Set to true to include tokens in the response .build(); - GetResponse getTokensResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").get(getTokensRequest); - System.out.println(getTokensResponse); + + // Step 3: Send the request to the Skyflow vault and retrieve the records with tokens + GetResponse getTokensResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").get(getTokensRequest); // Replace with actual Vault ID + System.out.println(getTokensResponse); // Print the response to the console + } catch (SkyflowException e) { + // Step 4: Handle any errors that occur during the data retrieval process System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception for debugging purposes } } } @@ -1183,29 +1296,31 @@ public class GetExample { Sample response: -```js +```json { - "data": [{ - "card_number": "3998-2139-0328-0697", - "email": "c9a6c9555060@82c092e7.bd52", - "name": "82c092e7-74c0-4e60-bd52-c9a6c9555060", - "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6", - }, { - "card_number": "3562-0140-8820-7499", - "email": "6174366e2bc6@59f82e89.93fc", - "name": "59f82e89-138e-4f9b-93fc-6174366e2bc6", - "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a", - }], - "errors": [] + "data": [ + { + "card_number": "3998-2139-0328-0697", + "email": "c9a6c9555060@82c092e7.bd52", + "name": "82c092e7-74c0-4e60-bd52-c9a6c9555060", + "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6" + }, + { + "card_number": "3562-0140-8820-7499", + "email": "6174366e2bc6@59f82e89.93fc", + "name": "59f82e89-138e-4f9b-93fc-6174366e2bc6", + "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a" + } + ], + "errors": [] } ``` ### Get By column name and column values -- +Retrieve records by unique column values. Ideal for querying data without knowing Skyflow IDs, using alternate unique identifiers. -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/GetExample.java) -of get call to retrieve data using column name and column values +An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/GetExample.java) of get call to retrieve data using column name and column values: ```java import com.skyflow.enums.RedactionType; @@ -1215,24 +1330,43 @@ import com.skyflow.vault.data.GetResponse; import java.util.ArrayList; +/** + * This example demonstrates how to retrieve data from the Skyflow vault based on column values. + * + * 1. Initializes the Skyflow client with a given vault ID. + * 2. Creates a request to retrieve records based on specific column values (e.g., email addresses). + * 3. Prints the response to display the retrieved records after redacting sensitive data based on the specified redaction type. + */ public class GetExample { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client + // Step 1: Initialize a list of column values (email addresses in this case) ArrayList columnValues = new ArrayList<>(); - columnValues.add("john.doe@gmail.com"); - columnValues.add("jane.doe@gmail.com"); + columnValues.add("john.doe@gmail.com"); // Example email address + columnValues.add("jane.doe@gmail.com"); // Example email address + + // Step 2: Create a GetRequest to retrieve records based on column values + // The request specifies: + // - `table`: The table from which the records will be retrieved + // - `columnName`: The column to filter the records by (e.g., "email") + // - `columnValues`: The list of values to match in the specified column + // - `redactionType`: Defines how sensitive data should be redacted (set to PLAIN_TEXT here) GetRequest getByColumnRequest = GetRequest.builder() - .table("table1") - .columnName("email") - .columnValues(columnValues) - .redactionType(RedactionType.PLAIN_TEXT) + .table("table1") // Replace with the actual table name + .columnName("email") // The column name to filter by (e.g., "email") + .columnValues(columnValues) // The list of column values to match + .redactionType(RedactionType.PLAIN_TEXT) // Set the redaction type (e.g., PLAIN_TEXT) .build(); - GetResponse getByColumnResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").get(getByColumnRequest); - System.out.println(getByColumnResponse); + + // Step 3: Send the request to the Skyflow vault and retrieve the records + GetResponse getByColumnResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").get(getByColumnRequest); // Replace with actual Vault ID + System.out.println(getByColumnResponse); // Print the response to the console + } catch (SkyflowException e) { + // Step 4: Handle any errors that occur during the data retrieval process System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception for debugging purposes } } } @@ -1240,31 +1374,42 @@ public class GetExample { Sample response: -```js +```json { - "data": [{ - "card_number": "4555555555555553", - "email": "john.doe@gmail.com", - "name": "john doe", - "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6", - }, { - "card_number": "4555555555555559", - "email": "jane.doe@gmail.com", - "name": "jane doe", - "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a", - }], - "errors": [] + "data": [ + { + "card_number": "4555555555555553", + "email": "john.doe@gmail.com", + "name": "john doe", + "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6" + }, + { + "card_number": "4555555555555559", + "email": "jane.doe@gmail.com", + "name": "jane doe", + "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a" + } + ], + "errors": [] } ``` ### Redaction types -There are four accepted values for RedactionType: +Redaction types determine how sensitive data is displayed when retrieved from the vault. + +#### **Available Redaction Types** -* `PLAIN_TEXT` -* `MASKED` -* `REDACTED` -* `DEFAULT` +- `DEFAULT`: Applies the vault-configured default redaction setting. +- `REDACTED`: Completely removes sensitive data from view. +- `MASKED`: Partially obscures sensitive information. +- `PLAIN_TEXT`: Displays the full, unmasked data. + +#### **Choosing the Right Redaction Type** + +- Use `REDACTED` for scenarios requiring maximum data protection to prevent exposure of sensitive information. +- Use `MASKED` to provide partial visibility of sensitive data for less critical use cases. +- Use `PLAIN_TEXT` for internal, authorized access where full data visibility is necessary. ## Update @@ -1273,7 +1418,7 @@ where you specify parameters such as the table name, data (as a map of key value tokenStrict. If `returnTokens` is set to `true`, Skyflow returns tokens for the updated records. If `returnTokens` is set to `false`, Skyflow returns IDs for the updated records. -Update Schema: +### Construct an update request ```java import com.skyflow.enums.TokenMode; @@ -1283,37 +1428,50 @@ import com.skyflow.vault.data.UpdateResponse; import java.util.HashMap; +/** + * This example demonstrates how to update records in the Skyflow vault by providing new data and/or tokenized values, along with corresponding UpdateRequest schema. + * + */ public class UpdateSchema { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client + // Step 1: Prepare the data to update in the vault + // Use a HashMap to store the data that will be updated in the specified table HashMap data = new HashMap<>(); - data.put("skyflow_id", ""); - data.put("", ""); - data.put("", ""); + data.put("skyflow_id", ""); // Skyflow ID for identifying the record to update + data.put("", ""); // Example of a column name and its value to update + data.put("", ""); // Another example of a column name and its value to update + // Step 2: Prepare the tokens (if necessary) for certain columns that require tokenization + // Use a HashMap to specify columns that need tokens in the update request HashMap tokens = new HashMap<>(); - tokens.put("", ""); + tokens.put("", ""); // Example of a column name that should be tokenized + // Step 3: Create an UpdateRequest to specify the update operation + // The request includes the table name, token mode, data, tokens, and the returnTokens flag UpdateRequest updateRequest = UpdateRequest.builder() - .table("") - .tokenMode(TokenMode.ENABLE) - .data(data) - .tokens(tokens) - .returnTokens(true) + .table("") // Replace with the actual table name to update + .tokenMode(TokenMode.ENABLE) // Specifies the tokenization mode (ENABLE means tokenization is applied) + .data(data) // The data to update in the record + .tokens(tokens) // The tokens associated with specific columns + .returnTokens(true) // Specify whether to return tokens in the response .build(); - UpdateResponse updateResponse = skyflowClient.vault("").update(updateRequest); - System.out.println(updateResponse); + + // Step 4: Send the request to the Skyflow vault and update the record + UpdateResponse updateResponse = skyflowClient.vault("").update(updateRequest); // Replace with actual Vault ID + System.out.println(updateResponse); // Print the response to confirm the update result + } catch (SkyflowException e) { + // Step 5: Handle any errors that occur during the update operation System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception for debugging purposes } } } ``` -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/UpdateExample.java) -of update call: +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/UpdateExample.java) of update call ```java import com.skyflow.enums.TokenMode; @@ -1323,29 +1481,47 @@ import com.skyflow.vault.data.UpdateResponse; import java.util.HashMap; +/** + * This example demonstrates how to update a record in the Skyflow vault with specified data and tokens. + * + * 1. Initializes the Skyflow client with a given vault ID. + * 2. Constructs an update request with data to modify and tokens to include. + * 3. Sends the request to update the record in the vault. + * 4. Prints the response to confirm the success or failure of the update operation. + */ public class UpdateExample { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client + // Step 1: Prepare the data to update in the vault + // A HashMap is used to store the data that will be updated in the specified table HashMap data = new HashMap<>(); - data.put("skyflow_id", "5b699e2c-4301-4f9f-bcff-0a8fd3057413"); - data.put("name", "john doe"); - data.put("card_number", "4111111111111115"); + data.put("skyflow_id", "5b699e2c-4301-4f9f-bcff-0a8fd3057413"); // Skyflow ID identifies the record to update + data.put("name", "john doe"); // Updating the "name" column with a new value + data.put("card_number", "4111111111111115"); // Updating the "card_number" column with a new value + // Step 2: Prepare the tokens to include in the update request + // Tokens can be included to update sensitive data with tokenized values HashMap tokens = new HashMap<>(); - tokens.put("name", "72b8ffe3-c8d3-4b4f-8052-38b2a7405b5a"); + tokens.put("name", "72b8ffe3-c8d3-4b4f-8052-38b2a7405b5a"); // Tokenized value for the "name" column + // Step 3: Create an UpdateRequest to define the update operation + // The request specifies the table name, token mode, data, and tokens for the update UpdateRequest updateRequest = UpdateRequest.builder() - .table("table1") - .tokenMode(TokenMode.ENABLE) - .data(data) - .tokens(tokens) + .table("table1") // Replace with the actual table name to update + .tokenMode(TokenMode.ENABLE) // Token mode enabled to allow tokenization of sensitive data + .data(data) // The data to update in the record + .tokens(tokens) // The tokenized values for sensitive columns .build(); - UpdateResponse updateResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").update(updateRequest); - System.out.println(updateResponse); + + // Step 4: Send the update request to the Skyflow vault + UpdateResponse updateResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").update(updateRequest); // Replace with your actual Vault ID + System.out.println(updateResponse); // Print the response to confirm the update result + } catch (SkyflowException e) { + // Step 5: Handle any exceptions that occur during the update operation System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception stack trace for debugging purposes } } } @@ -1353,9 +1529,9 @@ public class UpdateExample { Sample response: -- `returnTokens` set to `true` +- When `returnTokens` is set to `true` -```js +```json { "skyflowId": "5b699e2c-4301-4f9f-bcff-0a8fd3057413", "name": "72b8ffe3-c8d3-4b4f-8052-38b2a7405b5a", @@ -1363,9 +1539,9 @@ Sample response: } ``` -- `returnTokens` set to `false` +- When `returnTokens` is set to `false` -```js +```json { "skyflowId": "5b699e2c-4301-4f9f-bcff-0a8fd3057413" } @@ -1376,7 +1552,7 @@ Sample response: To delete records using Skyflow IDs, use the `delete` method. The `DeleteRequest` class accepts a list of Skyflow IDs that you want to delete, as shown below: -Delete schema: +### Construct a delete request ```java import com.skyflow.errors.SkyflowException; @@ -1385,27 +1561,42 @@ import com.skyflow.vault.data.DeleteResponse; import java.util.ArrayList; +/** + * This example demonstrates how to delete records from a Skyflow vault using specified Skyflow IDs, along with corresponding DeleteRequest schema. + * + */ public class DeleteSchema { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client + // Step 1: Prepare a list of Skyflow IDs for the records to delete + // The list stores the Skyflow IDs of the records that need to be deleted from the vault ArrayList ids = new ArrayList<>(); - ids.add(""); - ids.add(""); - ids.add(""); - DeleteRequest deleteRequest = DeleteRequest.builder().ids(ids).table("").build(); - DeleteResponse deleteResponse = skyflowClient.vault("").delete(deleteRequest); - System.out.println(deleteResponse); + ids.add(""); // Replace with actual Skyflow ID 1 + ids.add(""); // Replace with actual Skyflow ID 2 + ids.add(""); // Replace with actual Skyflow ID 3 + + // Step 2: Create a DeleteRequest to define the delete operation + // The request specifies the table from which to delete the records and the IDs of the records to delete + DeleteRequest deleteRequest = DeleteRequest.builder() + .ids(ids) // List of Skyflow IDs to delete + .table("") // Replace with the actual table name from which to delete + .build(); + + // Step 3: Send the delete request to the Skyflow vault + DeleteResponse deleteResponse = skyflowClient.vault("").delete(deleteRequest); // Replace with your actual Vault ID + System.out.println(deleteResponse); // Print the response to confirm the delete result + } catch (SkyflowException e) { + // Step 4: Handle any exceptions that occur during the delete operation System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception stack trace for debugging purposes } } } ``` -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/DeleteExample.java) -of delete call: +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/DeleteExample.java) of delete call: ```java import com.skyflow.errors.SkyflowException; @@ -1414,20 +1605,40 @@ import com.skyflow.vault.data.DeleteResponse; import java.util.ArrayList; +/** + * This example demonstrates how to delete records from a Skyflow vault using specified Skyflow IDs. + * + * 1. Initializes the Skyflow client with a given Vault ID. + * 2. Constructs a delete request by specifying the IDs of the records to delete. + * 3. Sends the delete request to the Skyflow vault to delete the specified records. + * 4. Prints the response to confirm the success or failure of the delete operation. + */ public class DeleteExample { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client + // Step 1: Prepare a list of Skyflow IDs for the records to delete + // The list stores the Skyflow IDs of the records that need to be deleted from the vault ArrayList ids = new ArrayList<>(); - ids.add("9cbf66df-6357-48f3-b77b-0f1acbb69280"); - ids.add("ea74bef4-f27e-46fe-b6a0-a28e91b4477b"); - ids.add("47700796-6d3b-4b54-9153-3973e281cafb"); - DeleteRequest deleteRequest = DeleteRequest.builder().ids(ids).table("table1").build(); - DeleteResponse deleteResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").delete(deleteRequest); - System.out.println(deleteResponse); + ids.add("9cbf66df-6357-48f3-b77b-0f1acbb69280"); // Replace with actual Skyflow ID 1 + ids.add("ea74bef4-f27e-46fe-b6a0-a28e91b4477b"); // Replace with actual Skyflow ID 2 + ids.add("47700796-6d3b-4b54-9153-3973e281cafb"); // Replace with actual Skyflow ID 3 + + // Step 2: Create a DeleteRequest to define the delete operation + // The request specifies the table from which to delete the records and the IDs of the records to delete + DeleteRequest deleteRequest = DeleteRequest.builder() + .ids(ids) // List of Skyflow IDs to delete + .table("table1") // Replace with the actual table name from which to delete + .build(); + + // Step 3: Send the delete request to the Skyflow vault + DeleteResponse deleteResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").delete(deleteRequest); // Replace with your actual Vault ID + System.out.println(deleteResponse); // Print the response to confirm the delete result + } catch (SkyflowException e) { + // Step 4: Handle any exceptions that occur during the delete operation System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception stack trace for debugging purposes } } } @@ -1445,57 +1656,85 @@ Sample response: } ``` -### Query +## Query -To retrieve data with SQL queries, use the `query` method. The `QueryRequest` class accepts a `query` parameter as -follows: +To retrieve data with SQL queries, use the `query` method. The `QueryRequest` class accepts a `query` parameter, as shown below. -Query Schema +### Construct a query request + +Refer to [Query your data](https://docs.skyflow.com/query-data/) and [Execute Query](https://docs.skyflow.com/record/#QueryService_ExecuteQuery) for guidelines and restrictions on supported SQL statements, operators, and keywords. ```java import com.skyflow.errors.SkyflowException; import com.skyflow.vault.data.QueryRequest; import com.skyflow.vault.data.QueryResponse; -public class QueryExample { +/** + * This example demonstrates how to execute a custom SQL query on a Skyflow vault, along with QueryRequest schema. + * + */ +public class QuerySchema { public static void main(String[] args) { try { - // initialize Skyflow client - String query = ""; - QueryRequest queryRequest = QueryRequest.builder().query(query).build(); - QueryResponse queryResponse = skyflowClient.vault("").query(queryRequest); - System.out.println(queryResponse); + // Initialize Skyflow client + // Step 1: Define the SQL query to execute on the Skyflow vault + // Replace "" with the actual SQL query you want to run + String query = ""; // Example: "SELECT * FROM table1 WHERE column1 = 'value'" + + // Step 2: Create a QueryRequest with the specified SQL query + QueryRequest queryRequest = QueryRequest.builder() + .query(query) // SQL query to execute + .build(); + + // Step 3: Execute the query request on the specified Skyflow vault + QueryResponse queryResponse = skyflowClient.vault("").query(queryRequest); // Replace with your actual Vault ID + System.out.println(queryResponse); // Print the response containing the query results + } catch (SkyflowException e) { + // Step 4: Handle any exceptions that occur during the query execution System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception stack trace for debugging } } } ``` -See [Query your data](https://docs.skyflow.com/query-data/) -and [Execute Query](https://docs.skyflow.com/record/#QueryService_ExecuteQuery) for guidelines and restrictions on -supported SQL statements, operators, and keywords. - -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/QueryExample.java) -of query call: +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/QueryExample.java) of query call ```java import com.skyflow.errors.SkyflowException; import com.skyflow.vault.data.QueryRequest; import com.skyflow.vault.data.QueryResponse; +/** + * This example demonstrates how to execute a SQL query on a Skyflow vault to retrieve data. + * + * 1. Initializes the Skyflow client with the Vault ID. + * 2. Constructs a query request with a specified SQL query. + * 3. Executes the query against the Skyflow vault. + * 4. Prints the response from the query execution. + */ public class QueryExample { public static void main(String[] args) { try { - // initialize Skyflow client + // Initialize Skyflow client + // Step 1: Define the SQL query + // Example query: Retrieve all records from the "cards" table with a specific skyflow_id String query = "SELECT * FROM cards WHERE skyflow_id='3ea3861-x107-40w8-la98-106sp08ea83f'"; - QueryRequest queryRequest = QueryRequest.builder().query(query).build(); - QueryResponse queryResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").query(queryRequest); - System.out.println(queryResponse); + + // Step 2: Create a QueryRequest with the SQL query + QueryRequest queryRequest = QueryRequest.builder() + .query(query) // SQL query to execute + .build(); + + // Step 3: Execute the query request on the specified Skyflow vault + QueryResponse queryResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").query(queryRequest); // Vault ID: 9f27764a10f7946fe56b3258e117 + System.out.println(queryResponse); // Print the query response (contains query results) + } catch (SkyflowException e) { + // Step 4: Handle any exceptions that occur during the query execution System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception stack trace for debugging } } } @@ -1503,28 +1742,31 @@ public class QueryExample { Sample response: -```js +```json { - "fields": [{ - "card_number": "XXXXXXXXXXXX1112", - "name": "S***ar", - "skyflow_id": "3ea3861-x107-40w8-la98-106sp08ea83f", - "tokenizedData": null - }] + "fields": [ + { + "card_number": "XXXXXXXXXXXX1112", + "name": "S***ar", + "skyflow_id": "3ea3861-x107-40w8-la98-106sp08ea83f", + "tokenizedData": null + } + ] } ``` # Connections -The [connections](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault/connection) -module is used to invoke INBOUND and/or OUTBOUND connections. +Skyflow Connections is a gateway service that uses tokenization to securely send and receive data between your systems and first- or third-party services. The [connections](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault/connection) module invokes both inbound and/or outbound connections. -## Invoke Connection +- **Inbound connections**: Act as intermediaries between your client and server, tokenizing sensitive data before it reaches your backend, ensuring downstream services handle only tokenized data. +- **Outbound connections**: Enable secure extraction of data from the vault and transfer it to third-party services via your backend server, such as processing checkout or card issuance flows. -Using Skyflow Connection, end-user applications can integrate checkout/card issuance flow with their apps/systems. To -invoke connection, use the `invoke` method of the Skyflow client. +## Invoke a connection -Invoke Connection Schema: +To invoke a connection, use the `invoke` method of the Skyflow client. + +### Construct an invoke connection request ```java import com.skyflow.enums.RequestMethod; @@ -1535,44 +1777,65 @@ import com.skyflow.vault.connection.InvokeConnectionResponse; import java.util.HashMap; import java.util.Map; +/** + * This example demonstrates how to invoke an external connection using the Skyflow SDK, along with corresponding InvokeConnectionRequest schema. + * + */ public class InvokeConnectionSchema { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client + // Step 1: Define the request body parameters + // These are the values you want to send in the request body Map requestBody = new HashMap<>(); requestBody.put("", ""); requestBody.put("", ""); + // Step 2: Define the request headers + // Add any required headers that need to be sent with the request Map requestHeaders = new HashMap<>(); requestHeaders.put("", ""); requestHeaders.put("", ""); + // Step 3: Define the path parameters + // Path parameters are part of the URL and typically used in RESTful APIs Map pathParams = new HashMap<>(); pathParams.put("", ""); pathParams.put("", ""); + // Step 4: Define the query parameters + // Query parameters are included in the URL after a '?' and are used to filter or modify the response Map queryParams = new HashMap<>(); queryParams.put("", ""); queryParams.put("", ""); + // Step 5: Build the InvokeConnectionRequest using the provided parameters InvokeConnectionRequest invokeConnectionRequest = InvokeConnectionRequest.builder() - .method(RequestMethod.POST) - .requestBody(requestBody) - .requestHeaders(requestHeaders) - .pathParams(pathParams) - .queryParams(queryParams) + .method(RequestMethod.POST) // The HTTP method to use for the request (POST in this case) + .requestBody(requestBody) // The body of the request + .requestHeaders(requestHeaders) // The headers to include in the request + .pathParams(pathParams) // The path parameters for the URL + .queryParams(queryParams) // The query parameters to append to the URL .build(); + + // Step 6: Invoke the connection using the request + // Replace "" with the actual connection ID you are using InvokeConnectionResponse invokeConnectionResponse = skyflowClient.connection("").invoke(invokeConnectionRequest); + + // Step 7: Print the response from the invoked connection + // This response contains the result of the request sent to the external system System.out.println(invokeConnectionResponse); + } catch (SkyflowException e) { + // Step 8: Handle any exceptions that occur during the connection invocation System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception stack trace for debugging } } } ``` -`methodName` supports the following methods: +`method` supports the following methods: - GET - POST @@ -1580,11 +1843,9 @@ public class InvokeConnectionSchema { - PATCH - DELETE -**pathParams, queryParams, requestHeader, requestBody** are the JSON objects represented as HashMaps, that will be sent -through the connection integration url. +**pathParams, queryParams, requestHeader, requestBody** are the JSON objects represented as HashMaps, that will be sent through the connection integration url. -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/connection/InvokeConnectionExample.java) -of invokeConnection: +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/connection/InvokeConnectionExample.java) of invokeConnection ```java import com.skyflow.Skyflow; @@ -1599,39 +1860,65 @@ import com.skyflow.vault.connection.InvokeConnectionResponse; import java.util.HashMap; import java.util.Map; +/** + * This example demonstrates how to invoke an external connection using the Skyflow SDK. + * It configures a connection, sets up the request, and sends a POST request to the external service. + * + * 1. Initialize Skyflow client with connection details. + * 2. Define the request body, headers, and method. + * 3. Execute the connection request. + * 4. Print the response from the invoked connection. + */ public class InvokeConnectionExample { public static void main(String[] args) { try { + // Initialize Skyflow client + // Step 1: Set up credentials and connection configuration + // Load credentials from a JSON file (you need to provide the correct path) Credentials credentials = new Credentials(); credentials.setPath("/path/to/credentials.json"); + // Define the connection configuration (URL and credentials) ConnectionConfig connectionConfig = new ConnectionConfig(); - connectionConfig.setConnectionId(""); - connectionConfig.setConnectionUrl("https://connection.url.com"); - connectionConfig.setCredentials(credentials); + connectionConfig.setConnectionId(""); // Replace with actual connection ID + connectionConfig.setConnectionUrl("https://connection.url.com"); // Replace with actual connection URL + connectionConfig.setCredentials(credentials); // Set credentials for the connection + // Initialize the Skyflow client with the connection configuration Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) - .addConnectionConfig(connectionConfig) - .build(); + .setLogLevel(LogLevel.DEBUG) // Set log level to DEBUG for detailed logs + .addConnectionConfig(connectionConfig) // Add connection configuration to client + .build(); // Build the Skyflow client instance + // Step 2: Define the request body and headers + // Map for request body parameters Map requestBody = new HashMap<>(); - requestBody.put("card_number", "4337-1696-5866-0865"); - requestBody.put("ssn", "524-41-4248"); + requestBody.put("card_number", "4337-1696-5866-0865"); // Example card number + requestBody.put("ssn", "524-41-4248"); // Example SSN + // Map for request headers Map requestHeaders = new HashMap<>(); - requestHeaders.put("Content-Type", "application/json"); + requestHeaders.put("Content-Type", "application/json"); // Set content type for the request + // Step 3: Build the InvokeConnectionRequest with required parameters + // Set HTTP method to POST, include the request body and headers InvokeConnectionRequest invokeConnectionRequest = InvokeConnectionRequest.builder() - .method(RequestMethod.POST) - .requestBody(requestBody) - .requestHeaders(requestHeaders) - .build(); + .method(RequestMethod.POST) // HTTP POST method + .requestBody(requestBody) // Add request body parameters + .requestHeaders(requestHeaders) // Add headers + .build(); // Build the request + + // Step 4: Invoke the connection and capture the response + // Replace "" with the actual connection ID InvokeConnectionResponse invokeConnectionResponse = skyflowClient.connection("").invoke(invokeConnectionRequest); - System.out.println(invokeConnectionResponse); + + // Step 5: Print the response from the connection invocation + System.out.println(invokeConnectionResponse); // Print the response to the console + } catch (SkyflowException e) { + // Step 6: Handle any exceptions that occur during the connection invocation System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); // Print the exception stack trace for debugging } } } @@ -1639,85 +1926,383 @@ public class InvokeConnectionExample { Sample response: -```js -InvokeConnectionResponse{ - response={ - "card_number":"4337-1696-5866-0865", - "ssn":"524-41-4248" +```json +{ + "data": { + "card_number": "4337-1696-5866-0865", + "ssn": "524-41-4248" + }, + "metadata": { + "requestId": "4a3453b5-7aa4-4373-98d7-cf102b1f6f97" + } } ``` -## Logging +# Authenticate with bearer tokens + +This section covers methods for generating and managing tokens to authenticate API calls: + +- **Generate a bearer token**: + Enable the creation of bearer tokens using service account credentials. These tokens, valid for 60 minutes, provide secure access to Vault services and management APIs based on the service account's permissions. Use this for general API calls when you only need basic authentication without additional context or role-based restrictions. +- **Generate a bearer token with context**: + Support embedding context values into bearer tokens, enabling dynamic access control and the ability to track end-user identity. These tokens include context claims and allow flexible authorization for Vault services. Use this when policies depend on specific contextual attributes or when tracking end-user identity is required. +- **Generate a scoped bearer token**: + Facilitate the creation of bearer tokens with role-specific access, ensuring permissions are limited to the operations allowed by the designated role. This is particularly useful for service accounts with multiple roles. Use this to enforce fine-grained role-based access control, ensuring tokens only grant permissions for a specific role. +- **Generate signed data tokens**: + Add an extra layer of security by digitally signing data tokens with the service account's private key. These signed tokens can be securely detokenized, provided the necessary bearer token and permissions are available. Use this to add cryptographic protection to sensitive data, enabling secure detokenization with verified integrity and authenticity. + +## Generate a bearer token -The skyflow java SDK provides useful logging using python's inbuilt `logging` library. By default, the logging level of -the SDK is set to `LogLevel.ERROR`. This can be changed by using `setLogLevel(logLevel)` method as shown below: +The [Service Account](https://github.com/skyflowapi/skyflow-java/tree/v2/src/main/java/com/skyflow/serviceaccount/util) Java module generates service account tokens using a service account credentials file, which is provided when a service account is created. The tokens generated by this module are valid for 60 minutes and can be used to make API calls to the [Data](https://docs.skyflow.com/record/) and [Management](https://docs.skyflow.com/management/) APIs, depending on the permissions assigned to the service account. + +The `BearerToken` utility class generates bearer tokens using a credentials JSON file. Alternatively, you can pass the credentials as a string. + +[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java): + +```java +/** + * Example program to generate a Bearer Token using Skyflow's BearerToken utility. + * The token can be generated in two ways: + * 1. Using the file path to a credentials.json file. + * 2. Using the JSON content of the credentials file as a string. + */ +public class BearerTokenGenerationExample { + public static void main(String[] args) { + // Variable to store the generated token + String token = null; + + // Example 1: Generate Bearer Token using a credentials.json file + try { + // Specify the full file path to the credentials.json file + String filePath = ""; + + // Check if the token is either not initialized or has expired + if (Token.isExpired(token)) { + // Create a BearerToken object using the credentials file + BearerToken bearerToken = BearerToken.builder() + .setCredentials(new File(filePath)) // Set credentials from the file path + .build(); + + // Generate a new Bearer Token + token = bearerToken.getBearerToken(); + } + + // Print the generated Bearer Token to the console + System.out.println("Generated Bearer Token (from file): " + token); + } catch (SkyflowException e) { + // Handle any exceptions encountered during the token generation process + e.printStackTrace(); + } + + // Example 2: Generate Bearer Token using the credentials JSON as a string + try { + // Provide the credentials JSON content as a string + String fileContents = ""; + + // Check if the token is either not initialized or has expired + if (Token.isExpired(token)) { + // Create a BearerToken object using the credentials string + BearerToken bearerToken = BearerToken.builder() + .setCredentials(fileContents) // Set credentials from the string + .build(); + + // Generate a new Bearer Token + token = bearerToken.getBearerToken(); + } + + // Print the generated Bearer Token to the console + System.out.println("Generated Bearer Token (from string): " + token); + } catch (SkyflowException e) { + // Handle any exceptions encountered during the token generation process + e.printStackTrace(); + } + } +} +``` + +## Generate bearer tokens with context + +**Context-aware authorization** embeds context values into a bearer token during its generation and so you can reference those values in your policies. This enables more flexible access controls, such as helping you track end-user identity when making API calls using service accounts, and facilitates using signed data tokens during detokenization. . + +A service account with the `context_id` identifier generates bearer tokens containing context information, represented as a JWT claim in a Skyflow-generated bearer token. Tokens generated from such service accounts include a `context_identifier` claim, are valid for 60 minutes, and can be used to make API calls to the Data and Management APIs, depending on the service account's permissions. + +[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java): ```java -import com.skyflow.Skyflow; -import com.skyflow.config.Credentials; -import com.skyflow.config.VaultConfig; -import com.skyflow.enums.Env; -import com.skyflow.enums.LogLevel; import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.BearerToken; -public class ChangeLogLevel { - public static void main(String[] args) throws SkyflowException { - // Pass only one of apiKey, token, credentialsString or path in credentials - Credentials credentials = new Credentials(); - credentials.setToken(""); +import java.io.File; - VaultConfig config = new VaultConfig(); - config.setVaultId(""); // Primary vault - config.setClusterId(""); // ID from your vault URL Eg https://{clusterId}.vault.skyflowapis.com - config.setEnv(Env.PROD); // Env by default is set to PROD - config.setCredentials(credentials); // Individual credentials +/** + * Example program to generate a Bearer Token using Skyflow's BearerToken utility. + * The token is generated using two approaches: + * 1. By providing the credentials.json file path. + * 2. By providing the contents of credentials.json as a string. + */ +public class BearerTokenGenerationWithContextExample { + public static void main(String[] args) { + // Variable to store the generated Bearer Token + String bearerToken = null; - JsonObject credentialsObject = new JsonObject(); - credentialsObject.addProperty("clientID", ""); - credentialsObject.addProperty("clientName", ""); - credentialsObject.addProperty("TokenURI", ""); - credentialsObject.addProperty("keyID", ""); - credentialsObject.addProperty("privateKey", ""); + // Approach 1: Generate Bearer Token by specifying the path to the credentials.json file + try { + // Replace with the full path to your credentials.json file + String filePath = ""; - // To generate Bearer Token from credentials string. - Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setCredentialsString(credentialsObject.toString()); + // Create a BearerToken object using the file path + BearerToken token = BearerToken.builder() + .setCredentials(new File(filePath)) // Set credentials using a File object + .setCtx("abc") // Set context string (example: "abc") + .build(); // Build the BearerToken object - Skyflow skyflowClient = Skyflow.builder() - .addVaultConfig(config) // Add vault config - .addSkyflowCredentials(skyflowCredentials) // Skyflow credentials will be used if no individual credentials are passed - .setLogLevel(LogLevel.INFO) // Set log level. By default, it is set to ERROR - .build(); + // Retrieve the Bearer Token as a string + bearerToken = token.getBearerToken(); + + // Print the generated Bearer Token to the console + System.out.println(bearerToken); + } catch (SkyflowException e) { + // Handle exceptions specific to Skyflow operations + e.printStackTrace(); + } + + // Approach 2: Generate Bearer Token by specifying the contents of credentials.json as a string + try { + // Replace with the actual contents of your credentials.json file + String fileContents = ""; + + // Create a BearerToken object using the file contents as a string + BearerToken token = BearerToken.builder() + .setCredentials(fileContents) // Set credentials using a string representation of the file + .setCtx("abc") // Set context string (example: "abc") + .build(); // Build the BearerToken object + + // Retrieve the Bearer Token as a string + bearerToken = token.getBearerToken(); + + // Print the generated Bearer Token to the console + System.out.println(bearerToken); + } catch (SkyflowException e) { + // Handle exceptions specific to Skyflow operations + e.printStackTrace(); + } + } +} +``` + +## Generate scoped bearer tokens + +A service account with multiple roles can generate bearer tokens with access limited to a specific role by specifying the appropriate `roleID`. This can be used to limit access to specific roles for services with multiple responsibilities, such as segregating access for billing and analytics. The generated bearer tokens are valid for 60 minutes and can only execute operations permitted by the permissions associated with the designated role. + +[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java): + +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.BearerToken; + +import java.io.File; +import java.util.ArrayList; + +/** + * Example program to generate a Scoped Token using Skyflow's BearerToken utility. + * The token is generated by providing the file path to the credentials.json file + * and specifying roles associated with the token. + */ +public class ScopedTokenGenerationExample { + public static void main(String[] args) { + // Variable to store the generated scoped token + String scopedToken = null; + + // Example: Generate Scoped Token by specifying the credentials.json file path + try { + // Create a list of roles that the generated token will be scoped to + ArrayList roles = new ArrayList<>(); + roles.add("ROLE_ID"); // Add a specific role to the list (e.g., "ROLE_ID") + + // Specify the full file path to the service account's credentials.json file + String filePath = ""; + + // Create a BearerToken object using the credentials file and associated roles + BearerToken bearerToken = BearerToken.builder() + .setCredentials(new File(filePath)) // Set credentials using the credentials.json file + .setRoles(roles) // Set the roles that the token should be scoped to + .build(); // Build the BearerToken object + + // Retrieve the generated scoped token + scopedToken = bearerToken.getBearerToken(); + + // Print the generated scoped token to the console + System.out.println(scopedToken); + } catch (SkyflowException e) { + // Handle exceptions that may occur during token generation + e.printStackTrace(); + } } } ``` -Currently, the following 5 log levels are supported: +Notes: + +- You can pass either the file path of a service account key credentials file or the service account key credentials as a string to the `setCredentials` method of the `BearerTokenBuilder` class. +- If both a file path and a string are provided, the last method used takes precedence. +- To generate multiple bearer tokens concurrently using threads, refer to the following [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java). + +## Signed Data Tokens Generation + +Skyflow generates data tokens when sensitive data is inserted into the vault. These data tokens can be digitally signed +with the private key of the service account credentials, which adds an additional layer of protection. Signed tokens can +be detokenized by passing the signed data token and a bearer token generated from service account credentials. The +service account must have appropriate permissions and context to detokenize the signed data tokens. + +[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java): + +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.SignedDataTokenResponse; +import com.skyflow.serviceaccount.util.SignedDataTokens; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +public class SignedTokenGenerationExample { + public static void main(String[] args) { + List signedTokenValues; + // Generate Signed data token with context by specifying credentials.json file path + try { + String filePath = ""; + String context = "abc"; + ArrayList dataTokens = new ArrayList<>(); + dataTokens.add("YOUR_DATA_TOKEN_1"); + SignedDataTokens signedToken = SignedDataTokens.builder() + .setCredentials(new File(filePath)) + .setCtx(context) + .setTimeToLive(30) // in seconds + .setDataTokens(dataTokens) + .build(); + signedTokenValues = signedToken.getSignedDataTokens(); + System.out.println(signedTokenValues); + } catch (SkyflowException e) { + e.printStackTrace(); + } + + // Generate Signed data token with context by specifying credentials.json as string + try { + String fileContents = ""; + String context = "abc"; + ArrayList dataTokens = new ArrayList<>(); + dataTokens.add("YOUR_DATA_TOKEN_1"); + SignedDataTokens signedToken = SignedDataTokens.builder() + .setCredentials(fileContents) + .setCtx(context) + .setTimeToLive(30) // in seconds + .setDataTokens(dataTokens) + .build(); + signedTokenValues = signedToken.getSignedDataTokens(); + System.out.println(signedTokenValues); + } catch (SkyflowException e) { + e.printStackTrace(); + } + } +} +``` -- `DEBUG`: +Response: - When `LogLevel.DEBUG` is passed, all level of logs will be printed(DEBUG, INFO, WARN, ERROR) +```json +[ + { + "dataToken": "5530-4316-0674-5748", + "signedDataToken": "signed_token_eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJzLCpZjA" + } +] +``` -- `INFO`: +Notes: - When `LogLevel.INFO` is passed, INFO logs for every event that has occurred during the SDK flow execution will be - printed along with WARN and ERROR logs +- You can provide either the file path to a service account key credentials file or the service account key credentials as a string to the `setCredentials` method of the `SignedDataTokensBuilder` class. +- If both a file path and a string are passed to the `setCredentials` method, the most recently specified input takes precedence. +- The `time-to-live` (TTL) value should be specified in seconds. +- By default, the TTL value is set to 60 seconds. -- `WARN`: +# Logging - When `LogLevel.WARN` is passed, WARN and ERROR logs will be printed +The SDK provides logging with Java's built-in logging library. By default, the SDK's logging level is set to `LogLevel.ERROR`. This can be changed using the `setLogLevel(logLevel)` method, as shown below: -- `ERROR`: +Currently, the following five log levels are supported: +- `DEBUG`**:** + When `LogLevel.DEBUG` is passed, logs at all levels will be printed (DEBUG, INFO, WARN, ERROR). +- `INFO`**:** + When `LogLevel.INFO` is passed, INFO logs for every event that occurs during SDK flow execution will be printed, along with WARN and ERROR logs. +- `WARN`**:** + When `LogLevel.WARN` is passed, only WARN and ERROR logs will be printed. +- `ERROR`**:** When `LogLevel.ERROR` is passed, only ERROR logs will be printed. +- `OFF`**:** + `LogLevel.OFF` can be used to turn off all logging from the Skyflow Java SDK. + +**Note:** The ranking of logging levels is as follows: `DEBUG` \< `INFO` \< `WARN` \< `ERROR` \< `OFF`. + +```java +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +/** + * This example demonstrates how to configure the Skyflow client with custom log levels + * and authentication credentials (either token, credentials string, or other methods). + * It also shows how to configure a vault connection using specific parameters. + * + * 1. Set up credentials with a Bearer token or credentials string. + * 2. Define the Vault configuration. + * 3. Build the Skyflow client with the chosen configuration and set log level. + * 4. Example of changing the log level from ERROR (default) to INFO. + */ +public class ChangeLogLevel { + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials - either pass token or use credentials string + // In this case, we are using a Bearer token for authentication + Credentials credentials = new Credentials(); + credentials.setToken(""); // Replace with actual Bearer token + + // Step 2: Define the Vault configuration + // Configure the vault with necessary details like vault ID, cluster ID, and environment + VaultConfig config = new VaultConfig(); + config.setVaultId(""); // Replace with actual Vault ID (primary vault) + config.setClusterId(""); // Replace with actual Cluster ID (from vault URL) + config.setEnv(Env.PROD); // Set the environment (default is PROD) + config.setCredentials(credentials); // Set credentials for the vault (either token or credentials) + + // Step 3: Define additional Skyflow credentials (optional, if needed for credentials string) + // Create a JSON object to hold your Skyflow credentials + JsonObject credentialsObject = new JsonObject(); + credentialsObject.addProperty("clientID", ""); // Replace with your client ID + credentialsObject.addProperty("clientName", ""); // Replace with your client name + credentialsObject.addProperty("TokenURI", ""); // Replace with your token URI + credentialsObject.addProperty("keyID", ""); // Replace with your key ID + credentialsObject.addProperty("privateKey", ""); // Replace with your private key -- `OFF`: + // Convert the credentials object to a string format to be used for generating a Bearer Token + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(credentialsObject.toString()); // Set credentials string - `LogLevel.OFF` can be used to turn off all logging from the skyflow-java SDK. + // Step 4: Build the Skyflow client with the chosen configuration and log level + Skyflow skyflowClient = Skyflow.builder() + .addVaultConfig(config) // Add the Vault configuration + .addSkyflowCredentials(skyflowCredentials) // Use Skyflow credentials if no token is passed + .setLogLevel(LogLevel.INFO) // Set log level to INFO (default is ERROR) + .build(); // Build the Skyflow client -`Note`: The ranking of logging levels is as follows : `DEBUG` < `INFO` < `WARN` < `ERROR`. + // Now, the Skyflow client is ready to use with the specified log level and credentials + System.out.println("Skyflow client has been successfully configured with log level: INFO."); + } +} +``` -## Reporting a Vulnerability +# Reporting a Vulnerability -If you discover a potential security issue in this project, please reach out to us at security@skyflow.com. Please do -not create public GitHub issues or Pull Requests, as malicious actors could potentially view them. +If you discover a potential security issue in this project, please reach out to us at **security@skyflow.com**. Please do not create public GitHub issues or Pull Requests, as malicious actors could potentially view them. From ce8278e3d54fca1bd63aa3b482dfe42964334384 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 14 Feb 2025 14:50:02 +0000 Subject: [PATCH 102/126] [AUTOMATED] Private Release 2.0.0-beta.1-dev-1284f08 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 99d337e7..6ba77d02 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0-dev.27ca248 + 2.0.0-beta.1-dev.1284f08 jar ${project.groupId}:${project.artifactId} From 0b69c49cceb37a45cb7233cd580bdcfddf57499c Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 17 Feb 2025 16:47:53 +0530 Subject: [PATCH 103/126] SK-1890 Add requestIds in response for continueOnError failures - Add requestId for detokenize failure responses when continueOnError is true - Add requestId for insert failure responses when continueOnError is true --- .../java/com/skyflow/utils/Constants.java | 1 + .../vault/controller/VaultController.java | 24 +++++++++++++------ .../tokens/DetokenizeRecordResponse.java | 10 ++++++++ .../com/skyflow/vault/data/InsertTests.java | 10 ++++++-- .../skyflow/vault/tokens/DetokenizeTests.java | 8 ++++--- 5 files changed, 41 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/skyflow/utils/Constants.java b/src/main/java/com/skyflow/utils/Constants.java index 3ce68c79..b0620609 100644 --- a/src/main/java/com/skyflow/utils/Constants.java +++ b/src/main/java/com/skyflow/utils/Constants.java @@ -24,4 +24,5 @@ public final class Constants { public static final String SDK_METRIC_RUNTIME_DETAILS_PREFIX = "Java@"; public static final String SDK_AUTH_HEADER_KEY = "x-skyflow-authorization"; public static final String SDK_METRICS_HEADER_KEY = "sky-metadata"; + public static final String REQUEST_ID_HEADER_KEY = "x-request-id"; } diff --git a/src/main/java/com/skyflow/vault/controller/VaultController.java b/src/main/java/com/skyflow/vault/controller/VaultController.java index 7744dfd8..f2130706 100644 --- a/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -7,9 +7,11 @@ import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.ApiException; +import com.skyflow.generated.rest.ApiResponse; import com.skyflow.generated.rest.models.*; import com.skyflow.logs.ErrorLogs; import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.Constants; import com.skyflow.utils.logger.LogUtil; import com.skyflow.utils.validations.Validations; import com.skyflow.vault.data.*; @@ -18,6 +20,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; public final class VaultController extends VaultClient { private static final Gson gson = new GsonBuilder().serializeNulls().create(); @@ -111,7 +114,7 @@ private static synchronized HashMap getFormattedQueryRecord(V1Fi public InsertResponse insert(InsertRequest insertRequest) throws SkyflowException { LogUtil.printInfoLog(InfoLogs.INSERT_TRIGGERED.getLog()); V1InsertRecordResponse bulkInsertResult = null; - V1BatchOperationResponse batchInsertResult = null; + ApiResponse batchInsertResult = null; ArrayList> insertedFields = new ArrayList<>(); ArrayList> errorFields = new ArrayList<>(); Boolean continueOnError = insertRequest.getContinueOnError(); @@ -121,15 +124,18 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio setBearerToken(); if (continueOnError) { RecordServiceBatchOperationBody insertBody = super.getBatchInsertRequestBody(insertRequest); - batchInsertResult = super.getRecordsApi().recordServiceBatchOperation(super.getVaultConfig().getVaultId(), insertBody); + batchInsertResult = super.getRecordsApi().recordServiceBatchOperationWithHttpInfo(super.getVaultConfig().getVaultId(), insertBody); LogUtil.printInfoLog(InfoLogs.INSERT_REQUEST_RESOLVED.getLog()); - List records = batchInsertResult.getResponses(); + Map> responseHeaders = batchInsertResult.getHeaders(); + String requestId = responseHeaders.get(Constants.REQUEST_ID_HEADER_KEY).get(0); + List records = batchInsertResult.getData().getResponses(); for (int index = 0; index < records.size(); index++) { Object record = records.get(index); HashMap insertRecord = getFormattedBatchInsertRecord(record, index); if (insertRecord.containsKey("skyflowId")) { insertedFields.add(insertRecord); } else { + insertRecord.put("requestId", requestId); errorFields.add(insertRecord); } } @@ -156,7 +162,7 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws SkyflowException { LogUtil.printInfoLog(InfoLogs.DETOKENIZE_TRIGGERED.getLog()); - V1DetokenizeResponse result = null; + ApiResponse result = null; ArrayList detokenizedFields = new ArrayList<>(); ArrayList errorRecords = new ArrayList<>(); try { @@ -164,15 +170,19 @@ public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws Validations.validateDetokenizeRequest(detokenizeRequest); setBearerToken(); V1DetokenizePayload payload = super.getDetokenizePayload(detokenizeRequest); - result = super.getTokensApi().recordServiceDetokenize(super.getVaultConfig().getVaultId(), payload); + result = super.getTokensApi().recordServiceDetokenizeWithHttpInfo(super.getVaultConfig().getVaultId(), payload); LogUtil.printInfoLog(InfoLogs.DETOKENIZE_REQUEST_RESOLVED.getLog()); - List records = result.getRecords(); + Map> responseHeaders = result.getHeaders(); + String requestId = responseHeaders.get(Constants.REQUEST_ID_HEADER_KEY).get(0); + List records = result.getData().getRecords(); + if (records != null) { for (V1DetokenizeRecordResponse record : records) { - DetokenizeRecordResponse recordResponse = new DetokenizeRecordResponse(record); if (record.getError() != null) { + DetokenizeRecordResponse recordResponse = new DetokenizeRecordResponse(record, requestId); errorRecords.add(recordResponse); } else { + DetokenizeRecordResponse recordResponse = new DetokenizeRecordResponse(record); detokenizedFields.add(recordResponse); } } diff --git a/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java index 198034a7..0904d6b6 100644 --- a/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java @@ -7,12 +7,18 @@ public class DetokenizeRecordResponse { private final String value; private final String type; private final String error; + private final String requestId; public DetokenizeRecordResponse(V1DetokenizeRecordResponse record) { + this(record, null); + } + + public DetokenizeRecordResponse(V1DetokenizeRecordResponse record, String requestId) { this.token = record.getToken(); this.value = record.getValue().isEmpty() ? null : record.getValue(); this.type = record.getValueType().getValue().equals("NONE") ? null : record.getValueType().getValue(); this.error = record.getError(); + this.requestId = requestId; } public String getError() { @@ -30,4 +36,8 @@ public String getValue() { public String getType() { return type; } + + public String getRequestId() { + return requestId; + } } \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/data/InsertTests.java b/src/test/java/com/skyflow/vault/data/InsertTests.java index 573ac5e4..00399f00 100644 --- a/src/test/java/com/skyflow/vault/data/InsertTests.java +++ b/src/test/java/com/skyflow/vault/data/InsertTests.java @@ -22,6 +22,7 @@ public class InsertTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static final String requestId = "95be08fc-4d13-4335-8b8d-24e85d53ed1d"; private static String vaultID = null; private static String clusterID = null; private static String table = null; @@ -408,6 +409,11 @@ public void testEmptyValueInTokensInInsertRequestValidations() { public void testInsertResponse() { try { ArrayList> errorFields = new ArrayList<>(); + HashMap error = new HashMap<>(); + error.put("requestIndex", 0); + error.put("requestId", requestId); + error.put("error", "Insert failed"); + errorFields.add(error); values.add(valueMap); values.add(valueMap); InsertResponse response = new InsertResponse(values, errorFields); @@ -416,9 +422,9 @@ public void testInsertResponse() { "\"test_column_2\":\"test_value_2\"}," + "{\"test_column_1\":\"test_value_1\"," + "\"test_column_2\":\"test_value_2\"}]" + - ",\"errors\":" + errorFields + "}"; + ",\"errors\":[{\"requestIndex\":0,\"requestId\":\"" + requestId + "\",\"error\":\"Insert failed\"}]}"; Assert.assertEquals(2, response.getInsertedFields().size()); - Assert.assertTrue(response.getErrors().isEmpty()); + Assert.assertEquals(1, response.getErrors().size()); Assert.assertEquals(responseString, response.toString()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); diff --git a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index aea06095..44bcf2a5 100644 --- a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -19,6 +19,7 @@ public class DetokenizeTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static final String requestId = "95be08fc-4d13-4335-8b8d-24e85d53ed1d"; private static ArrayList detokenizeData = null; private static DetokenizeData maskedRedactionRecord = null; private static DetokenizeData plainRedactionRecord = null; @@ -156,7 +157,7 @@ public void testDetokenizeResponse() { record2.setToken("3456-7890-1234-5678"); record2.setValue(""); record2.setError("Invalid token"); - DetokenizeRecordResponse error = new DetokenizeRecordResponse(record2); + DetokenizeRecordResponse error = new DetokenizeRecordResponse(record2, requestId); ArrayList fields = new ArrayList<>(); fields.add(field); @@ -170,14 +171,15 @@ public void testDetokenizeResponse() { String responseString = "{\"detokenizedFields\":[{" + "\"token\":\"1234-5678-9012-3456\",\"value\":\"4111111111111111\",\"type\":\"STRING\"}," + "{\"token\":\"1234-5678-9012-3456\",\"value\":\"4111111111111111\",\"type\":\"STRING\"}]," + - "\"errors\":[{\"token\":\"3456-7890-1234-5678\",\"error\":\"Invalid token\"}," + - "{\"token\":\"3456-7890-1234-5678\",\"error\":\"Invalid token\"}]}"; + "\"errors\":[{\"token\":\"3456-7890-1234-5678\",\"error\":\"Invalid token\",\"requestId\":\"" + requestId + "\"}," + + "{\"token\":\"3456-7890-1234-5678\",\"error\":\"Invalid token\",\"requestId\":\"" + requestId + "\"}]}"; Assert.assertEquals(2, response.getDetokenizedFields().size()); Assert.assertEquals(2, response.getErrors().size()); Assert.assertEquals("1234-5678-9012-3456", response.getDetokenizedFields().get(0).getToken()); Assert.assertEquals("4111111111111111", response.getDetokenizedFields().get(0).getValue()); Assert.assertEquals("STRING", response.getDetokenizedFields().get(0).getType()); Assert.assertEquals("Invalid token", response.getErrors().get(0).getError()); + Assert.assertEquals(requestId, response.getErrors().get(0).getRequestId()); Assert.assertEquals(responseString, response.toString()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); From ad0215a22588fde42e1286ebd46aa903fa17241d Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 20 Feb 2025 15:25:40 +0000 Subject: [PATCH 104/126] [AUTOMATED] Private Release 2.0.0-beta.1-dev-b6b25c8 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6ba77d02..21f3189b 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 2.0.0-beta.1-dev.1284f08 + 2.0.0-beta.1-dev.b6b25c8 jar ${project.groupId}:${project.artifactId} From 6b8c27da32c541c4e8bca46cf1e052293782e592 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 25 Feb 2025 13:57:47 +0530 Subject: [PATCH 105/126] SK-1900 Improve debugging errors in connections --- .../com/skyflow/errors/SkyflowException.java | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/skyflow/errors/SkyflowException.java b/src/main/java/com/skyflow/errors/SkyflowException.java index 1db1ed19..a455521d 100644 --- a/src/main/java/com/skyflow/errors/SkyflowException.java +++ b/src/main/java/com/skyflow/errors/SkyflowException.java @@ -41,10 +41,10 @@ public SkyflowException(int httpCode, Throwable cause, Map> super(cause); this.httpCode = httpCode; setRequestId(responseHeaders); - setResponseBody(responseBody); + setResponseBody(responseBody, responseHeaders); } - private void setResponseBody(String responseBody) { + private void setResponseBody(String responseBody, Map> responseHeaders) { try { if (responseBody != null) { this.responseBody = JsonParser.parseString(responseBody).getAsJsonObject(); @@ -52,7 +52,7 @@ private void setResponseBody(String responseBody) { setGrpcCode(); setHttpStatus(); setMessage(); - setDetails(); + setDetails(responseHeaders); } } } catch (JsonSyntaxException e) { @@ -86,9 +86,19 @@ private void setHttpStatus() { this.httpStatus = statusElement == null ? null : statusElement.getAsString(); } - private void setDetails() { + private void setDetails(Map> responseHeaders) { JsonElement detailsElement = ((JsonObject) responseBody.get("error")).get("details"); - this.details = detailsElement == null ? null : detailsElement.getAsJsonArray(); + List errorFromClientHeader = responseHeaders.get("error-from-client"); + if (detailsElement != null) { + this.details = detailsElement.getAsJsonArray(); + } + if (errorFromClientHeader != null) { + this.details = this.details == null ? new JsonArray() : this.details; + String errorFromClient = errorFromClientHeader.get(0); + JsonObject detailObject = new JsonObject(); + detailObject.addProperty("errorFromClient", errorFromClient); + this.details.add(detailObject); + } } public int getHttpCode() { From 0aaf4d246f7e9b32d3ca6af000b38a8ecfc053df Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 28 Feb 2025 05:46:36 +0000 Subject: [PATCH 106/126] [AUTOMATED] Private Release 2.0.0-beta.1-dev-ea71c1d --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 21f3189b..b3aa8170 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 2.0.0-beta.1-dev.b6b25c8 + 2.0.0-beta.1-dev.ea71c1d jar ${project.groupId}:${project.artifactId} From 9a4f0e6a9f48eb60490ee14531389e703dcdff0b Mon Sep 17 00:00:00 2001 From: skyflow-shravan <121150537+skyflow-shravan@users.noreply.github.com> Date: Thu, 16 Jan 2025 21:31:58 +0530 Subject: [PATCH 107/126] SK-1815 beta release for v2 (#153) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * SK-1663 Basic scaffolding and project structure for v2 * SK-1663 Worked on feedback for scaffolding * SK-1663 Moved main dir to src dir * SK-1663 Scaffolding for java sdk v2 - Renamed packages according to design doc for sdk v2 * SK-1663 Java sdk v2 scaffolding worked on feedback * SK-1663 Update method signatures for all controllers * SK-1663 Worked on feedback for java sdk v2 scafolding - SK-1677 Worked on client intialisation for Java SDK v2 * SK-1677 Delete old vault controller implementation * SK-1677 Client Initilisation and Credentials priorotisation * SK-1677 Client initilisation and credentials prioritisation * SK-1677 Used Constants instead of hard-coded strings * SK-1678 Bearer Token uitlities - Implemented bearer token utilities for generating bearer token with or without context and roles - Implemented Token utilties to check for validity of tokens - Implemented signed data tokens utilities to generate signed data tokens * SK-1665 Generate and integrate Data API code * SK-1664 Public interfaces for vault APIs - SK-1703 Implemented public interfaces for detokenize * SK-1701 Implemented public interfaces for insert vault API * SK-1703 Worked on feedback for Detokenize public interfaces * SK-1701 Worked on feedback for Insert public interfaces * SK-1702 Implement public interfaces for Get vault API * SK-1678 Replaced use of JSONObject with Gson JsonObject SK-1703 Abstracted constructor for Detokenize Request Builder * SK-1664 Implement vault API public interfaces - SK-1701 Modified insert public interfaces - SK-1702 Modified get public interfaces - SK-1704 Implemented update public interfaces * SK-1707 Implement Delete API public interfaces * SK-1705 Implement Query API public interfaces * SK-1664 implement tokenize api public interface * SK-1666 implement invoke connection public interface * SK-1701 Add continueOnError in insert vault API public interface * SK-1681 Add validations * SK-1681 add validations for tokenize request * SK-1666 validations for invoke connection request * SK-1664 move ColumnValue class to tokens package * SK-1664 Implement vault API interfaces - Change builder pattern implementation for vault API interfaces * SK-1682 add error codes, messages and logs * SK-1681 Add validations * SK-1678 Add support for using Api Key SK-1681 Add validations for Api Key * SK-1680 Implement logging SK-1723 Add error messages and codes * SK-1684 Add unit tests - Added unit tests for Detokenize request validations - Added unit tests for Insert request validations​ ​- Added unit tests for Get request validations​ ​- Added unit tests for Update request validations​ - Added unit tests for Delete request validations​ ​​- Added unit tests for Query request validations​ * SK-1680 Changed info logs to error logs in validation checks - SK-1681 Updated validation checks for Get request interface * SK-1684 Add unit tests - Add unit tests for configs i.e. vault, connection and credentials - Add unit tests for response pojo classes for few vault API interfaces * SK-1684 Add unit tests for bearer token utilities * SK-1684 Add unit tests for signed data tokens SK-1684 Add unit tests for Tokenize request validations * SK-1684 Add unit tests for Java SDK v2 * SK-1666 Fix conflicts and build issues after merge * SK-1684 Add unit tests for invoke connection SK-1766 Add validations for invoke connection interface SK-1766 Refactor code for invoke connection, removed unnecessary components for code optimisation * SK-1623 Java SDK v2 Removed v1,v2 modules and moved all v2 code directly to parent module Removed unnecessary dependencies * SK-1623 Downgrade dotenv to work with java 8 * SK-1767 Fix unit tests not running in CI pipeline * SK-1767 Add new secret for Java SDK v2 tests * SK-1767 Fix issues in CI pipeline * SK-1767 Fix compilation issues in CI pipeline - Excluding generating code from javadoc generation * SK-1682 Modified the structure of Skyflow error * SK-1623 Fix minor issues in Java SDK v2 * SK-1685 Add samples for Java SDK v2 - Added samples for vault API interfaces - Added sample for invoke connection interface * SK-1685 Add samples for Bearer token utilities * SK-1623 Fix minor issues in Javs SDK v2 * SK-1752 workflow for internal release * SK-1752 workflow for internal release * SK-1753 add create env step * SK-1753 auto generate release version in pom.xml * SK-1753 auto generate release version in pom.xml * SK-1753 auto generate release version in pom.xml * SK-1753 auto generate release version in pom.xml * SK-1753 auto generate release version in pom.xml * SK-1753 auto generate release version in pom.xml * SK-1753 auto generate release version in pom.xml * SK-1753 restore version in pom.xml * SK-1623 Fix typos in Samples * SK-1623 Worked on feedback for Update vault API interface * SK-1633 Upgraded dependency version * SK-1623 Made constructors for Bearer token utilities builders private * SK-1750 Rewrited README for SDK v2 * SK-1750 Change tokenStrict to tokenMode * SK-1790 Changed tokenStrict to tokenMode - Changed tokenStrict to tokenMode for insert and update requests. - Changed methodName to method for invoke connection request. - Changed enum Byot to TokenMode. * SK-1786 common workflow for internal and public release * SK-1789 common workflow for public and internal release v2 * SK-1786 test common workflow * SK-1786 modify scripts path in workflow * SK-1786 fix commit step * [AUTOMATED] Private Release 1.15.0-dev-f6c7f07 * SK-1786 include secrets from github * SK-1786 modify pattern in commit message check * [AUTOMATED] Private Release 1.15.0-dev-4ea53e6 * SK-1802 Fix inconsistencies in SDK v2 * SK-1802 Fix inconsistencies in SDK v2 - Fix inconsistency between vault and connection client - Added unit tests for vault and connection clients * SK-1802 Update examples and added unit tests * SK-1802 Renamed github secret * SK-1737 Fix inconsistencies in Java SDK * [AUTOMATED] Private Release 1.15.0-dev-8339ce7 * SK-1737 Update workflow to fix build issue * [AUTOMATED] Private Release 1.15.0-dev-f146b51 * SK-1737 add stack trace to debug failures * [AUTOMATED] Private Release 1.15.0-dev-ad9b710 * SK-1737 Fix spelling in error message * [AUTOMATED] Private Release 1.15.0-dev-d2e7155 * SK-1737 Added secrets for shared workflow * [AUTOMATED] Private Release 1.15.0-dev-a0537e8 * SK-1815 workflow for beta release (#152) * SK-1815 workflow for beta release * SK-1815 workflow for beta release * SK-1815 workflow for beta release * SK-1815 workflow for beta release * SK-1829/Release/25.1.1 (#155) * SK-1829 Fix http status for validation errors in Java SDK v2 * SK-1829 Fix errors in Invoke connection flow in Java SDK v2 * [AUTOMATED] Private Release 1.15.0-dev-27ca248 --------- Co-authored-by: skyflow-vivek --------- Co-authored-by: skyflow-vivek Co-authored-by: skyflow-vivek <121149418+skyflow-vivek@users.noreply.github.com> Co-authored-by: skyflow-shravan Co-authored-by: skyflow-vivek --- .github/workflows/shared-build-and-deploy.yml | 1 + README.md | 10 ++++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index 89332762..7fcbbce1 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -91,6 +91,7 @@ jobs: fi - name: Commit changes + if: ${{ inputs.tag == 'internal' || inputs.tag == 'public' }} run: | git config user.name ${{ github.actor }} git config user.email ${{ github.actor }}@users.noreply.github.com diff --git a/README.md b/README.md index 5ed7d604..c8229684 100644 --- a/README.md +++ b/README.md @@ -327,9 +327,9 @@ static class DemoTokenProvider implements TokenProvider { String filePath = ""; res = Token.generateBearerToken(filePath); } catch (SkyflowException e) { - e.printStackTrace(); + System.out.println("Error occurred: "); + System.out.println(e); } - return res.getAccessToken(); } } ``` @@ -642,6 +642,7 @@ public class InsertSchema { } } } + ``` Insert @@ -1266,7 +1267,7 @@ There are four accepted values for RedactionType: * `REDACTED` * `DEFAULT` -## Update +- `returnTokens` set to `false` To update data in your vault, use the `update` method. The `UpdateRequest` class is used to create an update request, where you specify parameters such as the table name, data (as a map of key value pairs), tokens, returnTokens, and @@ -1694,7 +1695,8 @@ public class ChangeLogLevel { Currently, the following 5 log levels are supported: -- `DEBUG`: + When `LogLevel.INFO` is passed, INFO logs for every event that has occurred during the SDK flow execution will be + printed along with WARN and ERROR logs When `LogLevel.DEBUG` is passed, all level of logs will be printed(DEBUG, INFO, WARN, ERROR) From 00ab0928e873772ce4b0cb5f3115ee299fc09a95 Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Thu, 16 Jan 2025 21:37:26 +0530 Subject: [PATCH 108/126] SK-1815 update beta version in pom xml --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 99d337e7..052dab76 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0-dev.27ca248 + 2.0.0-beta.1 jar ${project.groupId}:${project.artifactId} From a1b4e0e4385550769124c303b7e950f5b689732d Mon Sep 17 00:00:00 2001 From: skyflow-shravan Date: Fri, 17 Jan 2025 13:43:53 +0530 Subject: [PATCH 109/126] SK-1833 update samples --- .../com/example/connection/InvokeConnectionExample.java | 4 ++-- samples/src/main/java/com/example/vault/GetExample.java | 1 - samples/src/main/java/com/example/vault/InsertExample.java | 6 +++--- samples/src/main/java/com/example/vault/UpdateExample.java | 6 +++--- 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/samples/src/main/java/com/example/connection/InvokeConnectionExample.java b/samples/src/main/java/com/example/connection/InvokeConnectionExample.java index bae6a416..a730ca25 100644 --- a/samples/src/main/java/com/example/connection/InvokeConnectionExample.java +++ b/samples/src/main/java/com/example/connection/InvokeConnectionExample.java @@ -61,7 +61,7 @@ public static void main(String[] args) throws SkyflowException { // Build the POST request to invoke the connection InvokeConnectionRequest invokeConnectionRequest1 = InvokeConnectionRequest.builder() - .methodName(RequestMethod.POST) // Set the HTTP method to POST + .method(RequestMethod.POST) // Set the HTTP method to POST .requestBody(requestBody) // Set the request body .requestHeaders(requestHeaders) // Set the request headers .build(); @@ -87,7 +87,7 @@ public static void main(String[] args) throws SkyflowException { // Build the GET request to invoke the connection InvokeConnectionRequest invokeConnectionRequest2 = InvokeConnectionRequest.builder() - .methodName(RequestMethod.GET) // Set the HTTP method to GET + .method(RequestMethod.GET) // Set the HTTP method to GET .pathParams(pathParams) // Set the path parameters .queryParams(queryParams) // Set the query parameters .build(); diff --git a/samples/src/main/java/com/example/vault/GetExample.java b/samples/src/main/java/com/example/vault/GetExample.java index a25f580f..f964cfd2 100644 --- a/samples/src/main/java/com/example/vault/GetExample.java +++ b/samples/src/main/java/com/example/vault/GetExample.java @@ -56,7 +56,6 @@ public static void main(String[] args) throws SkyflowException { ids.add(""); // Replace with the Skyflow ID to fetch the record GetRequest getByIdRequest = GetRequest.builder() - .returnTokens(true) // Return tokens along with the fetched data .ids(ids) // Specify the list of Skyflow IDs .table("") // Replace with the table name .build(); diff --git a/samples/src/main/java/com/example/vault/InsertExample.java b/samples/src/main/java/com/example/vault/InsertExample.java index 3aa5309c..b84439f0 100644 --- a/samples/src/main/java/com/example/vault/InsertExample.java +++ b/samples/src/main/java/com/example/vault/InsertExample.java @@ -3,7 +3,7 @@ import com.skyflow.Skyflow; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.Byot; +import com.skyflow.enums.TokenMode; import com.skyflow.enums.Env; import com.skyflow.enums.LogLevel; import com.skyflow.errors.SkyflowException; @@ -68,7 +68,7 @@ public static void main(String[] args) throws SkyflowException { InsertRequest insertRequest = InsertRequest.builder() .table("") // Replace with the table name .continueOnError(true) // Continue inserting even if some records fail - .tokenStrict(Byot.ENABLE) // Enable BYOT for token validation + .tokenMode(TokenMode.ENABLE) // Enable BYOT for token validation .values(values1) // Data to insert .tokens(tokens) // Provide tokens for BYOT columns .returnTokens(true) // Return tokens along with the response @@ -92,7 +92,7 @@ public static void main(String[] args) throws SkyflowException { InsertRequest upsertRequest = InsertRequest.builder() .table("") // Replace with the table name .continueOnError(false) // Stop inserting if any record fails - .tokenStrict(Byot.DISABLE) // Disable BYOT + .tokenMode(TokenMode.DISABLE) // Disable BYOT .values(values2) // Data to insert .returnTokens(false) // Do not return tokens .upsert("") // Replace with the column name used for upsert logic diff --git a/samples/src/main/java/com/example/vault/UpdateExample.java b/samples/src/main/java/com/example/vault/UpdateExample.java index 1a220bb1..d69fbf6c 100644 --- a/samples/src/main/java/com/example/vault/UpdateExample.java +++ b/samples/src/main/java/com/example/vault/UpdateExample.java @@ -3,7 +3,7 @@ import com.skyflow.Skyflow; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.Byot; +import com.skyflow.enums.TokenMode; import com.skyflow.enums.Env; import com.skyflow.enums.LogLevel; import com.skyflow.errors.SkyflowException; @@ -62,7 +62,7 @@ public static void main(String[] args) throws SkyflowException { UpdateRequest updateRequest1 = UpdateRequest.builder() .table("") // Replace with the table name - .tokenStrict(Byot.ENABLE) // Enable BYOT for token validation + .tokenMode(TokenMode.ENABLE) // Enable BYOT for token validation .data(data1) // Data to update .tokens(tokens) // Provide tokens for BYOT columns .returnTokens(true) // Return tokens along with the update response @@ -84,7 +84,7 @@ public static void main(String[] args) throws SkyflowException { UpdateRequest updateRequest2 = UpdateRequest.builder() .table("") // Replace with the table name - .tokenStrict(Byot.DISABLE) // Disable BYOT + .tokenMode(TokenMode.DISABLE) // Disable BYOT .data(data2) // Data to update .returnTokens(false) // Do not return tokens .build(); From 8851d28582ae1080fa02a5bf2feabe397082d326 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 17 Mar 2025 21:04:10 +0530 Subject: [PATCH 110/126] SK-1959 Fix Java Samples --- .../connection/InvokeConnectionExample.java | 85 +++++++------ .../com/example/vault/ClientOperations.java | 95 ++++++++++++++ .../com/example/vault/CredentialsOptions.java | 84 +++++++++++++ .../java/com/example/vault/DeleteExample.java | 74 ++++------- .../com/example/vault/DetokenizeExample.java | 79 ++++-------- .../java/com/example/vault/GetExample.java | 35 +++--- .../java/com/example/vault/InsertExample.java | 75 +++++------ .../java/com/example/vault/QueryExample.java | 67 ++++------ .../com/example/vault/TokenizeExample.java | 116 ++++++------------ .../java/com/example/vault/UpdateExample.java | 82 ++++++------- 10 files changed, 413 insertions(+), 379 deletions(-) create mode 100644 samples/src/main/java/com/example/vault/ClientOperations.java create mode 100644 samples/src/main/java/com/example/vault/CredentialsOptions.java diff --git a/samples/src/main/java/com/example/connection/InvokeConnectionExample.java b/samples/src/main/java/com/example/connection/InvokeConnectionExample.java index a730ca25..b2e80924 100644 --- a/samples/src/main/java/com/example/connection/InvokeConnectionExample.java +++ b/samples/src/main/java/com/example/connection/InvokeConnectionExample.java @@ -13,92 +13,89 @@ import java.util.Map; /** - * This example demonstrates how to use the Skyflow SDK to invoke connections for different endpoints with different configurations. + * This example demonstrates how to use the Skyflow SDK to invoke API connections. * It includes: - * 1. Setting up connection configurations. - * 2. Creating a Skyflow client. - * 3. Sending POST and GET requests to connections. + * 1. Setting up credentials and connection configurations. + * 2. Creating a Skyflow client with multiple connections. + * 3. Sending a POST request with request body and headers. + * 4. Sending a GET request with path and query parameters. */ public class InvokeConnectionExample { public static void main(String[] args) throws SkyflowException { - // Step 1: Set up credentials for the first connection configuration + // Step 1: Set up credentials for API authentication Credentials credentials = new Credentials(); - credentials.setPath(""); // Replace with the path to the credentials file + credentials.setApiKey(""); // Replace with the actual API key - // Step 2: Configure the first connection (Connection 1) - ConnectionConfig connectionConfig1 = new ConnectionConfig(); - connectionConfig1.setConnectionId(""); // Replace with the ID of the first connection - connectionConfig1.setConnectionUrl(""); // Replace with the URL of the first connection - connectionConfig1.setCredentials(credentials); // Associate credentials for the first connection + // Step 2: Configure the first connection + ConnectionConfig primaryConnectionConfig = new ConnectionConfig(); + primaryConnectionConfig.setConnectionId(""); // Replace with first connection ID + primaryConnectionConfig.setConnectionUrl(""); // Replace with first connection URL + primaryConnectionConfig.setCredentials(credentials); // Assign credentials - // Step 3: Configure the second connection (Connection 2) - ConnectionConfig connectionConfig2 = new ConnectionConfig(); - connectionConfig2.setConnectionId(""); // Replace with the ID of the second connection - connectionConfig2.setConnectionUrl(""); // Replace with the URL of the second connection + // Step 3: Configure the second connection + ConnectionConfig secondaryConnectionConfig = new ConnectionConfig(); + secondaryConnectionConfig.setConnectionId(""); // Replace with second connection ID + secondaryConnectionConfig.setConnectionUrl(""); // Replace with second connection URL // Step 4: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); // Replace with the path to another credentials file + skyflowCredentials.setCredentialsString(""); // Replace with the credentials string - // Step 5: Create a Skyflow client and add connection configurations + // Step 5: Create a Skyflow client with connection configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs - .addConnectionConfig(connectionConfig1) // Add the first connection configuration - .addConnectionConfig(connectionConfig2) // Add the second connection configuration - .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR + .addConnectionConfig(primaryConnectionConfig) // Add the first connection + .addConnectionConfig(secondaryConnectionConfig) // Add the second connection + .addSkyflowCredentials(skyflowCredentials) // Provide Skyflow credentials .build(); // Example 1: Sending a POST request to the first connection try { - // Set up the request body and headers for the POST request + // Set up request body and headers Map requestBody = new HashMap<>(); - requestBody.put("", ""); // Replace with the actual column name and value + requestBody.put("", ""); // Replace with actual column name and value requestBody.put("", ""); // Replace with another column name and value Map requestHeaders = new HashMap<>(); - requestHeaders.put("", ""); // Replace with header name and value + requestHeaders.put("", ""); // Replace with actual header name and value requestHeaders.put("", ""); // Replace with another header name and value - // Build the POST request to invoke the connection + // Build and send the POST request InvokeConnectionRequest invokeConnectionRequest1 = InvokeConnectionRequest.builder() - .method(RequestMethod.POST) // Set the HTTP method to POST - .requestBody(requestBody) // Set the request body - .requestHeaders(requestHeaders) // Set the request headers + .method(RequestMethod.POST) // HTTP method set to POST + .requestBody(requestBody) // Include request body + .requestHeaders(requestHeaders) // Include request headers .build(); - // Execute the POST request to the first connection InvokeConnectionResponse invokeConnectionResponse1 = skyflowClient.connection().invoke(invokeConnectionRequest1); - System.out.println("Invoke Connection Response (POST): " + invokeConnectionResponse1); // Print the response + System.out.println("Invoke Connection Response (POST): " + invokeConnectionResponse1); } catch (SkyflowException e) { - System.out.println("Error while invoking connection (POST):"); - e.printStackTrace(); + System.out.println("Error while invoking connection (POST):" + e); } // Example 2: Sending a GET request to the second connection try { - // Set up path parameters and query parameters for the GET request + // Set up path and query parameters Map pathParams = new HashMap<>(); - pathParams.put("", ""); // Replace with path parameters + pathParams.put("", ""); // Replace with actual path parameter pathParams.put("", ""); // Replace with another path parameter Map queryParams = new HashMap<>(); - queryParams.put("", ""); // Replace with query parameters + queryParams.put("", ""); // Replace with actual query parameter queryParams.put("", ""); // Replace with another query parameter - // Build the GET request to invoke the connection + // Build and send the GET request InvokeConnectionRequest invokeConnectionRequest2 = InvokeConnectionRequest.builder() - .method(RequestMethod.GET) // Set the HTTP method to GET - .pathParams(pathParams) // Set the path parameters - .queryParams(queryParams) // Set the query parameters + .method(RequestMethod.GET) // HTTP method set to GET + .pathParams(pathParams) // Include path parameters + .queryParams(queryParams) // Include query parameters .build(); - // Execute the GET request to the second connection InvokeConnectionResponse invokeConnectionResponse2 = skyflowClient - .connection("").invoke(invokeConnectionRequest2); // Invoke connection with ID 2 - System.out.println("Invoke Connection Response (GET): " + invokeConnectionResponse2); // Print the response + .connection("").invoke(invokeConnectionRequest2); + System.out.println("Invoke Connection Response (GET): " + invokeConnectionResponse2); } catch (SkyflowException e) { - System.out.println("Error while invoking connection (GET):"); - e.printStackTrace(); + System.out.println("Error while invoking connection (GET):" + e); } } } diff --git a/samples/src/main/java/com/example/vault/ClientOperations.java b/samples/src/main/java/com/example/vault/ClientOperations.java new file mode 100644 index 00000000..7931db34 --- /dev/null +++ b/samples/src/main/java/com/example/vault/ClientOperations.java @@ -0,0 +1,95 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.DeleteRequest; +import com.skyflow.vault.data.DeleteResponse; + +import java.util.ArrayList; + +/** + * This class demonstrates how to configure and interact with Skyflow vaults using the Skyflow Java SDK. + *

+ * The operations performed in this class include: + * 1. Setting up authentication credentials. + * 2. Configuring a primary vault and initializing a Skyflow client. + * 3. Adding a secondary vault to the client. + * 4. Updating vault configuration. + * 5. Updating Skyflow API credentials dynamically. + * 6. Performing a secure deletion of a record in the secondary vault. + * 7. Removing the secondary vault configuration after the operation. + *

+ * This example illustrates how to securely manage and delete sensitive data using Skyflow. + */ +public class ClientOperations { + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up authentication credentials for accessing Skyflow vault + Credentials credentials = new Credentials(); + credentials.setToken(""); // Replace with the actual bearer token + // Alternative authentication methods include API key, credentials file path, or credentialsString + + // Step 2: Configure the primary vault with necessary identifiers and credentials + VaultConfig primaryVaultConfig = new VaultConfig(); + primaryVaultConfig.setVaultId(""); // Set first vault ID + primaryVaultConfig.setClusterId(""); // Set first cluster ID + primaryVaultConfig.setEnv(Env.PROD); // Define the environment (e.g., PROD, DEV, STAGE, SANDBOX) + primaryVaultConfig.setCredentials(credentials); // Attach authentication credentials + + // Step 3: Create a Skyflow client instance to interact with the vault + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Set logging level (ERROR to reduce verbosity) + .addVaultConfig(primaryVaultConfig) // Associate the primary vault configuration + .build(); // Build the Skyflow client instance + + // Step 4: Configure the secondary vault, which will be used later for deletion operations + VaultConfig secondaryVaultConfig = new VaultConfig(); + secondaryVaultConfig.setVaultId(""); // Set second vault ID + secondaryVaultConfig.setClusterId(""); // Set second cluster ID + secondaryVaultConfig.setEnv(Env.PROD); // Define the environment + + // Add the secondary vault configuration to the existing Skyflow client + skyflowClient.addVaultConfig(secondaryVaultConfig); + + // Step 5: Update the secondary vault configuration with credentials + VaultConfig updatedVaultConfig = new VaultConfig(); + updatedVaultConfig.setVaultId(""); // Ensure update applies to the correct vault + updatedVaultConfig.setClusterId(""); // Maintain correct cluster association + updatedVaultConfig.setCredentials(credentials); // Attach authentication credentials + + // Apply the updated vault configuration + skyflowClient.updateVaultConfig(updatedVaultConfig); + + // Step 6: Update Skyflow API credentials dynamically + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setApiKey(""); // Replace with the actual API key + + // Apply the updated credentials to the Skyflow client + skyflowClient.updateSkyflowCredentials(skyflowCredentials); // Used when individual credentials are not provided + + try { + // Step 7: Prepare a delete request to securely remove data from the secondary vault + ArrayList ids = new ArrayList<>(); + ids.add(""); // Replace with the actual ID of the record to delete + + DeleteRequest deleteRequest = DeleteRequest.builder() + .ids(ids) // Specify record IDs targeted for deletion + .table("") // Set the table name from which records should be deleted + .build(); + + // Step 8: Execute the secure delete operation on the secondary vault + DeleteResponse deleteResponse = skyflowClient.vault("").delete(deleteRequest); + System.out.println("Delete Response (Vault 2): " + deleteResponse); + + // Step 9: Remove the secondary vault configuration after the operation is completed + skyflowClient.removeVaultConfig(""); + + } catch (SkyflowException e) { + // Handle any errors that occur during the delete operation + System.out.println("Error during delete operation in vault 2: " + e); + } + } +} diff --git a/samples/src/main/java/com/example/vault/CredentialsOptions.java b/samples/src/main/java/com/example/vault/CredentialsOptions.java new file mode 100644 index 00000000..8a3ebc6a --- /dev/null +++ b/samples/src/main/java/com/example/vault/CredentialsOptions.java @@ -0,0 +1,84 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.DeleteRequest; +import com.skyflow.vault.data.DeleteResponse; + +import java.util.ArrayList; + +/** + * This class demonstrates multiple authentication methods and deletion operations across different Skyflow vaults. + *

+ * The operations performed in this class include: + * 1. Setting up authentication credentials with multiple options. + * 2. Configuring primary and secondary vaults. + * 3. Initializing a Skyflow client with multiple vault configurations. + * 4. Performing secure deletion of records from both vaults. + */ +public class CredentialsOptions { + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up authentication credentials using an API key + Credentials credentials = new Credentials(); + credentials.setApiKey(""); // Replace with your actual API key + + // Alternative authentication methods (uncomment if needed) + // credentials.setToken(""); + // credentials.setPath(""); + // credentials.setCredentialsString(""); + + // Step 2: Configure the primary vault + VaultConfig primaryVaultConfig = new VaultConfig(); + primaryVaultConfig.setVaultId(""); // Set first vault ID + primaryVaultConfig.setClusterId(""); // Set first cluster ID + primaryVaultConfig.setEnv(Env.PROD); // Define the environment (e.g., PROD, DEV, STAGE, SANDBOX) + + // Step 3: Configure the secondary vault with credentials + VaultConfig secondaryVaultConfig = new VaultConfig(); + secondaryVaultConfig.setVaultId(""); // Set second vault ID + secondaryVaultConfig.setClusterId(""); // Set second cluster ID + secondaryVaultConfig.setEnv(Env.PROD); // Define the environment + secondaryVaultConfig.setCredentials(credentials); // Attach authentication credentials + + // Step 4: Create a Skyflow client instance with both vault configurations + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Set logging level to ERROR + .addVaultConfig(primaryVaultConfig) // Associate the primary vault configuration + .addVaultConfig(secondaryVaultConfig) // Associate the secondary vault configuration + .build(); + + // Step 5: Perform secure deletion from the first vault + try { + ArrayList ids1 = new ArrayList<>(); + ids1.add(""); // Replace with the actual ID to delete + DeleteRequest deleteRequest1 = DeleteRequest.builder() + .ids(ids1) // Specify record IDs targeted for deletion + .table("") // Set the table name from which records should be deleted + .build(); + + DeleteResponse deleteResponse1 = skyflowClient.vault("").delete(deleteRequest1); + System.out.println("Delete Response (Vault 1): " + deleteResponse1); + } catch (SkyflowException e) { + System.out.println("Error during delete operation in Vault 1: " + e); + } + + // Step 6: Perform secure deletion from the second vault + try { + ArrayList ids2 = new ArrayList<>(); + ids2.add(""); // Replace with the actual ID to delete + DeleteRequest deleteRequest2 = DeleteRequest.builder() + .ids(ids2) // Specify record IDs targeted for deletion + .table("") // Set the table name from which records should be deleted + .build(); + + DeleteResponse deleteResponse2 = skyflowClient.vault("").delete(deleteRequest2); + System.out.println("Delete Response (Vault 2): " + deleteResponse2); + } catch (SkyflowException e) { + System.out.println("Error during delete operation in Vault 2: " + e); + } + } +} diff --git a/samples/src/main/java/com/example/vault/DeleteExample.java b/samples/src/main/java/com/example/vault/DeleteExample.java index bd6122cd..9fe41f61 100644 --- a/samples/src/main/java/com/example/vault/DeleteExample.java +++ b/samples/src/main/java/com/example/vault/DeleteExample.java @@ -16,71 +16,49 @@ * by specifying the vault configurations, credentials, and record IDs to delete. *

* Steps include: - * 1. Setting up vault configurations. - * 2. Creating a Skyflow client. - * 3. Deleting records from the specified vault(s) using record IDs and table names. + * 1. Setting up Skyflow credentials. + * 2. Configuring the vault. + * 3. Creating a Skyflow client. + * 4. Setting the log level for debugging and error tracking. + * 5. Deleting records from the specified vault(s) using record IDs and table names. */ public class DeleteExample { public static void main(String[] args) throws SkyflowException { - // Step 1: Set up credentials for the first vault configuration + // Step 1: Set up Skyflow credentials Credentials credentials = new Credentials(); - credentials.setPath(""); // Replace with the actual path to the credentials file + credentials.setPath(""); // Replace with the actual path to the credentials file - // Step 2: Configure the first vault (Blitz) - VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); // Replace with the ID of the first vault - blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault - blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) - blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 2: Configure the first vault + VaultConfig primaryVaultConfig = new VaultConfig(); + primaryVaultConfig.setVaultId(""); // Replace with the ID of the first vault + primaryVaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault + primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + primaryVaultConfig.setCredentials(credentials); // Associate the credentials with the vault - // Step 3: Configure the second vault (Stage) - VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); // Replace with the ID of the second vault - stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault - stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault - - // Step 4: Set up credentials for the Skyflow client + // Step 3: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); // Replace with the path to another credentials file + skyflowCredentials.setCredentialsString(""); // Replace with credentials string - // Step 5: Create a Skyflow client and add vault configurations + // Step 4: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs - .addVaultConfig(blitzConfig) // Add the first vault configuration - .addVaultConfig(stageConfig) // Add the second vault configuration + .setLogLevel(LogLevel.ERROR) // Set log level for debugging and error tracking + .addVaultConfig(primaryVaultConfig) // Add the first vault configuration .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - // Example 1: Delete a record from the first vault - try { - ArrayList ids1 = new ArrayList<>(); - ids1.add(""); // Replace with the ID of the record to delete - DeleteRequest deleteRequest1 = DeleteRequest.builder() - .ids(ids1) // Specify the record IDs to delete - .table("") // Replace with the table name - .build(); - - DeleteResponse deleteResponse1 = skyflowClient.vault().delete(deleteRequest1); // Perform the delete operation - System.out.println("Delete Response (Vault 1): " + deleteResponse1); - } catch (SkyflowException e) { - System.out.println("Error during delete operation in Vault 1:"); - e.printStackTrace(); - } - - // Example 2: Delete a record from the second vault + // Step 5: Delete a record from the first vault try { - ArrayList ids2 = new ArrayList<>(); - ids2.add(""); // Replace with the ID of the record to delete - DeleteRequest deleteRequest2 = DeleteRequest.builder() - .ids(ids2) // Specify the record IDs to delete + ArrayList ids = new ArrayList<>(); + ids.add(""); // Replace with the ID of the record to delete + DeleteRequest deleteRequest = DeleteRequest.builder() + .ids(ids) // Specify the record IDs to delete .table("") // Replace with the table name .build(); - DeleteResponse deleteResponse2 = skyflowClient.vault("").delete(deleteRequest2); // Perform the delete operation - System.out.println("Delete Response (Vault 2): " + deleteResponse2); + DeleteResponse deleteResponse = skyflowClient.vault().delete(deleteRequest); // Perform the delete operation + System.out.println("Delete Response: " + deleteResponse); } catch (SkyflowException e) { - System.out.println("Error during delete operation in Vault 2:"); - e.printStackTrace(); + System.out.println("Error during delete operation in Vault: " + e); } } } diff --git a/samples/src/main/java/com/example/vault/DetokenizeExample.java b/samples/src/main/java/com/example/vault/DetokenizeExample.java index f25d2be0..9a943dff 100644 --- a/samples/src/main/java/com/example/vault/DetokenizeExample.java +++ b/samples/src/main/java/com/example/vault/DetokenizeExample.java @@ -5,7 +5,6 @@ import com.skyflow.config.VaultConfig; import com.skyflow.enums.Env; import com.skyflow.enums.LogLevel; -import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.DetokenizeResponse; @@ -15,76 +14,50 @@ /** * This example demonstrates how to use the Skyflow SDK to detokenize sensitive data. * The steps include: - * 1. Setting up vault configurations. - * 2. Creating a Skyflow client. - * 3. Detokenizing tokens from specified vaults. + * 1. Setting up Skyflow credentials. + * 2. Configuring the vault. + * 3. Creating a Skyflow client. + * 4. Detokenizing tokens from specified vaults. */ public class DetokenizeExample { public static void main(String[] args) throws SkyflowException { - // Step 1: Set up credentials for the first vault configuration + // Step 1: Set up Skyflow credentials Credentials credentials = new Credentials(); - credentials.setPath(""); // Replace with the actual path to the credentials file + credentials.setToken(""); // Replace with the actual bearer token - // Step 2: Configure the first vault (Blitz) - VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); // Replace with the ID of the first vault - blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault - blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) - blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 2: Configure the first vault + VaultConfig primaryVaultConfig = new VaultConfig(); + primaryVaultConfig.setVaultId(""); // Replace with the ID of the first vault + primaryVaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault + primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + primaryVaultConfig.setCredentials(credentials); // Associate the credentials with the vault - // Step 3: Configure the second vault (Stage) - VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); // Replace with the ID of the second vault - stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault - stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault - - // Step 4: Set up credentials for the Skyflow client + // Step 3: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); // Replace with the path to another credentials file + skyflowCredentials.setCredentialsString(""); // Replace with credentials string - // Step 5: Create a Skyflow client and add vault configurations + // Step 4: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs - .addVaultConfig(blitzConfig) // Add the first vault configuration - .addVaultConfig(stageConfig) // Add the second vault configuration + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR to capture only critical logs + .addVaultConfig(primaryVaultConfig) // Add the first vault configuration .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - // Example 1: Detokenize tokens from the first vault + // Step 5: Detokenize tokens from the first vault try { - ArrayList tokens1 = new ArrayList<>(); - tokens1.add(""); // Replace with the first token to detokenize - tokens1.add(""); // Replace with the second token to detokenize + ArrayList tokens = new ArrayList<>(); + tokens.add(""); // Replace with the first token to detokenize + tokens.add(""); // Replace with the second token to detokenize - DetokenizeRequest detokenizeRequest1 = DetokenizeRequest.builder() - .tokens(tokens1) // Specify the tokens to detokenize + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .tokens(tokens) // Specify the tokens to detokenize .continueOnError(true) // Continue processing even if an error occurs for some tokens .build(); - DetokenizeResponse detokenizeResponse1 = skyflowClient.vault().detokenize(detokenizeRequest1); // Perform detokenization - System.out.println("Detokenize Response (Vault 1): " + detokenizeResponse1); - } catch (SkyflowException e) { - System.out.println("Error during detokenization in Vault 1:"); - e.printStackTrace(); - } - - // Example 2: Detokenize tokens from the second vault - try { - ArrayList tokens2 = new ArrayList<>(); - tokens2.add(""); // Replace with the first token to detokenize - tokens2.add(""); // Replace with the second token to detokenize - - DetokenizeRequest detokenizeRequest2 = DetokenizeRequest.builder() - .tokens(tokens2) // Specify the tokens to detokenize - .continueOnError(false) // Stop processing on the first error - .redactionType(RedactionType.DEFAULT) // Use the default redaction type for detokenization - .build(); - - DetokenizeResponse detokenizeResponse2 = skyflowClient.vault("").detokenize(detokenizeRequest2); // Perform detokenization - System.out.println("Detokenize Response (Vault 2): " + detokenizeResponse2); + DetokenizeResponse detokenizeResponse = skyflowClient.vault().detokenize(detokenizeRequest); // Perform detokenization + System.out.println("Detokenize Response: " + detokenizeResponse); } catch (SkyflowException e) { - System.out.println("Error during detokenization in Vault 2:"); - e.printStackTrace(); + System.out.println("Error during detokenization in Vault: " + e); } } } diff --git a/samples/src/main/java/com/example/vault/GetExample.java b/samples/src/main/java/com/example/vault/GetExample.java index f964cfd2..6d300752 100644 --- a/samples/src/main/java/com/example/vault/GetExample.java +++ b/samples/src/main/java/com/example/vault/GetExample.java @@ -23,30 +23,23 @@ public class GetExample { public static void main(String[] args) throws SkyflowException { // Step 1: Set up credentials for the first vault configuration Credentials credentials = new Credentials(); - credentials.setPath(""); // Replace with the actual path to the credentials file + credentials.setCredentialsString(""); // Replace with the actual credentials string - // Step 2: Configure the first vault (Blitz) - VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); // Replace with the ID of the first vault - blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault - blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) - blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 2: Configure the first vault + VaultConfig primaryVaultConfig = new VaultConfig(); + primaryVaultConfig.setVaultId(""); // Replace with the ID of the first vault + primaryVaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault + primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + primaryVaultConfig.setCredentials(credentials); // Associate the credentials with the vault - // Step 3: Configure the second vault (Stage) - VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); // Replace with the ID of the second vault - stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault - stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault - - // Step 4: Set up credentials for the Skyflow client + // Step 3: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); // Replace with the path to another credentials file + skyflowCredentials.setCredentialsString(""); // Replace with another credentials string - // Step 5: Create a Skyflow client and add vault configurations + // Step 4: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs - .addVaultConfig(blitzConfig) // Add the first vault configuration - .addVaultConfig(stageConfig) // Add the second vault configuration + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR to minimize log output + .addVaultConfig(primaryVaultConfig) // Add the first vault configuration .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); @@ -60,7 +53,7 @@ public static void main(String[] args) throws SkyflowException { .table("") // Replace with the table name .build(); - GetResponse getByIdResponse = skyflowClient.vault().get(getByIdRequest); // Perform the get operation + GetResponse getByIdResponse = skyflowClient.vault().get(getByIdRequest); // Fetch via skyflow IDs System.out.println("Get Response (By ID): " + getByIdResponse); } catch (SkyflowException e) { System.out.println("Error during fetch by ID:"); @@ -79,7 +72,7 @@ public static void main(String[] args) throws SkyflowException { .redactionType(RedactionType.PLAIN_TEXT) // Fetch the data in plain text format .build(); - GetResponse getByColumnResponse = skyflowClient.vault("").get(getByColumnRequest); // Fetch from the second vault + GetResponse getByColumnResponse = skyflowClient.vault().get(getByColumnRequest); // Fetch via column values System.out.println("Get Response (By Column): " + getByColumnResponse); } catch (SkyflowException e) { System.out.println("Error during fetch by column:"); diff --git a/samples/src/main/java/com/example/vault/InsertExample.java b/samples/src/main/java/com/example/vault/InsertExample.java index b84439f0..25610b2b 100644 --- a/samples/src/main/java/com/example/vault/InsertExample.java +++ b/samples/src/main/java/com/example/vault/InsertExample.java @@ -3,9 +3,9 @@ import com.skyflow.Skyflow; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.TokenMode; import com.skyflow.enums.Env; import com.skyflow.enums.LogLevel; +import com.skyflow.enums.TokenMode; import com.skyflow.errors.SkyflowException; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.InsertResponse; @@ -18,91 +18,82 @@ * It includes: * 1. Setting up vault configurations. * 2. Creating a Skyflow client. - * 3. Performing record insertion with and without BYOT (Bring Your Own Token). + * 3. Performing record insertion with and without TokenMode. * 4. Using upsert functionality to handle conflicts. */ public class InsertExample { public static void main(String[] args) throws SkyflowException { // Step 1: Set up credentials for the first vault configuration Credentials credentials = new Credentials(); - credentials.setPath(""); // Replace with the path to the credentials file - - // Step 2: Configure the first vault (Blitz) - VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); // Replace with the ID of the first vault - blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault - blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) - blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + credentials.setApiKey(""); // Replace with the actual API key - // Step 3: Configure the second vault (Stage) - VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); // Replace with the ID of the second vault - stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault - stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault + // Step 2: Configure the first vault + VaultConfig primaryVaultConfig = new VaultConfig(); + primaryVaultConfig.setVaultId(""); // Replace with the first vault ID + primaryVaultConfig.setClusterId(""); // Replace with the first vault cluster ID + primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, SANDBOX) + primaryVaultConfig.setCredentials(credentials); // Associate credentials with the vault - // Step 4: Set up credentials for the Skyflow client + // Step 3: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); // Replace with the path to another credentials file + skyflowCredentials.setCredentialsString(""); // Replace with the actual credentials string - // Step 5: Create a Skyflow client and add vault configurations + // Step 4: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs - .addVaultConfig(blitzConfig) // Add the first vault configuration - .addVaultConfig(stageConfig) // Add the second vault configuration + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR to limit output + .addVaultConfig(primaryVaultConfig) // Add the vault configuration .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - // Example 1: Insert records into the first vault with BYOT enabled + // Example 1: Insert records into the first vault with TokenMode enabled try { ArrayList> values1 = new ArrayList<>(); HashMap value1 = new HashMap<>(); - value1.put("", ""); // Replace with column name and value - value1.put("", ""); // Replace with another column name and value + value1.put("", ""); // Replace with actual column name and value + value1.put("", ""); // Replace with actual column name and value values1.add(value1); ArrayList> tokens = new ArrayList<>(); HashMap token = new HashMap<>(); - token.put("", ""); // Replace with the token for COLUMN_NAME_2 + token.put("", ""); // Replace with actual token value for COLUMN_NAME_2 tokens.add(token); InsertRequest insertRequest = InsertRequest.builder() - .table("") // Replace with the table name + .table("") // Replace with the actual table name .continueOnError(true) // Continue inserting even if some records fail - .tokenMode(TokenMode.ENABLE) // Enable BYOT for token validation + .tokenMode(TokenMode.ENABLE) // Enable TokenMode for token validation .values(values1) // Data to insert - .tokens(tokens) // Provide tokens for BYOT columns - .returnTokens(true) // Return tokens along with the response + .tokens(tokens) // Provide tokens for TokenMode columns + .returnTokens(true) // Return tokens in the response .build(); InsertResponse insertResponse = skyflowClient.vault().insert(insertRequest); // Perform the insertion - System.out.println("Insert Response (BYOT Enabled): " + insertResponse); + System.out.println("Insert Response (TokenMode Enabled): " + insertResponse); } catch (SkyflowException e) { - System.out.println("Error during insertion with BYOT enabled:"); - e.printStackTrace(); + System.out.println("Error during insertion with TokenMode enabled:" + e); } - // Example 2: Insert records into the second vault with BYOT disabled and upsert enabled + // Example 2: Insert records into the first vault with TokenMode disabled and upsert enabled try { ArrayList> values2 = new ArrayList<>(); HashMap value2 = new HashMap<>(); - value2.put("", ""); // Replace with column name and value - value2.put("", ""); // Replace with another column name and value + value2.put("", ""); // Replace with actual column name and value + value2.put("", ""); // Replace with actual column name and value values2.add(value2); InsertRequest upsertRequest = InsertRequest.builder() - .table("") // Replace with the table name + .table("") // Replace with the actual table name .continueOnError(false) // Stop inserting if any record fails - .tokenMode(TokenMode.DISABLE) // Disable BYOT + .tokenMode(TokenMode.DISABLE) // Disable TokenMode .values(values2) // Data to insert .returnTokens(false) // Do not return tokens - .upsert("") // Replace with the column name used for upsert logic + .upsert("") // Replace with the actual column name used for upsert logic .build(); - InsertResponse upsertResponse = skyflowClient.vault("").insert(upsertRequest); // Perform the insertion + InsertResponse upsertResponse = skyflowClient.vault().insert(upsertRequest); // Perform upsert operation System.out.println("Insert Response (Upsert Enabled): " + upsertResponse); } catch (SkyflowException e) { - System.out.println("Error during insertion with upsert enabled:"); - e.printStackTrace(); + System.out.println("Error during insertion with upsert enabled:" + e); } } -} +} \ No newline at end of file diff --git a/samples/src/main/java/com/example/vault/QueryExample.java b/samples/src/main/java/com/example/vault/QueryExample.java index 43f42a82..bde5c697 100644 --- a/samples/src/main/java/com/example/vault/QueryExample.java +++ b/samples/src/main/java/com/example/vault/QueryExample.java @@ -10,70 +10,47 @@ import com.skyflow.vault.data.QueryResponse; /** - * This example demonstrates how to use the Skyflow SDK to perform secure queries on multiple vaults. + * This example demonstrates how to use the Skyflow SDK to perform secure queries on a vault. * It includes: * 1. Setting up vault configurations. * 2. Creating a Skyflow client. - * 3. Performing SQL queries on the vaults. + * 3. Performing SQL queries on the vault. */ public class QueryExample { public static void main(String[] args) throws SkyflowException { - // Step 1: Set up credentials for the first vault configuration + // Step 1: Set up credentials for the vault configuration Credentials credentials = new Credentials(); - credentials.setPath(""); // Replace with the path to the credentials file + credentials.setApiKey(""); // Replace with the actual API key - // Step 2: Configure the first vault (Blitz) - VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); // Replace with the ID of the first vault - blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault - blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) - blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the ID of the vault + vaultConfig.setClusterId(""); // Replace with the cluster ID of the vault + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate the credentials with the vault - // Step 3: Configure the second vault (Stage) - VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); // Replace with the ID of the second vault - stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault - stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault - - // Step 4: Set up credentials for the Skyflow client + // Step 3: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); // Replace with the path to another credentials file + skyflowCredentials.setCredentialsString(""); // Replace with the actual credentials string - // Step 5: Create a Skyflow client and add vault configurations + // Step 4: Create a Skyflow client and add vault configuration Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs - .addVaultConfig(blitzConfig) // Add the first vault configuration - .addVaultConfig(stageConfig) // Add the second vault configuration + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR for minimal logging + .addVaultConfig(vaultConfig) // Add the vault configuration .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - // Example 1: Perform a query on the first vault - try { - String query1 = ""; // Replace with a valid SQL query for the first vault - QueryRequest queryRequest1 = QueryRequest.builder() - .query(query1) // Build the query request - .build(); - - QueryResponse queryResponse1 = skyflowClient.vault().query(queryRequest1); // Execute the query - System.out.println("Query Response (Vault 1): " + queryResponse1); // Print the query response - } catch (SkyflowException e) { - System.out.println("Error while querying Vault 1:"); - e.printStackTrace(); - } - - // Example 2: Perform a query on the second vault + // Example: Perform a query on the vault try { - String query2 = ""; // Replace with a valid SQL query for the second vault - QueryRequest queryRequest2 = QueryRequest.builder() - .query(query2) // Build the query request + String query = ""; // Replace with a valid SQL query for the vault + QueryRequest queryRequest = QueryRequest.builder() + .query(query) // Build the query request .build(); - QueryResponse queryResponse2 = skyflowClient.vault("").query(queryRequest2); // Execute the query - System.out.println("Query Response (Vault 2): " + queryResponse2); // Print the query response + QueryResponse queryResponse = skyflowClient.vault().query(queryRequest); // Execute the query + System.out.println("Query Response: " + queryResponse); // Print the query response } catch (SkyflowException e) { - System.out.println("Error while querying Vault 2:"); - e.printStackTrace(); + System.out.println("Error while querying the vault: " + e); } } } - diff --git a/samples/src/main/java/com/example/vault/TokenizeExample.java b/samples/src/main/java/com/example/vault/TokenizeExample.java index 38bd806b..2c390be8 100644 --- a/samples/src/main/java/com/example/vault/TokenizeExample.java +++ b/samples/src/main/java/com/example/vault/TokenizeExample.java @@ -13,97 +13,51 @@ import java.util.ArrayList; /** - * This example demonstrates how to use the Skyflow SDK to tokenize data using multiple vault configurations. + * This example demonstrates how to use the Skyflow SDK to tokenize data using a vault configuration. * It includes: - * 1. Setting up vault configurations. + * 1. Setting up a vault configuration. * 2. Creating a Skyflow client. - * 3. Performing tokenization on the vaults. + * 3. Performing tokenization. */ public class TokenizeExample { - public static void main(String[] args) throws SkyflowException { - // Step 1: Set up credentials for the first vault configuration - Credentials credentials = new Credentials(); - credentials.setPath(""); // Replace with the path to the credentials file - - // Step 2: Configure the first vault (Blitz) - VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); // Replace with the ID of the first vault - blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault - blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) - blitzConfig.setCredentials(credentials); // Associate the credentials with the vault - - // Step 3: Configure the second vault (Stage) - VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); // Replace with the ID of the second vault - stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault - stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault - - // Step 4: Set up credentials for the Skyflow client - Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); // Replace with the path to another credentials file - - // Step 5: Create a Skyflow client and add vault configurations - Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs - .addVaultConfig(blitzConfig) // Add the first vault configuration - .addVaultConfig(stageConfig) // Add the second vault configuration - .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials - .build(); - - // Example 1: Tokenize data for the first vault + public static void main(String[] args) { try { - ArrayList columnValues1 = new ArrayList<>(); - ColumnValue value1 = ColumnValue.builder() - .value("") // Replace with the actual value to tokenize - .columnGroup("") // Replace with the actual column group name + // Step 1: Set up credentials + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the vault ID + vaultConfig.setClusterId(""); // Replace with the cluster ID + vaultConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate credentials with the vault + + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(""); // Replace with the actual credentials string + + // Step 3: Create a Skyflow client + Skyflow skyflowClient = Skyflow.builder().setLogLevel(LogLevel.ERROR) // Set log level + .addVaultConfig(vaultConfig) // Add vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - ColumnValue value2 = ColumnValue.builder() - .value("") // Replace with another value to tokenize - .columnGroup("") // Replace with the column group name - .build(); - - columnValues1.add(value1); - columnValues1.add(value2); - // Build the tokenization request - TokenizeRequest tokenizeRequest1 = TokenizeRequest.builder() - .values(columnValues1) // Set the column values to tokenize - .build(); + // Step 4: Prepare data for tokenization + ArrayList columnValues = new ArrayList<>(); + columnValues.add(ColumnValue.builder().value("") // Replace with the actual value to tokenize + .columnGroup("") // Replace with the actual column group name + .build()); + columnValues.add(ColumnValue.builder().value("") // Replace with another value to tokenize + .columnGroup("") // Replace with the column group name + .build()); - // Execute tokenization request - TokenizeResponse tokenizeResponse1 = skyflowClient.vault().tokenize(tokenizeRequest1); - System.out.println("Tokenization Response (Vault 1): " + tokenizeResponse1); // Print the tokenization response - } catch (SkyflowException e) { - System.out.println("Error while tokenizing data for Vault 1:"); - e.printStackTrace(); - } - - // Example 2: Tokenize data for the second vault - try { - ArrayList columnValues2 = new ArrayList<>(); - ColumnValue value3 = ColumnValue.builder() - .value("") // Replace with the actual value to tokenize - .columnGroup("") // Replace with the column group name - .build(); - ColumnValue value4 = ColumnValue.builder() - .value("") // Replace with another value to tokenize - .columnGroup("") // Replace with the column group name - .build(); - - columnValues2.add(value3); - columnValues2.add(value4); - - // Build the tokenization request for the second vault - TokenizeRequest tokenizeRequest2 = TokenizeRequest.builder() - .values(columnValues2) // Set the column values to tokenize - .build(); + // Step 5: Build and execute the tokenization request + TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); - // Execute tokenization request for the second vault - TokenizeResponse tokenizeResponse2 = skyflowClient.vault("").tokenize(tokenizeRequest2); - System.out.println("Tokenization Response (Vault 2): " + tokenizeResponse2); // Print the tokenization response + TokenizeResponse tokenizeResponse = skyflowClient.vault().tokenize(tokenizeRequest); + System.out.println("Tokenization Response: " + tokenizeResponse); } catch (SkyflowException e) { - System.out.println("Error while tokenizing data for Vault 2:"); - e.printStackTrace(); + System.out.println("Error while tokenizing data for Vault:" + e); } } } diff --git a/samples/src/main/java/com/example/vault/UpdateExample.java b/samples/src/main/java/com/example/vault/UpdateExample.java index d69fbf6c..d5c5ed02 100644 --- a/samples/src/main/java/com/example/vault/UpdateExample.java +++ b/samples/src/main/java/com/example/vault/UpdateExample.java @@ -3,9 +3,9 @@ import com.skyflow.Skyflow; import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.TokenMode; import com.skyflow.enums.Env; import com.skyflow.enums.LogLevel; +import com.skyflow.enums.TokenMode; import com.skyflow.errors.SkyflowException; import com.skyflow.vault.data.UpdateRequest; import com.skyflow.vault.data.UpdateResponse; @@ -17,83 +17,75 @@ * It includes: * 1. Setting up vault configurations. * 2. Creating a Skyflow client. - * 3. Updating records using different configurations and data. + * 3. Updating records with and without TokenMode. */ public class UpdateExample { public static void main(String[] args) throws SkyflowException { // Step 1: Set up credentials for the first vault configuration Credentials credentials = new Credentials(); - credentials.setPath(""); // Replace with the actual path to the credentials file + credentials.setApiKey(""); // Replace with the actual API key - // Step 2: Configure the first vault (Blitz) - VaultConfig blitzConfig = new VaultConfig(); - blitzConfig.setVaultId(""); // Replace with the ID of the first vault - blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault - blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) - blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 2: Configure the first vault + VaultConfig primaryVaultConfig = new VaultConfig(); + primaryVaultConfig.setVaultId(""); // Replace with the ID of the first vault + primaryVaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault + primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + primaryVaultConfig.setCredentials(credentials); // Associate the credentials with the vault - // Step 3: Configure the second vault (Stage) - VaultConfig stageConfig = new VaultConfig(); - stageConfig.setVaultId(""); // Replace with the ID of the second vault - stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault - stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault - - // Step 4: Set up credentials for the Skyflow client + // Step 3: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); - skyflowCredentials.setPath(""); // Replace with the path to another credentials file + skyflowCredentials.setCredentialsString(""); // Replace with the actual credentials string - // Step 5: Create a Skyflow client and add vault configurations + // Step 4: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs - .addVaultConfig(blitzConfig) // Add the first vault configuration - .addVaultConfig(stageConfig) // Add the second vault configuration + .setLogLevel(LogLevel.ERROR) // Enable debugging for detailed logs + .addVaultConfig(primaryVaultConfig) // Add the first vault configuration .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - // Example 1: Update records in the first vault with BYOT (Bring Your Own Token) enabled + // Step 5: Update records with TokenMode enabled try { HashMap data1 = new HashMap<>(); - data1.put("skyflow_id", ""); // Replace with the Skyflow ID of the record - data1.put("", ""); // Replace with column name and value to update - data1.put("", ""); // Replace with another column name and value + data1.put("skyflow_id", ""); // Replace with the Skyflow ID of the record + data1.put("", ""); // Replace with column name and value to update + data1.put("", ""); // Replace with another column name and value HashMap tokens = new HashMap<>(); - tokens.put("", ""); // Replace with the token for COLUMN_NAME_2 + tokens.put("", ""); // Replace with the token for COLUMN_NAME_2 UpdateRequest updateRequest1 = UpdateRequest.builder() - .table("") // Replace with the table name - .tokenMode(TokenMode.ENABLE) // Enable BYOT for token validation - .data(data1) // Data to update - .tokens(tokens) // Provide tokens for BYOT columns - .returnTokens(true) // Return tokens along with the update response + .table("") // Replace with the table name + .tokenMode(TokenMode.ENABLE) // Enable TokenMode for token validation + .data(data1) // Data to update + .tokens(tokens) // Provide tokens for TokenMode columns + .returnTokens(true) // Return tokens along with the update response .build(); UpdateResponse updateResponse1 = skyflowClient.vault().update(updateRequest1); // Perform the update - System.out.println("Update Response (BYOT Enabled): " + updateResponse1); + System.out.println("Update Response (TokenMode Enabled): " + updateResponse1); } catch (SkyflowException e) { - System.out.println("Error during update with BYOT enabled:"); + System.out.println("Error during update with TokenMode enabled:"); e.printStackTrace(); } - // Example 2: Update records in the second vault with BYOT disabled + // Step 6: Update records with TokenMode disabled try { HashMap data2 = new HashMap<>(); - data2.put("skyflow_id", ""); // Replace with the Skyflow ID of the record - data2.put("", ""); // Replace with column name and value to update - data2.put("", ""); // Replace with another column name and value + data2.put("skyflow_id", ""); // Replace with the Skyflow ID of the record + data2.put("", ""); // Replace with column name and value to update + data2.put("", ""); // Replace with another column name and value UpdateRequest updateRequest2 = UpdateRequest.builder() - .table("") // Replace with the table name - .tokenMode(TokenMode.DISABLE) // Disable BYOT - .data(data2) // Data to update - .returnTokens(false) // Do not return tokens + .table("") // Replace with the table name + .tokenMode(TokenMode.DISABLE) // Disable TokenMode + .data(data2) // Data to update + .returnTokens(false) // Do not return tokens .build(); - UpdateResponse updateResponse2 = skyflowClient.vault("").update(updateRequest2); // Perform the update - System.out.println("Update Response (BYOT Disabled): " + updateResponse2); + UpdateResponse updateResponse2 = skyflowClient.vault().update(updateRequest2); // Perform the update + System.out.println("Update Response (TokenMode Disabled): " + updateResponse2); } catch (SkyflowException e) { - System.out.println("Error during update with BYOT disabled:"); - e.printStackTrace(); + System.out.println("Error during update with TokenMode disabled:" + e); } } } From b0658dc9f0122c4fe86976c380bcdb23a87561d2 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 19 Mar 2025 16:57:22 +0530 Subject: [PATCH 111/126] SK-1959 Fix README after rebase --- README.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c8229684..5ed7d604 100644 --- a/README.md +++ b/README.md @@ -327,9 +327,9 @@ static class DemoTokenProvider implements TokenProvider { String filePath = ""; res = Token.generateBearerToken(filePath); } catch (SkyflowException e) { - System.out.println("Error occurred: "); - System.out.println(e); + e.printStackTrace(); } + return res.getAccessToken(); } } ``` @@ -642,7 +642,6 @@ public class InsertSchema { } } } - ``` Insert @@ -1267,7 +1266,7 @@ There are four accepted values for RedactionType: * `REDACTED` * `DEFAULT` -- `returnTokens` set to `false` +## Update To update data in your vault, use the `update` method. The `UpdateRequest` class is used to create an update request, where you specify parameters such as the table name, data (as a map of key value pairs), tokens, returnTokens, and @@ -1695,8 +1694,7 @@ public class ChangeLogLevel { Currently, the following 5 log levels are supported: - When `LogLevel.INFO` is passed, INFO logs for every event that has occurred during the SDK flow execution will be - printed along with WARN and ERROR logs +- `DEBUG`: When `LogLevel.DEBUG` is passed, all level of logs will be printed(DEBUG, INFO, WARN, ERROR) From 57f888b0d12ed966c9bcff4a321c5e691f0ad76c Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 19 Mar 2025 18:13:15 +0530 Subject: [PATCH 112/126] SK-1959 Fix workflow after rebase --- .github/workflows/shared-build-and-deploy.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index 7fcbbce1..89332762 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -91,7 +91,6 @@ jobs: fi - name: Commit changes - if: ${{ inputs.tag == 'internal' || inputs.tag == 'public' }} run: | git config user.name ${{ github.actor }} git config user.email ${{ github.actor }}@users.noreply.github.com From 694e7732616c5bbdb208b4a8b0f0558c75654b06 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Wed, 26 Mar 2025 14:09:01 +0530 Subject: [PATCH 113/126] SK-1969 Fix error handling for certain scenarios --- .../java/com/skyflow/errors/ErrorMessage.java | 26 ++++---- .../com/skyflow/errors/SkyflowException.java | 61 ++++++++++--------- .../java/com/skyflow/utils/Constants.java | 1 + 3 files changed, 47 insertions(+), 41 deletions(-) diff --git a/src/main/java/com/skyflow/errors/ErrorMessage.java b/src/main/java/com/skyflow/errors/ErrorMessage.java index da992da2..33833443 100644 --- a/src/main/java/com/skyflow/errors/ErrorMessage.java +++ b/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -3,27 +3,27 @@ import com.skyflow.utils.Constants; public enum ErrorMessage { - // client initialization + // Client initialization VaultIdAlreadyInConfigList("%s0 Validation error. VaultId is present in an existing config. Specify a new vaultId in config."), VaultIdNotInConfigList("%s0 Validation error. VaultId is missing from the config. Specify the vaultIds from configs."), ConnectionIdAlreadyInConfigList("%s0 Validation error. ConnectionId is present in an existing config. Specify a connectionId in config."), ConnectionIdNotInConfigList("%s0 Validation error. ConnectionId is missing from the config. Specify the connectionIds from configs."), EmptyCredentials("%s0 Validation error. Invalid credentials. Credentials must not be empty."), - // vault config + // Vault config InvalidVaultId("%s0 Initialization failed. Invalid vault ID. Specify a valid vault ID."), EmptyVaultId("%s0 Initialization failed. Invalid vault ID. Vault ID must not be empty."), InvalidClusterId("%s0 Initialization failed. Invalid cluster ID. Specify cluster ID."), EmptyClusterId("%s0 Initialization failed. Invalid cluster ID. Specify a valid cluster ID."), - // connection config + // Connection config InvalidConnectionId("%s0 Initialization failed. Invalid connection ID. Specify a valid connection ID."), EmptyConnectionId("%s0 Initialization failed. Invalid connection ID. Connection ID must not be empty."), InvalidConnectionUrl("%s0 Initialization failed. Invalid connection URL. Specify a valid connection URL."), EmptyConnectionUrl("%s0 Initialization failed. Invalid connection URL. Connection URL must not be empty."), InvalidConnectionUrlFormat("%s0 Initialization failed. Connection URL is not a valid URL. Specify a valid connection URL."), - // credentials + // Credentials MultipleTokenGenerationMeansPassed("%s0 Initialization failed. Invalid credentials. Specify only one from 'path', 'credentialsString', 'token' or 'apiKey'."), NoTokenGenerationMeansPassed("%s0 Initialization failed. Invalid credentials. Specify any one from 'path', 'credentialsString', 'token' or 'apiKey'."), EmptyCredentialFilePath("%s0 Initialization failed. Invalid credentials. Credentials file path must not be empty."), @@ -35,7 +35,7 @@ public enum ErrorMessage { EmptyRoleInRoles("%s0 Initialization failed. Invalid role. Specify a valid role."), EmptyContext("%s0 Initialization failed. Invalid context. Specify a valid context."), - // bearer token generation + // Bearer token generation FileNotFound("%s0 Initialization failed. Credential file not found at %s1. Verify the file path."), FileInvalidJson("%s0 Initialization failed. File at %s1 is not in valid JSON format. Verify the file contents."), CredentialsStringInvalidJson("%s0 Initialization failed. Credentials string is not in valid JSON format. Verify the credentials string contents."), @@ -52,7 +52,7 @@ public enum ErrorMessage { MissingAccessToken("%s0 Validation error. Access token not present in the response from bearer token generation. Verify your credentials."), MissingTokenType("%s0 Validation error. Token type not present in the response from bearer token generation. Verify your credentials."), - // insert + // Insert TableKeyError("%s0 Validation error. 'table' key is missing from the payload. Specify a 'table' key."), EmptyTable("%s0 Validation error. 'table' can't be empty. Specify a table."), ValuesKeyError("%s0 Validation error. 'values' key is missing from the payload. Specify a 'values' key."), @@ -72,12 +72,12 @@ public enum ErrorMessage { BatchInsertPartialSuccess("%s0 Insert operation completed with partial success."), BatchInsertFailure("%s0 Insert operation failed."), - // detokenize + // Detokenize InvalidDetokenizeData("%s0 Validation error. Invalid detokenize data. Specify valid detokenize data."), EmptyDetokenizeData("%s0 Validation error. Invalid data tokens. Specify at least one data token."), EmptyTokenInDetokenizeData("%s0 Validation error. Invalid data tokens. Specify a valid data token."), - // get interface + // Get IdsKeyError("%s0 Validation error. 'ids' key is missing from the payload. Specify an 'ids' key."), EmptyIds("%s0 Validation error. 'ids' can't be empty. Specify at least one id."), EmptyIdInIds("%s0 Validation error. Invalid id in 'ids'. Specify a valid id."), @@ -99,22 +99,22 @@ public enum ErrorMessage { TokenKeyError("%s0 Validation error. 'token' key is missing from the payload. Specify a 'token' key."), PartialSuccess("%s0 Validation error. Check 'SkyflowError.data' for details."), - // update + // Update DataKeyError("%s0 Validation error. 'data' key is missing from the payload. Specify a 'data' key."), EmptyData("%s0 Validation error. 'data' can't be empty. Specify data."), SkyflowIdKeyError("%s0 Validation error. 'skyflow_id' is missing from the data payload. Specify a 'skyflow_id'."), InvalidSkyflowIdType("%s0 Validation error. Invalid type for 'skyflow_id' in data payload. Specify 'skyflow_id' as a string."), EmptySkyflowId("%s0 Validation error. 'skyflow_id' can't be empty. Specify a skyflow id."), - // query + // Query QueryKeyError("%s0 Validation error. 'query' key is missing from the payload. Specify a 'query' key."), EmptyQuery("%s0 Validation error. 'query' can't be empty. Specify a query"), - // tokenize + // Tokenize ColumnValuesKeyErrorTokenize("%s0 Validation error. 'columnValues' key is missing from the payload. Specify a 'columnValues' key."), EmptyColumnGroupInColumnValue("%s0 Validation error. Invalid column group in column value. Specify a valid column group."), - // connection + // Connection InvalidRequestHeaders("%s0 Validation error. Request headers aren't valid. Specify valid request headers."), EmptyRequestHeaders("%s0 Validation error. Request headers are empty. Specify valid request headers."), InvalidPathParams("%s0 Validation error. Path parameters aren't valid. Specify valid path parameters."), @@ -124,6 +124,8 @@ public enum ErrorMessage { InvalidRequestBody("%s0 Validation error. Invalid request body. Specify the request body as an object."), EmptyRequestBody("%s0 Validation error. Request body can't be empty. Specify a valid request body."), + // Generic + ErrorOccurred("%s0 API error. Error occurred.") ; private final String message; diff --git a/src/main/java/com/skyflow/errors/SkyflowException.java b/src/main/java/com/skyflow/errors/SkyflowException.java index a455521d..32c71f39 100644 --- a/src/main/java/com/skyflow/errors/SkyflowException.java +++ b/src/main/java/com/skyflow/errors/SkyflowException.java @@ -1,6 +1,10 @@ package com.skyflow.errors; -import com.google.gson.*; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.skyflow.utils.Constants; import java.util.List; import java.util.Map; @@ -39,24 +43,25 @@ public SkyflowException(int code, String message) { public SkyflowException(int httpCode, Throwable cause, Map> responseHeaders, String responseBody) { super(cause); - this.httpCode = httpCode; - setRequestId(responseHeaders); - setResponseBody(responseBody, responseHeaders); + this.httpCode = httpCode > 0 ? httpCode : 400; + try { + setRequestId(responseHeaders); + setResponseBody(responseBody, responseHeaders); + } catch (Exception e) { + this.httpStatus = HttpStatus.BAD_REQUEST.getHttpStatus(); + String fullMessage = responseBody != null ? responseBody : + (cause.getLocalizedMessage() != null ? cause.getMessage() : ErrorMessage.ErrorOccurred.getMessage()); + this.message = fullMessage.split("HTTP response code:")[0].trim(); + } } private void setResponseBody(String responseBody, Map> responseHeaders) { - try { - if (responseBody != null) { - this.responseBody = JsonParser.parseString(responseBody).getAsJsonObject(); - if (this.responseBody.get("error") != null) { - setGrpcCode(); - setHttpStatus(); - setMessage(); - setDetails(responseHeaders); - } - } - } catch (JsonSyntaxException e) { - throw new RuntimeException(e); + this.responseBody = JsonParser.parseString(responseBody).getAsJsonObject(); + if (this.responseBody.get("error") != null) { + setGrpcCode(); + setHttpStatus(); + setMessage(); + setDetails(responseHeaders); } } @@ -65,10 +70,8 @@ public String getRequestId() { } private void setRequestId(Map> responseHeaders) { - if (responseHeaders != null) { - List ids = responseHeaders.get("x-request-id"); - this.requestId = ids == null ? null : ids.get(0); - } + List ids = responseHeaders.get(Constants.REQUEST_ID_HEADER_KEY); + this.requestId = ids == null ? null : ids.get(0); } private void setMessage() { @@ -86,9 +89,17 @@ private void setHttpStatus() { this.httpStatus = statusElement == null ? null : statusElement.getAsString(); } + public int getHttpCode() { + return httpCode; + } + + public JsonArray getDetails() { + return details; + } + private void setDetails(Map> responseHeaders) { JsonElement detailsElement = ((JsonObject) responseBody.get("error")).get("details"); - List errorFromClientHeader = responseHeaders.get("error-from-client"); + List errorFromClientHeader = responseHeaders.get(Constants.ERROR_FROM_CLIENT_HEADER_KEY); if (detailsElement != null) { this.details = detailsElement.getAsJsonArray(); } @@ -101,14 +112,6 @@ private void setDetails(Map> responseHeaders) { } } - public int getHttpCode() { - return httpCode; - } - - public JsonArray getDetails() { - return details; - } - public Integer getGrpcCode() { return grpcCode; } diff --git a/src/main/java/com/skyflow/utils/Constants.java b/src/main/java/com/skyflow/utils/Constants.java index b0620609..500d8c94 100644 --- a/src/main/java/com/skyflow/utils/Constants.java +++ b/src/main/java/com/skyflow/utils/Constants.java @@ -25,4 +25,5 @@ public final class Constants { public static final String SDK_AUTH_HEADER_KEY = "x-skyflow-authorization"; public static final String SDK_METRICS_HEADER_KEY = "sky-metadata"; public static final String REQUEST_ID_HEADER_KEY = "x-request-id"; + public static final String ERROR_FROM_CLIENT_HEADER_KEY = "error-from-client"; } From 7c12079bff1e51100f21e98d4a1cc3a70287f952 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Thu, 27 Mar 2025 07:05:59 +0000 Subject: [PATCH 114/126] [AUTOMATED] Private Release 2.0.0-beta.1-dev-9f386ac --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b3aa8170..0f61f9c3 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 2.0.0-beta.1-dev.ea71c1d + 2.0.0-beta.1-dev.9f386ac jar ${project.groupId}:${project.artifactId} From cf242b107627d117b5276d71e44283949f5236ab Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Mon, 7 Apr 2025 06:33:28 +0000 Subject: [PATCH 115/126] [AUTOMATED] Private Release 2.0.0-beta.1-dev-ec349a9 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 0f61f9c3..84dfe438 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 2.0.0-beta.1-dev.9f386ac + 2.0.0-beta.1-dev.ec349a9 jar ${project.groupId}:${project.artifactId} From 6004ba34e0a41b76a2935ac88eb7994bcc9bbb01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Camith-skyflow=E2=80=9D?= <“amit@skyflow.com”> Date: Wed, 16 Apr 2025 12:14:56 +0530 Subject: [PATCH 116/126] SK-2003: update readme --- README.md | 103 +++++++++++++++++- .../BearerTokenExpiryExample.java | 86 +++++++++++++++ 2 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java diff --git a/README.md b/README.md index 1f6563b9..cee75d31 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ The Skyflow Java SDK is designed to help with integrating Skyflow into a Java ba - [Generate bearer tokens with context](#generate-bearer-tokens-with-context) - [Generate scoped bearer tokens](#generate-scoped-bearer-tokens) - [Generate signed data tokens](#generate-signed-data-tokens) + - [Bearer token expiry edge case](#bearer-token-expiry-edge-case) - [Logging](#logging) - [Reporting a Vulnerability](#reporting-a-vulnerability) @@ -2147,7 +2148,7 @@ Notes: - If both a file path and a string are provided, the last method used takes precedence. - To generate multiple bearer tokens concurrently using threads, refer to the following [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java). -## Signed Data Tokens Generation +## Generate Signed Data Tokens Skyflow generates data tokens when sensitive data is inserted into the vault. These data tokens can be digitally signed with the private key of the service account credentials, which adds an additional layer of protection. Signed tokens can @@ -2225,6 +2226,106 @@ Notes: - The `time-to-live` (TTL) value should be specified in seconds. - By default, the TTL value is set to 60 seconds. +## Bearer token expiry edge case +When you use bearer tokens for authentication and API requests in SDKs, there's the potential for a token to expire after the token is verified as valid but before the actual API call is made, causing the request to fail unexpectedly due to the token's expiration. An error from this edge case would look something like this: + +```txt +message: Authentication failed. Bearer token is expired. Use a valid bearer token. See https://docs.skyflow.com/api-authentication/ +``` + +If you encounter this kind of error, retry the request. During the retry, the SDK detects that the previous bearer token has expired and generates a new one for the current and subsequent requests. + +#### [Example](https://github.com/skyflowapi/skyflow-java/blob/v2/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java): + +```java +package com.example.serviceaccount; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.DetokenizeResponse; +import io.github.cdimascio.dotenv.Dotenv; +import java.util.ArrayList; + +/** + * This example demonstrates how to configure and use the Skyflow SDK + * to detokenize sensitive data stored in a Skyflow vault. + * It includes setting up credentials, configuring the vault, and + * making a detokenization request. The code also implements a retry + * mechanism to handle unauthorized access errors (HTTP 401). + */ +public class DetokenizeExample { + public static void main(String[] args) { + try { + // Setting up credentials for accessing the Skyflow vault + Credentials vaultCredentials = new Credentials(); + vaultCredentials.setCredentialsString(""); + + // Configuring the Skyflow vault with necessary details + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Vault ID + vaultConfig.setClusterId(""); // Cluster ID + vaultConfig.setEnv(Env.PROD); // Environment (e.g., DEV, PROD) + vaultConfig.setCredentials(vaultCredentials); // Setting credentials + + // Creating a Skyflow client instance with the configured vault + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Setting log level to ERROR + .addVaultConfig(vaultConfig) // Adding vault configuration + .build(); + + // Attempting to detokenize data using the Skyflow client + try { + detokenizeData(skyflowClient); + } catch (SkyflowException e) { + // Retry detokenization if the error is due to unauthorized access (HTTP 401) + if (e.getHttpCode() == 401) { + detokenizeData(skyflowClient); + } else { + // Rethrow the exception for other error codes + throw e; + } + } + } catch (SkyflowException e) { + // Handling any exceptions that occur during the process + System.out.println("An error occurred: " + e.getMessage()); + } + } + + /** + * Method to detokenize data using the Skyflow client. + * It sends a detokenization request with a list of tokens and prints the response. + * + * @param skyflowClient The Skyflow client instance used for detokenization. + * @throws SkyflowException If an error occurs during the detokenization process. + */ + public static void detokenizeData(Skyflow skyflowClient) throws SkyflowException { + // Creating a list of tokens to be detokenized + ArrayList tokenList = new ArrayList<>(); + tokenList.add(""); // First token + tokenList.add(""); // Second token + + // Building a detokenization request with the token list and configuration + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .tokens(tokenList) // Adding tokens to the request + .continueOnError(false) // Stop on error + .redactionType(RedactionType.PLAIN_TEXT) // Redaction type (e.g., PLAIN_TEXT) + .build(); + + // Sending the detokenization request and receiving the response + DetokenizeResponse detokenizeResponse = skyflowClient.vault().detokenize(detokenizeRequest); + + // Printing the detokenized response + System.out.println(detokenizeResponse); + } +} +``` + # Logging The SDK provides logging with Java's built-in logging library. By default, the SDK's logging level is set to `LogLevel.ERROR`. This can be changed using the `setLogLevel(logLevel)` method, as shown below: diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java new file mode 100644 index 00000000..1f56296d --- /dev/null +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java @@ -0,0 +1,86 @@ +package com.example.serviceaccount; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.DetokenizeResponse; +import io.github.cdimascio.dotenv.Dotenv; +import java.util.ArrayList; + +/** + * This example demonstrates how to configure and use the Skyflow SDK + * to detokenize sensitive data stored in a Skyflow vault. + * It includes setting up credentials, configuring the vault, and + * making a detokenization request. The code also implements a retry + * mechanism to handle unauthorized access errors (HTTP 401). + */ +public class BearerTokenExpiryExample { + public static void main(String[] args) { + try { + // Setting up credentials for accessing the Skyflow vault + Credentials vaultCredentials = new Credentials(); + vaultCredentials.setCredentialsString(""); + + // Configuring the Skyflow vault with necessary details + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Vault ID + vaultConfig.setClusterId(""); // Cluster ID + vaultConfig.setEnv(Env.PROD); // Environment (e.g., DEV, PROD) + vaultConfig.setCredentials(vaultCredentials); // Setting credentials + + // Creating a Skyflow client instance with the configured vault + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Setting log level to ERROR + .addVaultConfig(vaultConfig) // Adding vault configuration + .build(); + + // Attempting to detokenize data using the Skyflow client + try { + detokenizeData(skyflowClient); + } catch (SkyflowException e) { + // Retry detokenization if the error is due to unauthorized access (HTTP 401) + if (e.getHttpCode() == 401) { + detokenizeData(skyflowClient); + } else { + // Rethrow the exception for other error codes + throw e; + } + } + } catch (SkyflowException e) { + // Handling any exceptions that occur during the process + System.out.println("An error occurred: " + e.getMessage()); + } + } + + /** + * Method to detokenize data using the Skyflow client. + * It sends a detokenization request with a list of tokens and prints the response. + * + * @param skyflowClient The Skyflow client instance used for detokenization. + * @throws SkyflowException If an error occurs during the detokenization process. + */ + public static void detokenizeData(Skyflow skyflowClient) throws SkyflowException { + // Creating a list of tokens to be detokenized + ArrayList tokenList = new ArrayList<>(); + tokenList.add(""); // First token + tokenList.add(""); // Second token + + // Building a detokenization request with the token list and configuration + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .tokens(tokenList) // Adding tokens to the request + .continueOnError(false) // Stop on error + .redactionType(RedactionType.PLAIN_TEXT) // Redaction type (e.g., PLAIN_TEXT) + .build(); + + // Sending the detokenization request and receiving the response + DetokenizeResponse detokenizeResponse = skyflowClient.vault().detokenize(detokenizeRequest); + + // Printing the detokenized response + System.out.println(detokenizeResponse); + } +} From b886165cce7c89484734398c7088b78695978f9a Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow <156889717+saileshwar-skyflow@users.noreply.github.com> Date: Mon, 30 Jun 2025 18:52:45 +0530 Subject: [PATCH 117/126] SK-2141: Beta Release Fern Integration and Detect Support (#182) * SK-2071: Fern Integration and Detect Support (#179) --- .github/workflows/internal-release.yml | 1 - .github/workflows/pr.yml | 2 +- .github/workflows/shared-build-and-deploy.yml | 1 + pom.xml | 38 +- src/main/java/com/skyflow/Skyflow.java | 47 +- src/main/java/com/skyflow/VaultClient.java | 754 ++++++- .../skyflow/enums/DeidentifyFileStatus.java | 16 + .../com/skyflow/enums/DetectEntities.java | 83 + .../enums/DetectOutputTranscriptions.java | 24 + .../java/com/skyflow/enums/InterfaceName.java | 1 + .../java/com/skyflow/enums/MaskingMethod.java | 21 + .../java/com/skyflow/enums/RedactionType.java | 17 +- .../java/com/skyflow/enums/TokenMode.java | 16 +- .../java/com/skyflow/enums/TokenType.java | 27 + .../java/com/skyflow/errors/ErrorMessage.java | 23 + .../skyflow/generated/rest/ApiCallback.java | 62 - .../com/skyflow/generated/rest/ApiClient.java | 1631 +--------------- .../generated/rest/ApiClientBuilder.java | 67 + .../skyflow/generated/rest/ApiException.java | 167 -- .../skyflow/generated/rest/ApiResponse.java | 76 - .../generated/rest/AsyncApiClient.java | 92 + .../generated/rest/AsyncApiClientBuilder.java | 67 + .../skyflow/generated/rest/Configuration.java | 41 - .../rest/GzipRequestInterceptor.java | 85 - .../java/com/skyflow/generated/rest/JSON.java | 440 ----- .../java/com/skyflow/generated/rest/Pair.java | 57 - .../generated/rest/ProgressRequestBody.java | 73 - .../generated/rest/ProgressResponseBody.java | 70 - .../generated/rest/ServerConfiguration.java | 72 - .../generated/rest/ServerVariable.java | 37 - .../skyflow/generated/rest/StringUtil.java | 83 - .../skyflow/generated/rest/api/AuditApi.java | 466 ----- .../generated/rest/api/AuthenticationApi.java | 216 -- .../generated/rest/api/BinLookupApi.java | 208 -- .../skyflow/generated/rest/api/QueryApi.java | 218 --- .../generated/rest/api/RecordsApi.java | 1730 ----------------- .../skyflow/generated/rest/api/TokensApi.java | 361 ---- .../generated/rest/auth/ApiKeyAuth.java | 80 - .../generated/rest/auth/Authentication.java | 36 - .../generated/rest/auth/HttpBasicAuth.java | 55 - .../generated/rest/auth/HttpBearerAuth.java | 75 - .../rest/core/ApiClientApiException.java | 73 + .../rest/core/ApiClientException.java | 17 + .../rest/core/ApiClientHttpResponse.java | 37 + .../generated/rest/core/ClientOptions.java | 170 ++ .../rest/core/DateTimeDeserializer.java | 55 + .../generated/rest/core/Environment.java | 24 + .../generated/rest/core/FileStream.java | 60 + .../rest/core/InputStreamRequestBody.java | 79 + .../generated/rest/core/MediaTypes.java | 13 + .../skyflow/generated/rest/core/Nullable.java | 140 ++ .../rest/core/NullableNonemptyFilter.java | 19 + .../generated/rest/core/ObjectMappers.java | 36 + .../rest/core/QueryStringMapper.java | 142 ++ .../rest/core/QueryStringMapperTest.java | 339 ++++ .../generated/rest/core/RequestOptions.java | 101 + .../rest/core/ResponseBodyInputStream.java | 45 + .../rest/core/ResponseBodyReader.java | 44 + .../generated/rest/core/RetryInterceptor.java | 78 + .../skyflow/generated/rest/core/Stream.java | 97 + .../generated/rest/core/Suppliers.java | 23 + .../rest/errors/BadRequestError.java | 32 + .../rest/errors/InternalServerError.java | 33 + .../generated/rest/errors/NotFoundError.java | 32 + .../rest/errors/UnauthorizedError.java | 32 + .../rest/models/AbstractOpenApiSchema.java | 146 -- .../models/AuditEventAuditResourceType.java | 134 -- .../rest/models/AuditEventContext.java | 530 ----- .../generated/rest/models/AuditEventData.java | 205 -- .../rest/models/AuditEventHTTPInfo.java | 234 --- .../rest/models/BatchRecordMethod.java | 84 - .../rest/models/ContextAccessType.java | 80 - .../rest/models/ContextAuthMode.java | 82 - .../DetokenizeRecordResponseValueType.java | 92 - .../rest/models/GooglerpcStatus.java | 272 --- .../generated/rest/models/ProtobufAny.java | 286 --- .../models/QueryServiceExecuteQueryBody.java | 205 -- .../RecordServiceBatchOperationBody.java | 284 --- .../RecordServiceBulkDeleteRecordBody.java | 216 -- .../models/RecordServiceInsertRecordBody.java | 339 ---- .../models/RecordServiceUpdateRecordBody.java | 264 --- .../rest/models/RedactionEnumREDACTION.java | 82 - .../rest/models/RequestActionType.java | 110 -- .../rest/models/V1AuditAfterOptions.java | 234 --- .../rest/models/V1AuditEventResponse.java | 291 --- .../rest/models/V1AuditResponse.java | 258 --- .../rest/models/V1AuditResponseEvent.java | 367 ---- .../models/V1AuditResponseEventRequest.java | 456 ----- .../rest/models/V1BINListRequest.java | 305 --- .../rest/models/V1BINListResponse.java | 227 --- .../skyflow/generated/rest/models/V1BYOT.java | 80 - .../rest/models/V1BatchOperationResponse.java | 245 --- .../generated/rest/models/V1BatchRecord.java | 458 ----- .../models/V1BulkDeleteRecordResponse.java | 216 -- .../rest/models/V1BulkGetRecordResponse.java | 227 --- .../skyflow/generated/rest/models/V1Card.java | 437 ----- .../rest/models/V1DeleteFileResponse.java | 231 --- .../rest/models/V1DeleteRecordResponse.java | 231 --- .../rest/models/V1DetokenizePayload.java | 279 --- .../models/V1DetokenizeRecordRequest.java | 236 --- .../models/V1DetokenizeRecordResponse.java | 294 --- .../rest/models/V1DetokenizeResponse.java | 227 --- .../generated/rest/models/V1FieldRecords.java | 228 --- .../rest/models/V1FileAVScanStatus.java | 92 - .../rest/models/V1GetAuthTokenRequest.java | 359 ---- .../rest/models/V1GetAuthTokenResponse.java | 234 --- .../models/V1GetFileScanStatusResponse.java | 207 -- .../rest/models/V1GetQueryResponse.java | 227 --- .../rest/models/V1InsertRecordResponse.java | 227 --- .../generated/rest/models/V1MemberType.java | 80 - .../rest/models/V1RecordMetaProperties.java | 231 --- .../rest/models/V1TokenizePayload.java | 227 --- .../rest/models/V1TokenizeRecordRequest.java | 234 --- .../rest/models/V1TokenizeRecordResponse.java | 205 -- .../rest/models/V1TokenizeResponse.java | 227 --- .../rest/models/V1UpdateRecordResponse.java | 231 --- .../rest/models/V1VaultFieldMapping.java | 263 --- .../rest/models/V1VaultSchemaConfig.java | 265 --- .../resources/audit/AsyncAuditClient.java | 45 + .../resources/audit/AsyncRawAuditClient.java | 296 +++ .../rest/resources/audit/AuditClient.java | 44 + .../rest/resources/audit/RawAuditClient.java | 277 +++ .../AuditServiceListAuditEventsRequest.java | 1589 +++++++++++++++ ...AuditEventsRequestFilterOpsActionType.java | 56 + ...entsRequestFilterOpsContextAccessType.java | 28 + ...ventsRequestFilterOpsContextActorType.java | 26 + ...EventsRequestFilterOpsContextAuthMode.java | 28 + ...ditEventsRequestFilterOpsResourceType.java | 80 + ...eListAuditEventsRequestSortOpsOrderBy.java | 24 + .../AsyncAuthenticationClient.java | 45 + .../AsyncRawAuthenticationClient.java | 126 ++ .../authentication/AuthenticationClient.java | 44 + .../RawAuthenticationClient.java | 102 + .../requests/V1GetAuthTokenRequest.java | 335 ++++ .../binlookup/AsyncBinLookupClient.java | 52 + .../binlookup/AsyncRawBinLookupClient.java | 118 ++ .../resources/binlookup/BinLookupClient.java | 50 + .../binlookup/RawBinLookupClient.java | 98 + .../binlookup/requests/V1BinListRequest.java | 189 ++ .../deprecated/AsyncDeprecatedClient.java | 89 + .../deprecated/AsyncRawDeprecatedClient.java | 271 +++ .../deprecated/DeprecatedClient.java | 87 + .../deprecated/RawDeprecatedClient.java | 222 +++ .../DetectServiceDetectStatusRequest.java | 101 + .../DetectServiceDetectTextRequest.java | 526 +++++ .../requests/V1DetectFileRequest.java | 634 ++++++ .../resources/files/AsyncFilesClient.java | 188 ++ .../resources/files/AsyncRawFilesClient.java | 929 +++++++++ .../rest/resources/files/FilesClient.java | 180 ++ .../rest/resources/files/RawFilesClient.java | 714 +++++++ .../requests/DeidentifyAudioRequest.java | 582 ++++++ .../requests/DeidentifyDocumentRequest.java | 310 +++ .../files/requests/DeidentifyFileRequest.java | 310 +++ .../requests/DeidentifyImageRequest.java | 446 +++++ .../files/requests/DeidentifyPdfRequest.java | 400 ++++ .../DeidentifyPresentationRequest.java | 310 +++ .../DeidentifySpreadsheetRequest.java | 310 +++ .../DeidentifyStructuredTextRequest.java | 310 +++ .../files/requests/DeidentifyTextRequest.java | 310 +++ .../files/requests/GetRunRequest.java | 112 ++ .../types/DeidentifyAudioRequestFile.java | 145 ++ .../DeidentifyAudioRequestFileDataFormat.java | 24 + ...entifyAudioRequestOutputTranscription.java | 30 + .../types/DeidentifyDocumentRequestFile.java | 147 ++ ...identifyDocumentRequestFileDataFormat.java | 26 + .../types/DeidentifyFileRequestFile.java | 145 ++ .../DeidentifyFileRequestFileDataFormat.java | 58 + .../types/DeidentifyImageRequestFile.java | 145 ++ .../DeidentifyImageRequestFileDataFormat.java | 32 + .../DeidentifyImageRequestMaskingMethod.java | 24 + .../files/types/DeidentifyPdfRequestFile.java | 120 ++ .../DeidentifyPresentationRequestFile.java | 147 ++ ...tifyPresentationRequestFileDataFormat.java | 24 + .../DeidentifySpreadsheetRequestFile.java | 147 ++ ...ntifySpreadsheetRequestFileDataFormat.java | 26 + .../DeidentifyStructuredTextRequestFile.java | 148 ++ ...fyStructuredTextRequestFileDataFormat.java | 24 + .../types/DeidentifyTextRequestFile.java | 120 ++ .../resources/query/AsyncQueryClient.java | 53 + .../resources/query/AsyncRawQueryClient.java | 121 ++ .../rest/resources/query/QueryClient.java | 51 + .../rest/resources/query/RawQueryClient.java | 102 + .../QueryServiceExecuteQueryBody.java | 101 + .../records/AsyncRawRecordsClient.java | 956 +++++++++ .../resources/records/AsyncRecordsClient.java | 317 +++ .../resources/records/RawRecordsClient.java | 800 ++++++++ .../rest/resources/records/RecordsClient.java | 312 +++ .../FileServiceUploadFileRequest.java | 59 + .../RecordServiceBatchOperationBody.java | 160 ++ .../RecordServiceBulkDeleteRecordBody.java | 103 + .../RecordServiceBulkGetRecordRequest.java | 413 ++++ .../RecordServiceGetRecordRequest.java | 202 ++ .../RecordServiceInsertRecordBody.java | 221 +++ .../RecordServiceUpdateRecordBody.java | 151 ++ ...ordServiceBulkGetRecordRequestOrderBy.java | 26 + ...dServiceBulkGetRecordRequestRedaction.java | 28 + ...ecordServiceGetRecordRequestRedaction.java | 28 + .../strings/AsyncRawStringsClient.java | 217 +++ .../resources/strings/AsyncStringsClient.java | 60 + .../resources/strings/RawStringsClient.java | 171 ++ .../rest/resources/strings/StringsClient.java | 57 + .../requests/DeidentifyStringRequest.java | 309 +++ .../requests/ReidentifyStringRequest.java | 192 ++ .../types/ReidentifyStringRequestFormat.java | 163 ++ .../tokens/AsyncRawTokensClient.java | 206 ++ .../resources/tokens/AsyncTokensClient.java | 79 + .../resources/tokens/RawTokensClient.java | 172 ++ .../rest/resources/tokens/TokensClient.java | 77 + .../tokens/requests/V1DetokenizePayload.java | 166 ++ .../tokens/requests/V1TokenizePayload.java | 104 + .../types/AdvancedOptionsColumnMapping.java | 194 ++ .../types/AdvancedOptionsEntityColumnMap.java | 126 ++ .../types/AdvancedOptionsVaultSchema.java | 135 ++ .../types/AudioConfigTranscriptionType.java | 40 + .../types/AuditEventAuditResourceType.java | 80 + .../rest/types/AuditEventContext.java | 440 +++++ .../generated/rest/types/AuditEventData.java | 101 + .../rest/types/AuditEventHttpInfo.java | 130 ++ .../rest/types/BatchRecordMethod.java | 30 + .../rest/types/ContextAccessType.java | 26 + .../generated/rest/types/ContextAuthMode.java | 28 + .../rest/types/DeidentifyFileOutput.java | 164 ++ ...DeidentifyFileOutputProcessedFileType.java | 40 + .../rest/types/DeidentifyFileResponse.java | 112 ++ .../rest/types/DeidentifyStatusResponse.java | 521 +++++ .../DeidentifyStatusResponseOutputType.java | 26 + .../types/DeidentifyStatusResponseStatus.java | 26 + .../rest/types/DeidentifyStringResponse.java | 242 +++ .../rest/types/DetectDataAccuracy.java | 36 + .../rest/types/DetectDataEntities.java | 146 ++ .../rest/types/DetectFileRequestDataType.java | 24 + .../types/DetectRequestDeidentifyOption.java | 26 + .../generated/rest/types/DetectedEntity.java | 217 +++ .../DetokenizeRecordResponseValueType.java | 38 + .../generated/rest/types/EntityLocation.java | 194 ++ .../generated/rest/types/EntityType.java | 146 ++ .../generated/rest/types/ErrorResponse.java | 102 + .../rest/types/ErrorResponseError.java | 240 +++ .../generated/rest/types/GooglerpcStatus.java | 144 ++ .../ProcessedFileOutputProcessedFileType.java | 40 + .../generated/rest/types/ProtobufAny.java | 95 + .../rest/types/RedactionEnumRedaction.java | 28 + .../rest/types/ReidentifyStringResponse.java | 101 + .../rest/types/RequestActionType.java | 56 + .../generated/rest/types/TokenType.java | 188 ++ .../rest/types/TokenTypeDefault.java | 26 + .../rest/types/TokenTypeWithoutVault.java | 158 ++ .../types/TokenTypeWithoutVaultDefault.java | 24 + .../generated/rest/types/Transformations.java | 101 + .../rest/types/TransformationsShiftDates.java | 162 ++ ...nsformationsShiftDatesEntityTypesItem.java | 26 + .../rest/types/V1AdvancedOptions.java | 157 ++ .../generated/rest/types/V1AudioConfig.java | 151 ++ .../generated/rest/types/V1AudioOptions.java | 234 +++ .../rest/types/V1AuditAfterOptions.java | 130 ++ .../rest/types/V1AuditEventResponse.java | 187 ++ .../generated/rest/types/V1AuditResponse.java | 127 ++ .../rest/types/V1AuditResponseEvent.java | 238 +++ .../types/V1AuditResponseEventRequest.java | 339 ++++ .../rest/types/V1BatchOperationResponse.java | 133 ++ .../generated/rest/types/V1BatchRecord.java | 382 ++++ .../rest/types/V1BinListResponse.java | 102 + .../types/V1BulkDeleteRecordResponse.java | 103 + .../rest/types/V1BulkGetRecordResponse.java | 102 + .../skyflow/generated/rest/types/V1Byot.java | 26 + .../skyflow/generated/rest/types/V1Card.java | 362 ++++ .../rest/types/V1DeleteFileResponse.java | 130 ++ .../rest/types/V1DeleteRecordResponse.java | 130 ++ .../rest/types/V1DetectFileResponse.java | 101 + .../rest/types/V1DetectStatusResponse.java | 156 ++ .../types/V1DetectStatusResponseStatus.java | 28 + .../rest/types/V1DetectTextRequest.java | 522 +++++ .../rest/types/V1DetectTextResponse.java | 133 ++ .../rest/types/V1DetokenizeRecordRequest.java | 126 ++ .../types/V1DetokenizeRecordResponse.java | 187 ++ .../rest/types/V1DetokenizeResponse.java | 103 + .../generated/rest/types/V1FieldRecords.java | 132 ++ .../rest/types/V1FileAvScanStatus.java | 38 + .../rest/types/V1FileDataFormat.java | 58 + .../rest/types/V1GetAuthTokenResponse.java | 130 ++ .../types/V1GetFileScanStatusResponse.java | 96 + .../rest/types/V1GetQueryResponse.java | 102 + .../generated/rest/types/V1ImageOptions.java | 132 ++ .../rest/types/V1InsertRecordResponse.java | 103 + .../generated/rest/types/V1Locations.java | 193 ++ .../generated/rest/types/V1MemberType.java | 26 + .../generated/rest/types/V1PdfConfig.java | 95 + .../generated/rest/types/V1PdfOptions.java | 130 ++ .../rest/types/V1ProcessedFileOutput.java | 151 ++ .../rest/types/V1RecordMetaProperties.java | 132 ++ .../rest/types/V1ResponseEntities.java | 218 +++ .../rest/types/V1TokenizeRecordRequest.java | 130 ++ .../rest/types/V1TokenizeRecordResponse.java | 101 + .../rest/types/V1TokenizeResponse.java | 103 + .../rest/types/V1UpdateRecordResponse.java | 132 ++ .../rest/types/V1VaultFieldMapping.java | 163 ++ .../rest/types/V1VaultSchemaConfig.java | 155 ++ src/main/java/com/skyflow/logs/ErrorLogs.java | 18 + src/main/java/com/skyflow/logs/InfoLogs.java | 22 +- .../serviceaccount/util/BearerToken.java | 39 +- .../java/com/skyflow/utils/Constants.java | 4 +- .../utils/validations/Validations.java | 146 +- .../vault/controller/AuditController.java | 4 +- .../vault/controller/BinLookupController.java | 3 - .../vault/controller/DetectController.java | 379 +++- .../vault/controller/VaultController.java | 245 ++- .../skyflow/vault/data/DeleteResponse.java | 11 +- .../com/skyflow/vault/data/GetRequest.java | 1 - .../com/skyflow/vault/data/QueryResponse.java | 2 +- .../skyflow/vault/data/UpdateResponse.java | 2 +- .../com/skyflow/vault/detect/AudioBleep.java | 64 + .../vault/detect/DateTransformation.java | 30 + .../vault/detect/DeIdentifyRequest.java | 10 - .../vault/detect/DeIdentifyResponse.java | 10 - .../vault/detect/DeidentifyFileRequest.java | 192 ++ .../vault/detect/DeidentifyFileResponse.java | 112 ++ .../vault/detect/DeidentifyTextRequest.java | 88 + .../vault/detect/DeidentifyTextResponse.java | 44 + .../com/skyflow/vault/detect/EntityInfo.java | 46 + .../skyflow/vault/detect/FileEntityInfo.java | 19 + .../com/skyflow/vault/detect/FileInfo.java | 33 + .../com/skyflow/vault/detect/FileInput.java | 46 + .../vault/detect/GetDetectRunRequest.java | 33 + .../vault/detect/ReidentifyTextRequest.java | 68 + .../vault/detect/ReidentifyTextResponse.java | 23 + .../com/skyflow/vault/detect/TextIndex.java | 29 + .../com/skyflow/vault/detect/TokenFormat.java | 71 + .../skyflow/vault/detect/Transformations.java | 14 + .../tokens/DetokenizeRecordResponse.java | 21 +- .../vault/tokens/TokenizeResponse.java | 2 +- src/test/java/com/skyflow/SkyflowTests.java | 126 ++ .../java/com/skyflow/VaultClientTests.java | 729 ++++++- .../skyflow/errors/SkyflowExceptionTest.java | 98 + .../controller/DetectControllerFileTests.java | 409 ++++ .../controller/DetectControllerTests.java | 121 ++ .../controller/VaultControllerTests.java | 43 +- .../com/skyflow/vault/data/DeleteTests.java | 2 +- .../com/skyflow/vault/data/QueryTests.java | 2 +- .../com/skyflow/vault/data/UpdateTests.java | 2 +- .../detect/DeidentifyFileRequestTest.java | 99 + .../detect/DeidentifyFileResponseTest.java | 60 + .../vault/detect/DeidentifyTextTests.java | 217 +++ .../vault/detect/FileEntityInfoTest.java | 21 + .../skyflow/vault/detect/FileInfoTest.java | 41 + .../vault/detect/ReidentifyTextTests.java | 149 ++ .../skyflow/vault/tokens/DetokenizeTests.java | 23 +- .../skyflow/vault/tokens/TokenizeTests.java | 2 +- 347 files changed, 37015 insertions(+), 19188 deletions(-) create mode 100644 src/main/java/com/skyflow/enums/DeidentifyFileStatus.java create mode 100644 src/main/java/com/skyflow/enums/DetectEntities.java create mode 100644 src/main/java/com/skyflow/enums/DetectOutputTranscriptions.java create mode 100644 src/main/java/com/skyflow/enums/MaskingMethod.java create mode 100644 src/main/java/com/skyflow/enums/TokenType.java delete mode 100644 src/main/java/com/skyflow/generated/rest/ApiCallback.java create mode 100644 src/main/java/com/skyflow/generated/rest/ApiClientBuilder.java delete mode 100644 src/main/java/com/skyflow/generated/rest/ApiException.java delete mode 100644 src/main/java/com/skyflow/generated/rest/ApiResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/AsyncApiClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/AsyncApiClientBuilder.java delete mode 100644 src/main/java/com/skyflow/generated/rest/Configuration.java delete mode 100644 src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java delete mode 100644 src/main/java/com/skyflow/generated/rest/JSON.java delete mode 100644 src/main/java/com/skyflow/generated/rest/Pair.java delete mode 100644 src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java delete mode 100644 src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java delete mode 100644 src/main/java/com/skyflow/generated/rest/ServerConfiguration.java delete mode 100644 src/main/java/com/skyflow/generated/rest/ServerVariable.java delete mode 100644 src/main/java/com/skyflow/generated/rest/StringUtil.java delete mode 100644 src/main/java/com/skyflow/generated/rest/api/AuditApi.java delete mode 100644 src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java delete mode 100644 src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java delete mode 100644 src/main/java/com/skyflow/generated/rest/api/QueryApi.java delete mode 100644 src/main/java/com/skyflow/generated/rest/api/RecordsApi.java delete mode 100644 src/main/java/com/skyflow/generated/rest/api/TokensApi.java delete mode 100644 src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java delete mode 100644 src/main/java/com/skyflow/generated/rest/auth/Authentication.java delete mode 100644 src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java delete mode 100644 src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/ApiClientApiException.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/ApiClientException.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/ApiClientHttpResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/ClientOptions.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/DateTimeDeserializer.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/Environment.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/FileStream.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/InputStreamRequestBody.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/MediaTypes.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/Nullable.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/NullableNonemptyFilter.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/ObjectMappers.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/QueryStringMapper.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/QueryStringMapperTest.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/RequestOptions.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/ResponseBodyInputStream.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/ResponseBodyReader.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/RetryInterceptor.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/Stream.java create mode 100644 src/main/java/com/skyflow/generated/rest/core/Suppliers.java create mode 100644 src/main/java/com/skyflow/generated/rest/errors/BadRequestError.java create mode 100644 src/main/java/com/skyflow/generated/rest/errors/InternalServerError.java create mode 100644 src/main/java/com/skyflow/generated/rest/errors/NotFoundError.java create mode 100644 src/main/java/com/skyflow/generated/rest/errors/UnauthorizedError.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/AuditEventData.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/RequestActionType.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1BYOT.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1Card.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1MemberType.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java delete mode 100644 src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/audit/AsyncAuditClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/audit/AsyncRawAuditClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/audit/AuditClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/audit/RawAuditClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/audit/requests/AuditServiceListAuditEventsRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsActionType.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAccessType.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextActorType.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAuthMode.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsResourceType.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestSortOpsOrderBy.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/authentication/AsyncAuthenticationClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/authentication/AsyncRawAuthenticationClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/authentication/AuthenticationClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/authentication/RawAuthenticationClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/authentication/requests/V1GetAuthTokenRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncBinLookupClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncRawBinLookupClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/binlookup/BinLookupClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/binlookup/RawBinLookupClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/binlookup/requests/V1BinListRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncDeprecatedClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncRawDeprecatedClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/DeprecatedClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/RawDeprecatedClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectStatusRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectTextRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/V1DetectFileRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/AsyncFilesClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/AsyncRawFilesClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/FilesClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/RawFilesClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyAudioRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyDocumentRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyImageRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPdfRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPresentationRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifySpreadsheetRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyStructuredTextRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyTextRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/requests/GetRunRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyAudioRequestFile.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyAudioRequestFileDataFormat.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyAudioRequestOutputTranscription.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyDocumentRequestFile.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyDocumentRequestFileDataFormat.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestFile.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestFileDataFormat.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyImageRequestFile.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyImageRequestFileDataFormat.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyImageRequestMaskingMethod.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyPdfRequestFile.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyPresentationRequestFile.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyPresentationRequestFileDataFormat.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifySpreadsheetRequestFile.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifySpreadsheetRequestFileDataFormat.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyStructuredTextRequestFile.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyStructuredTextRequestFileDataFormat.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyTextRequestFile.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/query/AsyncQueryClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/query/AsyncRawQueryClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/query/QueryClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/query/RawQueryClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/query/requests/QueryServiceExecuteQueryBody.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/AsyncRawRecordsClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/AsyncRecordsClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/RawRecordsClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/RecordsClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/requests/FileServiceUploadFileRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBatchOperationBody.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkDeleteRecordBody.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkGetRecordRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceGetRecordRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceInsertRecordBody.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceUpdateRecordBody.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestOrderBy.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestRedaction.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceGetRecordRequestRedaction.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/strings/AsyncRawStringsClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/strings/AsyncStringsClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/strings/RawStringsClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/strings/StringsClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/strings/requests/DeidentifyStringRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/strings/requests/ReidentifyStringRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/strings/types/ReidentifyStringRequestFormat.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncRawTokensClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncTokensClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/tokens/RawTokensClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/tokens/TokensClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/tokens/requests/V1DetokenizePayload.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/tokens/requests/V1TokenizePayload.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsColumnMapping.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsEntityColumnMap.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsVaultSchema.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/AudioConfigTranscriptionType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/AuditEventAuditResourceType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/AuditEventContext.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/AuditEventData.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/AuditEventHttpInfo.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/BatchRecordMethod.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/ContextAccessType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/ContextAuthMode.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/DeidentifyFileOutput.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/DeidentifyFileOutputProcessedFileType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/DeidentifyFileResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseOutputType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseStatus.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/DeidentifyStringResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/DetectDataAccuracy.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/DetectDataEntities.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/DetectFileRequestDataType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/DetectRequestDeidentifyOption.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/DetectedEntity.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordResponseValueType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/EntityLocation.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/EntityType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/ErrorResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/ErrorResponseError.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/GooglerpcStatus.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/ProcessedFileOutputProcessedFileType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/ProtobufAny.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/RedactionEnumRedaction.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/ReidentifyStringResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/RequestActionType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/TokenType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/TokenTypeDefault.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/TokenTypeWithoutVault.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/TokenTypeWithoutVaultDefault.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/Transformations.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/TransformationsShiftDates.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/TransformationsShiftDatesEntityTypesItem.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1AdvancedOptions.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1AudioConfig.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1AudioOptions.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1AuditAfterOptions.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1AuditEventResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1AuditResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1AuditResponseEvent.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1AuditResponseEventRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1BatchOperationResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1BatchRecord.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1BinListResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1BulkDeleteRecordResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1BulkGetRecordResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1Byot.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1Card.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DeleteFileResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DeleteRecordResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DetectFileResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponseStatus.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DetectTextRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DetectTextResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DetokenizeRecordRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DetokenizeRecordResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DetokenizeResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1FieldRecords.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1FileAvScanStatus.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1FileDataFormat.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1GetAuthTokenResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1GetFileScanStatusResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1GetQueryResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1ImageOptions.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1InsertRecordResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1Locations.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1MemberType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1PdfConfig.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1PdfOptions.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1ProcessedFileOutput.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1RecordMetaProperties.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1ResponseEntities.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1TokenizeRecordRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1TokenizeRecordResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1TokenizeResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1UpdateRecordResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1VaultFieldMapping.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/V1VaultSchemaConfig.java create mode 100644 src/main/java/com/skyflow/vault/detect/AudioBleep.java create mode 100644 src/main/java/com/skyflow/vault/detect/DateTransformation.java delete mode 100644 src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java delete mode 100644 src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java create mode 100644 src/main/java/com/skyflow/vault/detect/DeidentifyFileRequest.java create mode 100644 src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java create mode 100644 src/main/java/com/skyflow/vault/detect/DeidentifyTextRequest.java create mode 100644 src/main/java/com/skyflow/vault/detect/DeidentifyTextResponse.java create mode 100644 src/main/java/com/skyflow/vault/detect/EntityInfo.java create mode 100644 src/main/java/com/skyflow/vault/detect/FileEntityInfo.java create mode 100644 src/main/java/com/skyflow/vault/detect/FileInfo.java create mode 100644 src/main/java/com/skyflow/vault/detect/FileInput.java create mode 100644 src/main/java/com/skyflow/vault/detect/GetDetectRunRequest.java create mode 100644 src/main/java/com/skyflow/vault/detect/ReidentifyTextRequest.java create mode 100644 src/main/java/com/skyflow/vault/detect/ReidentifyTextResponse.java create mode 100644 src/main/java/com/skyflow/vault/detect/TextIndex.java create mode 100644 src/main/java/com/skyflow/vault/detect/TokenFormat.java create mode 100644 src/main/java/com/skyflow/vault/detect/Transformations.java create mode 100644 src/test/java/com/skyflow/errors/SkyflowExceptionTest.java create mode 100644 src/test/java/com/skyflow/vault/controller/DetectControllerFileTests.java create mode 100644 src/test/java/com/skyflow/vault/controller/DetectControllerTests.java create mode 100644 src/test/java/com/skyflow/vault/detect/DeidentifyFileRequestTest.java create mode 100644 src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java create mode 100644 src/test/java/com/skyflow/vault/detect/DeidentifyTextTests.java create mode 100644 src/test/java/com/skyflow/vault/detect/FileEntityInfoTest.java create mode 100644 src/test/java/com/skyflow/vault/detect/FileInfoTest.java create mode 100644 src/test/java/com/skyflow/vault/detect/ReidentifyTextTests.java diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index f87afc29..e8b8ee61 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -4,7 +4,6 @@ on: tags-ignore: - '*.*' paths-ignore: - - "pom.xml" - "*.md" branches: - release/* diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 5554efe3..3883a1a9 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -40,7 +40,7 @@ jobs: echo TEST_REUSABLE_TOKEN=${{ secrets.TEST_REUSABLE_TOKEN }} >> .env - name: Build & Run tests with Maven - run: mvn -B package -f pom.xml + run: mvn -B package -f pom.xml -Dmaven.javadoc.skip=true - name: Codecov uses: codecov/codecov-action@v2.1.0 diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index 89332762..c9cadd2c 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -126,6 +126,7 @@ jobs: - name: Publish package run: mvn --batch-mode deploy -P ${{ inputs.profile }} + env: SERVER_USERNAME: ${{ secrets.server-username }} SERVER_PASSWORD: ${{ secrets.server-password }} diff --git a/pom.xml b/pom.xml index 84dfe438..7802501d 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 2.0.0-beta.1-dev.ec349a9 + 2.0.0-beta.1-dev.e14bd74 jar ${project.groupId}:${project.artifactId} @@ -45,6 +45,30 @@ + + com.squareup.okhttp3 + okhttp + 4.12.0 + compile + + + com.fasterxml.jackson.core + jackson-databind + 2.17.2 + compile + + + com.fasterxml.jackson.datatype + jackson-datatype-jdk8 + 2.17.2 + compile + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + 2.17.2 + compile + io.github.cdimascio @@ -117,6 +141,12 @@ 2.0.9 test + + org.junit.jupiter + junit-jupiter + 5.13.2 + compile + @@ -140,10 +170,7 @@ 3.2.0 - :com.skyflow.generated.rest - :com.skyflow.generated.rest.api - :com.skyflow.generated.rest.auth - :com.skyflow.generated.rest.models + com.skyflow.generated.rest.* @@ -276,5 +303,4 @@ - diff --git a/src/main/java/com/skyflow/Skyflow.java b/src/main/java/com/skyflow/Skyflow.java index 6866bd43..8e51da57 100644 --- a/src/main/java/com/skyflow/Skyflow.java +++ b/src/main/java/com/skyflow/Skyflow.java @@ -14,6 +14,7 @@ import com.skyflow.utils.logger.LogUtil; import com.skyflow.utils.validations.Validations; import com.skyflow.vault.controller.ConnectionController; +import com.skyflow.vault.controller.DetectController; import com.skyflow.vault.controller.VaultController; import java.util.LinkedHashMap; @@ -101,18 +102,49 @@ public VaultController vault(String vaultId) throws SkyflowException { return controller; } - public ConnectionController connection() { - String connectionId = (String) this.builder.connectionsMap.keySet().toArray()[0]; + + public ConnectionController connection() throws SkyflowException { + Object[] array = this.builder.connectionsMap.keySet().toArray(); + if (array.length < 1) { + LogUtil.printErrorLog(ErrorLogs.CONNECTION_CONFIG_DOES_NOT_EXIST.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ConnectionIdNotInConfigList.getMessage()); + } + String connectionId = (String) array[0]; return this.connection(connectionId); } - public ConnectionController connection(String connectionId) { - return this.builder.connectionsMap.get(connectionId); + public ConnectionController connection(String connectionId) throws SkyflowException { + ConnectionController controller = this.builder.connectionsMap.get(connectionId); + if (controller == null) { + LogUtil.printErrorLog(ErrorLogs.CONNECTION_CONFIG_DOES_NOT_EXIST.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ConnectionIdNotInConfigList.getMessage()); + } + return controller; + } + + public DetectController detect() throws SkyflowException { + Object[] array = this.builder.detectClientsMap.keySet().toArray(); + if (array.length < 1) { + LogUtil.printErrorLog(ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultIdNotInConfigList.getMessage()); + } + String detectId = (String) array[0]; + return this.detect(detectId); + } + + public DetectController detect(String vaultId) throws SkyflowException { + DetectController controller = this.builder.detectClientsMap.get(vaultId); + if (controller == null) { + LogUtil.printErrorLog(ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultIdNotInConfigList.getMessage()); + } + return controller; } public static final class SkyflowClientBuilder { private final LinkedHashMap connectionsMap; private final LinkedHashMap vaultClientsMap; + private final LinkedHashMap detectClientsMap; private final LinkedHashMap vaultConfigMap; private final LinkedHashMap connectionConfigMap; private Credentials skyflowCredentials; @@ -120,6 +152,7 @@ public static final class SkyflowClientBuilder { public SkyflowClientBuilder() { this.vaultClientsMap = new LinkedHashMap<>(); + this.detectClientsMap = new LinkedHashMap<>(); this.vaultConfigMap = new LinkedHashMap<>(); this.connectionsMap = new LinkedHashMap<>(); this.connectionConfigMap = new LinkedHashMap<>(); @@ -139,8 +172,11 @@ public SkyflowClientBuilder addVaultConfig(VaultConfig vaultConfig) throws Skyfl } else { this.vaultConfigMap.put(vaultConfig.getVaultId(), vaultConfig); this.vaultClientsMap.put(vaultConfig.getVaultId(), new VaultController(vaultConfig, this.skyflowCredentials)); + this.detectClientsMap.put(vaultConfig.getVaultId(), new DetectController(vaultConfig, this.skyflowCredentials)); LogUtil.printInfoLog(Utils.parameterizedString( InfoLogs.VAULT_CONTROLLER_INITIALIZED.getLog(), vaultConfig.getVaultId())); + LogUtil.printInfoLog(Utils.parameterizedString( + InfoLogs.DETECT_CONTROLLER_INITIALIZED.getLog(), vaultConfig.getVaultId())); } return this; } @@ -226,6 +262,9 @@ public SkyflowClientBuilder addSkyflowCredentials(Credentials credentials) throw for (VaultController vault : this.vaultClientsMap.values()) { vault.setCommonCredentials(this.skyflowCredentials); } + for (DetectController detect : this.detectClientsMap.values()) { + detect.setCommonCredentials(this.skyflowCredentials); + } for (ConnectionController connection : this.connectionsMap.values()) { connection.setCommonCredentials(this.skyflowCredentials); } diff --git a/src/main/java/com/skyflow/VaultClient.java b/src/main/java/com/skyflow/VaultClient.java index eb1cc3fa..7536a2c1 100644 --- a/src/main/java/com/skyflow/VaultClient.java +++ b/src/main/java/com/skyflow/VaultClient.java @@ -2,15 +2,30 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; +import com.skyflow.enums.DetectEntities; +import com.skyflow.enums.DetectOutputTranscriptions; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.api.QueryApi; -import com.skyflow.generated.rest.api.RecordsApi; -import com.skyflow.generated.rest.api.TokensApi; -import com.skyflow.generated.rest.auth.HttpBearerAuth; -import com.skyflow.generated.rest.models.*; +import com.skyflow.generated.rest.ApiClientBuilder; +import com.skyflow.generated.rest.resources.files.FilesClient; +import com.skyflow.generated.rest.resources.files.requests.*; +import com.skyflow.generated.rest.resources.files.types.*; +import com.skyflow.generated.rest.resources.query.QueryClient; +import com.skyflow.generated.rest.resources.records.RecordsClient; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.resources.strings.StringsClient; +import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; +import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; +import com.skyflow.generated.rest.resources.strings.types.ReidentifyStringRequestFormat; +import com.skyflow.generated.rest.resources.tokens.TokensClient; +import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; +import com.skyflow.generated.rest.types.*; +import com.skyflow.generated.rest.types.Transformations; import com.skyflow.logs.InfoLogs; import com.skyflow.serviceaccount.util.Token; import com.skyflow.utils.Constants; @@ -19,6 +34,9 @@ import com.skyflow.utils.validations.Validations; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.UpdateRequest; +import com.skyflow.vault.detect.*; +import com.skyflow.vault.detect.DeidentifyFileRequest; +import com.skyflow.vault.detect.DeidentifyTextRequest; import com.skyflow.vault.tokens.ColumnValue; import com.skyflow.vault.tokens.DetokenizeData; import com.skyflow.vault.tokens.DetokenizeRequest; @@ -26,16 +44,14 @@ import io.github.cdimascio.dotenv.Dotenv; import io.github.cdimascio.dotenv.DotenvException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; +import java.util.*; +import java.util.stream.Collectors; + public class VaultClient { - private final RecordsApi recordsApi; - private final TokensApi tokensApi; - private final QueryApi queryApi; - private final ApiClient apiClient; private final VaultConfig vaultConfig; + private final ApiClientBuilder apiClientBuilder; + private ApiClient apiClient; private Credentials commonCredentials; private Credentials finalCredentials; private String token; @@ -45,28 +61,29 @@ protected VaultClient(VaultConfig vaultConfig, Credentials credentials) { super(); this.vaultConfig = vaultConfig; this.commonCredentials = credentials; - this.apiClient = new ApiClient(); - apiClient.addDefaultHeader(Constants.SDK_METRICS_HEADER_KEY, Utils.getMetrics().toString()); - this.recordsApi = new RecordsApi(this.apiClient); - this.tokensApi = new TokensApi(this.apiClient); - this.queryApi = new QueryApi(this.apiClient); + this.apiClientBuilder = new ApiClientBuilder(); + this.apiClient = null; updateVaultURL(); } - protected RecordsApi getRecordsApi() { - return recordsApi; + protected RecordsClient getRecordsApi() { + return this.apiClient.records(); + } + + protected TokensClient getTokensApi() { + return this.apiClient.tokens(); } - protected TokensApi getTokensApi() { - return tokensApi; + protected StringsClient getDetectTextApi() { + return this.apiClient.strings(); } - protected QueryApi getQueryApi() { - return queryApi; + protected FilesClient getDetectFileAPi(){ + return this.apiClient.files(); } - protected ApiClient getApiClient() { - return apiClient; + protected QueryClient getQueryApi() { + return this.apiClient.query(); } protected VaultConfig getVaultConfig() { @@ -84,121 +101,690 @@ protected void updateVaultConfig() throws SkyflowException { } protected V1DetokenizePayload getDetokenizePayload(DetokenizeRequest request) { - V1DetokenizePayload payload = new V1DetokenizePayload(); - payload.setContinueOnError(request.getContinueOnError()); - payload.setDownloadURL(request.getDownloadURL()); + List recordRequests = new ArrayList<>(); + for (DetokenizeData detokenizeDataRecord : request.getDetokenizeData()) { - V1DetokenizeRecordRequest recordRequest = new V1DetokenizeRecordRequest(); - recordRequest.setToken(detokenizeDataRecord.getToken()); - recordRequest.setRedaction(detokenizeDataRecord.getRedactionType().getRedaction()); - payload.addDetokenizationParametersItem(recordRequest); + V1DetokenizeRecordRequest recordRequest = V1DetokenizeRecordRequest.builder() + .token(detokenizeDataRecord.getToken()) + .redaction(detokenizeDataRecord.getRedactionType().getRedaction()) + .build(); + recordRequests.add(recordRequest); } - return payload; + + return V1DetokenizePayload.builder() + .continueOnError(request.getContinueOnError()) + .downloadUrl(request.getDownloadURL()) + .detokenizationParameters(recordRequests) + .build(); } protected RecordServiceInsertRecordBody getBulkInsertRequestBody(InsertRequest request) { - RecordServiceInsertRecordBody insertRecordBody = new RecordServiceInsertRecordBody(); - insertRecordBody.setTokenization(request.getReturnTokens()); - insertRecordBody.setHomogeneous(request.getHomogeneous()); - insertRecordBody.setUpsert(request.getUpsert()); - insertRecordBody.setByot(request.getTokenMode().getBYOT()); - List> values = request.getValues(); List> tokens = request.getTokens(); List records = new ArrayList<>(); + for (int index = 0; index < values.size(); index++) { - V1FieldRecords record = new V1FieldRecords(); - record.setFields(values.get(index)); + V1FieldRecords.Builder recordBuilder = V1FieldRecords.builder().fields(values.get(index)); if (tokens != null && index < tokens.size()) { - record.setTokens(tokens.get(index)); + recordBuilder.tokens(tokens.get(index)); } - records.add(record); + records.add(recordBuilder.build()); } - insertRecordBody.setRecords(records); - return insertRecordBody; + + return RecordServiceInsertRecordBody.builder() + .tokenization(request.getReturnTokens()) + .homogeneous(request.getHomogeneous()) + .upsert(request.getUpsert()) + .byot(request.getTokenMode().getBYOT()) + .records(records) + .build(); } protected RecordServiceBatchOperationBody getBatchInsertRequestBody(InsertRequest request) { - RecordServiceBatchOperationBody insertRequestBody = new RecordServiceBatchOperationBody(); - insertRequestBody.setContinueOnError(true); - insertRequestBody.setByot(request.getTokenMode().getBYOT()); - ArrayList> values = request.getValues(); ArrayList> tokens = request.getTokens(); List records = new ArrayList<>(); for (int index = 0; index < values.size(); index++) { - V1BatchRecord record = new V1BatchRecord(); - record.setMethod(BatchRecordMethod.POST); - record.setTableName(request.getTable()); - record.setUpsert(request.getUpsert()); - record.setTokenization(request.getReturnTokens()); - record.setFields(values.get(index)); + V1BatchRecord.Builder recordBuilder = V1BatchRecord.builder() + .method(BatchRecordMethod.POST) + .tableName(request.getTable()) + .upsert(request.getUpsert()) + .tokenization(request.getReturnTokens()) + .fields(values.get(index)); + if (tokens != null && index < tokens.size()) { - record.setTokens(tokens.get(index)); + recordBuilder.tokens(tokens.get(index)); } - records.add(record); + + records.add(recordBuilder.build()); } - insertRequestBody.setRecords(records); - return insertRequestBody; + return RecordServiceBatchOperationBody.builder() + .continueOnError(true) + .byot(request.getTokenMode().getBYOT()) + .records(records) + .build(); } protected RecordServiceUpdateRecordBody getUpdateRequestBody(UpdateRequest request) { - RecordServiceUpdateRecordBody updateRequestBody = new RecordServiceUpdateRecordBody(); - updateRequestBody.byot(request.getTokenMode().getBYOT()); - updateRequestBody.setTokenization(request.getReturnTokens()); + RecordServiceUpdateRecordBody.Builder updateRequestBodyBuilder = RecordServiceUpdateRecordBody.builder(); + updateRequestBodyBuilder.byot(request.getTokenMode().getBYOT()); + updateRequestBodyBuilder.tokenization(request.getReturnTokens()); + V1FieldRecords.Builder recordBuilder = V1FieldRecords.builder(); HashMap values = request.getData(); + + if (values != null) { + recordBuilder.fields(values); + } + HashMap tokens = request.getTokens(); - V1FieldRecords record = new V1FieldRecords(); - record.setFields(values); if (tokens != null) { - record.setTokens(tokens); + recordBuilder.tokens(tokens); } - updateRequestBody.setRecord(record); - return updateRequestBody; + + updateRequestBodyBuilder.record(recordBuilder.build()); + + return updateRequestBodyBuilder.build(); } protected V1TokenizePayload getTokenizePayload(TokenizeRequest request) { - V1TokenizePayload payload = new V1TokenizePayload(); + List tokenizationParameters = new ArrayList<>(); + for (ColumnValue columnValue : request.getColumnValues()) { - V1TokenizeRecordRequest recordRequest = new V1TokenizeRecordRequest(); - recordRequest.setValue(columnValue.getValue()); - recordRequest.setColumnGroup(columnValue.getColumnGroup()); - payload.addTokenizationParametersItem(recordRequest); + V1TokenizeRecordRequest.Builder recordBuilder = V1TokenizeRecordRequest.builder(); + String value = columnValue.getValue(); + recordBuilder.value(value); + String columnGroup = columnValue.getColumnGroup(); + recordBuilder.columnGroup(columnGroup); + tokenizationParameters.add(recordBuilder.build()); } - return payload; + + V1TokenizePayload.Builder payloadBuilder = V1TokenizePayload.builder(); + + if (!tokenizationParameters.isEmpty()) { + payloadBuilder.tokenizationParameters(tokenizationParameters); + } + + return payloadBuilder.build(); } protected void setBearerToken() throws SkyflowException { prioritiseCredentials(); Validations.validateCredentials(this.finalCredentials); if (this.finalCredentials.getApiKey() != null) { - setApiKey(); - return; + LogUtil.printInfoLog(InfoLogs.REUSE_API_KEY.getLog()); + token=this.finalCredentials.getApiKey(); } else if (Token.isExpired(token)) { LogUtil.printInfoLog(InfoLogs.BEARER_TOKEN_EXPIRED.getLog()); token = Utils.generateBearerToken(this.finalCredentials); } else { LogUtil.printInfoLog(InfoLogs.REUSE_BEARER_TOKEN.getLog()); } - HttpBearerAuth Bearer = (HttpBearerAuth) this.apiClient.getAuthentication("Bearer"); - Bearer.setBearerToken(token); + this.apiClientBuilder.token(token); + this.apiClient = this.apiClientBuilder.build(); + } + + protected DeidentifyTextResponse getDeIdentifyTextResponse(DeidentifyStringResponse deidentifyStringResponse) { + List entities = deidentifyStringResponse.getEntities() != null + ? deidentifyStringResponse.getEntities().stream() + .map(this::convertDetectedEntityToEntityInfo) + .collect(Collectors.toList()) + : null; + + return new DeidentifyTextResponse( + deidentifyStringResponse.getProcessedText(), + entities, + deidentifyStringResponse.getWordCount(), + deidentifyStringResponse.getCharacterCount() + ); + } + + protected DeidentifyStringRequest getDeidentifyStringRequest(DeidentifyTextRequest deIdentifyTextRequest, String vaultId) throws SkyflowException { + List entities = deIdentifyTextRequest.getEntities(); + + List mappedEntityTypes = null; + if (entities != null) { + mappedEntityTypes = deIdentifyTextRequest.getEntities().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList()); + } + + TokenFormat tokenFormat = deIdentifyTextRequest.getTokenFormat(); + + Optional> vaultToken = Optional.empty(); + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(deIdentifyTextRequest.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(deIdentifyTextRequest.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(deIdentifyTextRequest.getTransformations())); + + if (tokenFormat != null) { + if (tokenFormat.getVaultToken() != null && !tokenFormat.getVaultToken().isEmpty()) { + vaultToken = Optional.of(tokenFormat.getVaultToken().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { + entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { + entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + } + + TokenType tokenType = TokenType.builder() + .vaultToken(vaultToken) + .entityOnly(entityTypes) + .entityUnqCounter(entityUniqueCounter) + .build(); + + + return DeidentifyStringRequest.builder() + .vaultId(vaultId) + .text(deIdentifyTextRequest.getText()) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .transformations(transformations) + .build(); + } + + protected ReidentifyStringRequest getReidentifyStringRequest(ReidentifyTextRequest reidentifyTextRequest, String vaultId) throws SkyflowException { + List maskEntities = null; + List redactedEntities = null; + List plaintextEntities = null; + + if (reidentifyTextRequest.getMaskedEntities() != null) { + maskEntities = reidentifyTextRequest.getMaskedEntities().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList()); + } + + if (reidentifyTextRequest.getPlainTextEntities() != null) { + plaintextEntities = reidentifyTextRequest.getPlainTextEntities().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList()); + } + + if (reidentifyTextRequest.getRedactedEntities() != null) { + redactedEntities = reidentifyTextRequest.getRedactedEntities().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList()); + } + + ReidentifyStringRequestFormat reidentifyStringRequestFormat = ReidentifyStringRequestFormat.builder() + .masked(maskEntities) + .plaintext(plaintextEntities) + .redacted(redactedEntities) + .build(); + + + return ReidentifyStringRequest.builder() + .text(reidentifyTextRequest.getText()) + .vaultId(vaultId) + .format(reidentifyStringRequestFormat) + .build(); } - private void setApiKey() { - if (apiKey == null) { - apiKey = this.finalCredentials.getApiKey(); + + private EntityInfo convertDetectedEntityToEntityInfo(DetectedEntity detectedEntity) { + TextIndex textIndex = new TextIndex( + detectedEntity.getLocation().get().getStartIndex().orElse(0), + detectedEntity.getLocation().get().getEndIndex().orElse(0) + ); + TextIndex processedIndex = new TextIndex( + detectedEntity.getLocation().get().getStartIndexProcessed().orElse(0), + detectedEntity.getLocation().get().getEndIndexProcessed().orElse(0) + ); + + Map entityScores = detectedEntity.getEntityScores() + .map(doubleMap -> doubleMap.entrySet().stream() + .collect(Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue + ))) + .orElse(Collections.emptyMap()); + + + return new EntityInfo( + detectedEntity.getToken().orElse(""), + detectedEntity.getValue().orElse(""), + textIndex, + processedIndex, + detectedEntity.getEntityType().orElse(""), + entityScores); + } + + + private Transformations getTransformations(com.skyflow.vault.detect.Transformations transformations) { + if (transformations == null || transformations.getShiftDates() == null) { + return null; + } + + List entityTypes = null; + if (!transformations.getShiftDates().getEntities().isEmpty()) { + entityTypes = transformations.getShiftDates().getEntities().stream() + .map(entity -> TransformationsShiftDatesEntityTypesItem.valueOf(entity.name())) + .collect(Collectors.toList()); } else { - LogUtil.printInfoLog(InfoLogs.REUSE_API_KEY.getLog()); + entityTypes = Collections.emptyList(); + } + + return Transformations.builder() + .shiftDates(TransformationsShiftDates.builder() + .maxDays(transformations.getShiftDates().getMax()) + .minDays(transformations.getShiftDates().getMin()) + .entityTypes(entityTypes) + .build()) + .build(); + } + + private List getEntityTypes(List entities){ + List mappedEntityTypes = null; + if (entities != null) { + mappedEntityTypes = entities.stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList()); + } + + return mappedEntityTypes; + } + + protected com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest getDeidentifyTextFileRequest(DeidentifyFileRequest request, String vaultId, String base64Content){ + List mappedEntityTypes = getEntityTypes(request.getEntities()); + + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); + + if (tokenFormat != null) { + + if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { + entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { + entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + } + + TokenTypeWithoutVault tokenType = TokenTypeWithoutVault.builder() + .entityOnly(entityTypes) + .entityUnqCounter(entityUniqueCounter) + .build(); + + DeidentifyTextRequestFile file = DeidentifyTextRequestFile.builder() + .base64(base64Content) + .build(); + + // Build the final request + com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest req = + com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .transformations(transformations) + .build(); + + return req; + } + + + protected DeidentifyAudioRequest getDeidentifyAudioRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String dataFormat) throws SkyflowException { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); + + if (tokenFormat != null) { + + if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { + entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { + entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + } + + TokenTypeWithoutVault tokenType = TokenTypeWithoutVault.builder() + .entityOnly(entityTypes) + .entityUnqCounter(entityUniqueCounter) + .build(); + + DeidentifyAudioRequestFile deidentifyAudioRequestFile = DeidentifyAudioRequestFile.builder().base64(base64Content).dataFormat(mapAudioDataFormat(dataFormat)).build(); + DetectOutputTranscriptions transcription = request.getOutputTranscription(); + DeidentifyAudioRequestOutputTranscription outputTranscriptionType = null; + if (transcription != null) { + outputTranscriptionType = DeidentifyAudioRequestOutputTranscription.valueOf(transcription.name()); + } + + return DeidentifyAudioRequest.builder() + .vaultId(vaultId) + .file(deidentifyAudioRequestFile) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .entityTypes(mappedEntityTypes) + .bleepFrequency(request.getBleep() != null ? request.getBleep().getFrequency() : null) + .bleepGain(request.getBleep() != null ? request.getBleep().getGain() : null) + .bleepStartPadding(request.getBleep() != null ? request.getBleep().getStartPadding() : null) + .bleepStopPadding(request.getBleep() != null ? request.getBleep().getStopPadding() : null) + .outputProcessedAudio(request.getOutputProcessedAudio()) + .outputTranscription(outputTranscriptionType) + .tokenType(tokenType) + .transformations(transformations) + .build(); + } + + protected DeidentifyPdfRequest getDeidentifyPdfRequest(DeidentifyFileRequest request, String vaultId, String base64Content) { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + + TokenFormat tokenFormat = request.getTokenFormat(); + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); + + if (tokenFormat != null) { + if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { + entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { + entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + } + + TokenTypeWithoutVault tokenType = TokenTypeWithoutVault.builder() + .entityOnly(entityTypes) + .entityUnqCounter(entityUniqueCounter) + .build(); + + DeidentifyPdfRequestFile file = DeidentifyPdfRequestFile.builder() + .base64(base64Content) + .build(); + + return DeidentifyPdfRequest.builder() + .vaultId(vaultId) + .file(file) + .density(request.getPixelDensity() != null ? request.getPixelDensity().intValue() : null) + .maxResolution(request.getMaxResolution() != null ? request.getMaxResolution().intValue() : null) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .transformations(transformations) + .build(); + } + + protected DeidentifyImageRequest getDeidentifyImageRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + + TokenFormat tokenFormat = request.getTokenFormat(); + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); + + TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); + + DeidentifyImageRequestFile file = DeidentifyImageRequestFile.builder() + .base64(base64Content) + .dataFormat(DeidentifyImageRequestFileDataFormat.valueOf(format.toUpperCase())) + .build(); + + Optional maskingMethod = Optional.empty(); + if (request.getMaskingMethod() != null) { + maskingMethod = Optional.of(DeidentifyImageRequestMaskingMethod.valueOf(request.getMaskingMethod().name())); + } + + return DeidentifyImageRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .maskingMethod(maskingMethod) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .transformations(transformations) + .outputProcessedImage(request.getOutputProcessedImage()) + .outputOcrText(request.getOutputOcrText()) + .build(); + } + + protected DeidentifyPresentationRequest getDeidentifyPresentationRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); + + TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); + + DeidentifyPresentationRequestFile file = DeidentifyPresentationRequestFile.builder() + .base64(base64Content) + .dataFormat(DeidentifyPresentationRequestFileDataFormat.valueOf(format.toUpperCase())) + .build(); + + return DeidentifyPresentationRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .transformations(transformations) + .build(); + } + + protected DeidentifySpreadsheetRequest getDeidentifySpreadsheetRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); + + TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); + + DeidentifySpreadsheetRequestFile file = DeidentifySpreadsheetRequestFile.builder() + .base64(base64Content) + .dataFormat(DeidentifySpreadsheetRequestFileDataFormat.valueOf(format.toUpperCase())) + .build(); + + return DeidentifySpreadsheetRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .transformations(transformations) + .build(); + } + + protected DeidentifyStructuredTextRequest getDeidentifyStructuredTextRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); + + TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); + + DeidentifyStructuredTextRequestFile file = DeidentifyStructuredTextRequestFile.builder() + .base64(base64Content) + .dataFormat(DeidentifyStructuredTextRequestFileDataFormat.valueOf(format.toUpperCase())) + .build(); + + return DeidentifyStructuredTextRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .transformations(transformations) + .build(); + } + + protected DeidentifyDocumentRequest getDeidentifyDocumentRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); + + TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); + + DeidentifyDocumentRequestFile file = DeidentifyDocumentRequestFile.builder() + .base64(base64Content) + .dataFormat(DeidentifyDocumentRequestFileDataFormat.valueOf(format.toUpperCase())) + .build(); + + return DeidentifyDocumentRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .transformations(transformations) + .build(); + } + + protected com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest getDeidentifyGenericFileRequest( + DeidentifyFileRequest request, String vaultId, String base64Content, String fileExtension) { + + List mappedEntityTypes = getEntityTypes(request.getEntities()); + + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); + + if (tokenFormat != null) { + if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { + entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { + entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + } + + TokenTypeWithoutVault tokenType = TokenTypeWithoutVault.builder() + .entityOnly(entityTypes) + .entityUnqCounter(entityUniqueCounter) + .build(); + + DeidentifyFileRequestFile file = + DeidentifyFileRequestFile.builder() + .base64(base64Content) + .dataFormat(fileExtension != null ? DeidentifyFileRequestFileDataFormat.valueOf(fileExtension.toUpperCase()) : null) + .build(); + + return com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .transformations(transformations) + .build(); + } + + private TokenTypeWithoutVault buildTokenType(TokenFormat tokenFormat, + Optional> entityTypes, + Optional> entityUniqueCounter) { + + if (tokenFormat != null) { + if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { + entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { + entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + } + + return TokenTypeWithoutVault.builder() + .entityOnly(entityTypes) + .entityUnqCounter(entityUniqueCounter) + .build(); + } + + private DeidentifyAudioRequestFileDataFormat mapAudioDataFormat(String dataFormat) throws SkyflowException { + switch (dataFormat) { + case "mp3": + return DeidentifyAudioRequestFileDataFormat.MP_3; + case "wav": + return DeidentifyAudioRequestFileDataFormat.WAV; + default: + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidAudioFileType.getMessage()); } - HttpBearerAuth Bearer = (HttpBearerAuth) this.apiClient.getAuthentication("Bearer"); - Bearer.setBearerToken(apiKey); } private void updateVaultURL() { String vaultURL = Utils.getVaultURL(this.vaultConfig.getClusterId(), this.vaultConfig.getEnv()); - this.apiClient.setBasePath(vaultURL); + this.apiClientBuilder.url(vaultURL); } private void prioritiseCredentials() throws SkyflowException { diff --git a/src/main/java/com/skyflow/enums/DeidentifyFileStatus.java b/src/main/java/com/skyflow/enums/DeidentifyFileStatus.java new file mode 100644 index 00000000..e17c6d0c --- /dev/null +++ b/src/main/java/com/skyflow/enums/DeidentifyFileStatus.java @@ -0,0 +1,16 @@ +package com.skyflow.enums; + +public enum DeidentifyFileStatus { + IN_PROGRESS("IN_PROGRESS"), + SUCCESS("SUCCESS"); + + private final String value; + + DeidentifyFileStatus(String value) { + this.value = value; + } + + public String value() { + return value; + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/enums/DetectEntities.java b/src/main/java/com/skyflow/enums/DetectEntities.java new file mode 100644 index 00000000..f2c21eff --- /dev/null +++ b/src/main/java/com/skyflow/enums/DetectEntities.java @@ -0,0 +1,83 @@ +package com.skyflow.enums; + + +public enum DetectEntities { + ACCOUNT_NUMBER("account_number"), + AGE("age"), + ALL("all"), + BANK_ACCOUNT("bank_account"), + BLOOD_TYPE("blood_type"), + CONDITION("condition"), + CORPORATE_ACTION("corporate_action"), + CREDIT_CARD("credit_card"), + CREDIT_CARD_EXPIRATION("credit_card_expiration"), + CVV("cvv"), + DATE("date"), + DATE_INTERVAL("date_interval"), + DOB("dob"), + DOSE("dose"), + DRIVER_LICENSE("driver_license"), + DRUG("drug"), + DURATION("duration"), + EMAIL_ADDRESS("email_address"), + EVENT("event"), + FILENAME("filename"), + FINANCIAL_METRIC("financial_metric"), + GENDER_SEXUALITY("gender_sexuality"), + HEALTHCARE_NUMBER("healthcare_number"), + INJURY("injury"), + IP_ADDRESS("ip_address"), + LANGUAGE("language"), + LOCATION("location"), + LOCATION_ADDRESS("location_address"), + LOCATION_ADDRESS_STREET("location_address_street"), + LOCATION_CITY("location_city"), + LOCATION_COORDINATE("location_coordinate"), + LOCATION_COUNTRY("location_country"), + LOCATION_STATE("location_state"), + LOCATION_ZIP("location_zip"), + MARITAL_STATUS("marital_status"), + MEDICAL_CODE("medical_code"), + MEDICAL_PROCESS("medical_process"), + MONEY("money"), + NAME("name"), + NAME_FAMILY("name_family"), + NAME_GIVEN("name_given"), + NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), + NUMERICAL_PII("numerical_pii"), + OCCUPATION("occupation"), + ORGANIZATION("organization"), + ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), + ORIGIN("origin"), + PASSPORT_NUMBER("passport_number"), + PASSWORD("password"), + PHONE_NUMBER("phone_number"), + PHYSICAL_ATTRIBUTE("physical_attribute"), + POLITICAL_AFFILIATION("political_affiliation"), + PRODUCT("product"), + RELIGION("religion"), + ROUTING_NUMBER("routing_number"), + SSN("ssn"), + STATISTICS("statistics"), + TIME("time"), + TREND("trend"), + URL("url"), + USERNAME("username"), + VEHICLE_ID("vehicle_id"), + ZODIAC_SIGN("zodiac_sign"); + + private final String detectEntities; + + DetectEntities(String detectEntities) { + this.detectEntities = detectEntities; + } + + public String getDetectEntities() { + return detectEntities; + } + + @Override + public String toString() { + return detectEntities; + } +} diff --git a/src/main/java/com/skyflow/enums/DetectOutputTranscriptions.java b/src/main/java/com/skyflow/enums/DetectOutputTranscriptions.java new file mode 100644 index 00000000..43251c61 --- /dev/null +++ b/src/main/java/com/skyflow/enums/DetectOutputTranscriptions.java @@ -0,0 +1,24 @@ +package com.skyflow.enums; + +public enum DetectOutputTranscriptions { + DIARIZED_TRANSCRIPTION("diarized_transcription"), + MEDICAL_DIARIZED_TRANSCRIPTION("medical_diarized_transcription"), + MEDICAL_TRANSCRIPTION("medical_transcription"), + PLAINTEXT_TRANSCRIPTION("plaintext_transcription"), + TRANSCRIPTION("transcription"); + + private final String detectOutputTranscriptions; + + DetectOutputTranscriptions(String detectOutputTranscriptions) { + this.detectOutputTranscriptions = detectOutputTranscriptions; + } + + public String getDetectOutputTranscriptions() { + return detectOutputTranscriptions; + } + + @Override + public String toString() { + return detectOutputTranscriptions; + } +} diff --git a/src/main/java/com/skyflow/enums/InterfaceName.java b/src/main/java/com/skyflow/enums/InterfaceName.java index 643bf9da..98992f21 100644 --- a/src/main/java/com/skyflow/enums/InterfaceName.java +++ b/src/main/java/com/skyflow/enums/InterfaceName.java @@ -9,6 +9,7 @@ public enum InterfaceName { QUERY("query"), TOKENIZE("tokenize"), FILE_UPLOAD("file upload"), + DETECT("detect"), INVOKE_CONNECTION("invoke connection"); private final String interfaceName; diff --git a/src/main/java/com/skyflow/enums/MaskingMethod.java b/src/main/java/com/skyflow/enums/MaskingMethod.java new file mode 100644 index 00000000..e3ff252c --- /dev/null +++ b/src/main/java/com/skyflow/enums/MaskingMethod.java @@ -0,0 +1,21 @@ +package com.skyflow.enums; + +public enum MaskingMethod { + BLACKBOX("blackbox"), + BLUR("blur"); + + private final String maskingMethod; + + MaskingMethod(String maskingMethod) { + this.maskingMethod = maskingMethod; + } + + public String getMaskingMethod() { + return maskingMethod; + } + + @Override + public String toString() { + return maskingMethod; + } +} diff --git a/src/main/java/com/skyflow/enums/RedactionType.java b/src/main/java/com/skyflow/enums/RedactionType.java index af86a560..9c76cc7d 100644 --- a/src/main/java/com/skyflow/enums/RedactionType.java +++ b/src/main/java/com/skyflow/enums/RedactionType.java @@ -1,20 +1,21 @@ package com.skyflow.enums; -import com.skyflow.generated.rest.models.RedactionEnumREDACTION; + +import com.skyflow.generated.rest.types.RedactionEnumRedaction; public enum RedactionType { - PLAIN_TEXT(RedactionEnumREDACTION.PLAIN_TEXT), - MASKED(RedactionEnumREDACTION.MASKED), - DEFAULT(RedactionEnumREDACTION.DEFAULT), - REDACTED(RedactionEnumREDACTION.REDACTED); + PLAIN_TEXT(RedactionEnumRedaction.PLAIN_TEXT), + MASKED(RedactionEnumRedaction.MASKED), + DEFAULT(RedactionEnumRedaction.DEFAULT), + REDACTED(RedactionEnumRedaction.REDACTED); - private final RedactionEnumREDACTION redaction; + private final RedactionEnumRedaction redaction; - RedactionType(RedactionEnumREDACTION redaction) { + RedactionType(RedactionEnumRedaction redaction) { this.redaction = redaction; } - public RedactionEnumREDACTION getRedaction() { + public RedactionEnumRedaction getRedaction() { return redaction; } diff --git a/src/main/java/com/skyflow/enums/TokenMode.java b/src/main/java/com/skyflow/enums/TokenMode.java index 28564bb5..63e9b8a9 100644 --- a/src/main/java/com/skyflow/enums/TokenMode.java +++ b/src/main/java/com/skyflow/enums/TokenMode.java @@ -1,24 +1,24 @@ package com.skyflow.enums; -import com.skyflow.generated.rest.models.V1BYOT; +import com.skyflow.generated.rest.types.V1Byot; public enum TokenMode { - DISABLE(V1BYOT.DISABLE), - ENABLE(V1BYOT.ENABLE), - ENABLE_STRICT(V1BYOT.ENABLE_STRICT); + DISABLE(V1Byot.DISABLE), + ENABLE(V1Byot.ENABLE), + ENABLE_STRICT(V1Byot.ENABLE_STRICT); - private final V1BYOT byot; + private final V1Byot byot; - TokenMode(V1BYOT byot) { + TokenMode(V1Byot byot) { this.byot = byot; } - public V1BYOT getBYOT() { + public V1Byot getBYOT() { return byot; } @Override public String toString() { - return String.valueOf(byot); + return byot.toString(); } } diff --git a/src/main/java/com/skyflow/enums/TokenType.java b/src/main/java/com/skyflow/enums/TokenType.java new file mode 100644 index 00000000..4a619e9c --- /dev/null +++ b/src/main/java/com/skyflow/enums/TokenType.java @@ -0,0 +1,27 @@ +package com.skyflow.enums; + +public enum TokenType { + VAULT_TOKEN("vault_token"), + ENTITY_UNIQUE_COUNTER("entity_unq_counter"), + ENTITY_ONLY("entity_only"); + + private final String tokenType; + + TokenType(String tokenType) { + this.tokenType = tokenType; + } + + public String getTokenType() { + return tokenType; + } + + public String getDefault() { + return ENTITY_UNIQUE_COUNTER.getTokenType(); + } + + @Override + public String toString() { + return tokenType; + } +} + diff --git a/src/main/java/com/skyflow/errors/ErrorMessage.java b/src/main/java/com/skyflow/errors/ErrorMessage.java index 33833443..df075bca 100644 --- a/src/main/java/com/skyflow/errors/ErrorMessage.java +++ b/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -124,6 +124,29 @@ public enum ErrorMessage { InvalidRequestBody("%s0 Validation error. Invalid request body. Specify the request body as an object."), EmptyRequestBody("%s0 Validation error. Request body can't be empty. Specify a valid request body."), + // detect + InvalidTextInDeIdentify("%s0 Validation error. The text field is required and must be a non-empty string. Specify a valid text."), + InvalidTextInReIdentify("%s0 Validation error. The text field is required and must be a non-empty string. Specify a valid text."), + + //Detect Files + InvalidNullFileInDeIdentifyFile("%s0 Validation error. The file field is required and must not be null. Specify a valid file object."), + InvalidFilePath("%s0 Validation error. The file path is invalid. Specify a valid file path."), + BothFileAndFilePathProvided("%s0 Validation error. Both file and filePath are provided. Specify either file object or filePath, not both."), + FileNotFoundToDeidentify("%s0 Validation error. The file to deidentify was not found at the specified path. Verify the file path and try again."), + FileNotReadableToDeidentify("%s0 Validation error. The file to deidentify is not readable. Check the file permissions and try again."), + InvalidPixelDensityToDeidentifyFile("%s0 Validation error. Should be a positive integer. Specify a valid pixel density."), + InvalidMaxResolution("%s0 Validation error. Should be a positive integer. Specify a valid max resolution."), + OutputDirectoryNotFound("%s0 Validation error. The output directory for deidentified files was not found at the specified path. Verify the output directory path and try again."), + InvalidPermission("%s0 Validation error. The output directory for deidentified files is not writable. Check the directory permissions and try again."), + InvalidWaitTime("%s0 Validation error. The wait time for deidentify file operation should be a positive integer. Specify a valid wait time."), + WaitTimeExceedsLimit("%s0 Validation error. The wait time for deidentify file operation exceeds the maximum limit of 64 seconds. Specify a wait time less than or equal to 60 seconds."), + InvalidOrEmptyRunId("%s0 Validation error. The run ID is invalid or empty. Specify a valid run ID."), + FailedToEncodeFile("%s0 Validation error. Failed to encode the file. Ensure the file is in a supported format and try again."), + FailedToDecodeFileFromResponse("%s0 Failed to decode the file from the response. Ensure the response is valid and try again."), + EmptyFileAndFilePathInDeIdentifyFile("%s0 Validation error. Both file and filePath are empty. Specify either file object or filePath, not both."), + PollingForResultsFailed("%s0 API error. Polling for results failed. Unable to retrieve the deidentified file"), + FailedtoSaveProcessedFile("%s0 Validation error. Failed to save the processed file. Ensure the output directory is valid and writable."), + InvalidAudioFileType("%s0 Validation error. The file type is not supported. Specify a valid file type mp3 or wav."), // Generic ErrorOccurred("%s0 API error. Error occurred.") ; diff --git a/src/main/java/com/skyflow/generated/rest/ApiCallback.java b/src/main/java/com/skyflow/generated/rest/ApiCallback.java deleted file mode 100644 index 84a241d3..00000000 --- a/src/main/java/com/skyflow/generated/rest/ApiCallback.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.

  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest; - -import java.io.IOException; - -import java.util.Map; -import java.util.List; - -/** - * Callback for asynchronous API call. - * - * @param The return type - */ -public interface ApiCallback { - /** - * This is called when the API call fails. - * - * @param e The exception causing the failure - * @param statusCode Status code of the response if available, otherwise it would be 0 - * @param responseHeaders Headers of the response if available, otherwise it would be null - */ - void onFailure(ApiException e, int statusCode, Map> responseHeaders); - - /** - * This is called when the API call succeeded. - * - * @param result The result deserialized from response - * @param statusCode Status code of the response - * @param responseHeaders Headers of the response - */ - void onSuccess(T result, int statusCode, Map> responseHeaders); - - /** - * This is called when the API upload processing. - * - * @param bytesWritten bytes Written - * @param contentLength content length of request body - * @param done write end - */ - void onUploadProgress(long bytesWritten, long contentLength, boolean done); - - /** - * This is called when the API download processing. - * - * @param bytesRead bytes Read - * @param contentLength content length of the response - * @param done Read end - */ - void onDownloadProgress(long bytesRead, long contentLength, boolean done); -} diff --git a/src/main/java/com/skyflow/generated/rest/ApiClient.java b/src/main/java/com/skyflow/generated/rest/ApiClient.java index bb0391a4..296a553f 100644 --- a/src/main/java/com/skyflow/generated/rest/ApiClient.java +++ b/src/main/java/com/skyflow/generated/rest/ApiClient.java @@ -1,1615 +1,92 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. +/** + * This file was auto-generated by Fern from our API Definition. */ - - package com.skyflow.generated.rest; -import okhttp3.*; -import okhttp3.internal.http.HttpMethod; -import okhttp3.internal.tls.OkHostnameVerifier; -import okhttp3.logging.HttpLoggingInterceptor; -import okhttp3.logging.HttpLoggingInterceptor.Level; -import okio.Buffer; -import okio.BufferedSink; -import okio.Okio; - -import javax.net.ssl.*; -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; -import java.nio.file.Paths; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.text.DateFormat; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.TimeUnit; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.Suppliers; +import com.skyflow.generated.rest.resources.audit.AuditClient; +import com.skyflow.generated.rest.resources.authentication.AuthenticationClient; +import com.skyflow.generated.rest.resources.binlookup.BinLookupClient; +import com.skyflow.generated.rest.resources.deprecated.DeprecatedClient; +import com.skyflow.generated.rest.resources.files.FilesClient; +import com.skyflow.generated.rest.resources.query.QueryClient; +import com.skyflow.generated.rest.resources.records.RecordsClient; +import com.skyflow.generated.rest.resources.strings.StringsClient; +import com.skyflow.generated.rest.resources.tokens.TokensClient; import java.util.function.Supplier; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import com.skyflow.generated.rest.auth.Authentication; -import com.skyflow.generated.rest.auth.HttpBasicAuth; -import com.skyflow.generated.rest.auth.HttpBearerAuth; -import com.skyflow.generated.rest.auth.ApiKeyAuth; - -/** - *

ApiClient class.

- */ public class ApiClient { + protected final ClientOptions clientOptions; - private String basePath = "https://identifier.vault.skyflowapis.com"; - protected List servers = new ArrayList(Arrays.asList( - new ServerConfiguration( - "https://identifier.vault.skyflowapis.com", - "Production", - new HashMap() - ), - new ServerConfiguration( - "https://identifier.vault.skyflowapis-preview.com", - "Sandbox", - new HashMap() - ) - )); - protected Integer serverIndex = 0; - protected Map serverVariables = null; - private boolean debugging = false; - private Map defaultHeaderMap = new HashMap(); - private Map defaultCookieMap = new HashMap(); - private String tempFolderPath = null; - - private Map authentications; - - private DateFormat dateFormat; - private DateFormat datetimeFormat; - private boolean lenientDatetimeFormat; - private int dateLength; - - private InputStream sslCaCert; - private boolean verifyingSsl; - private KeyManager[] keyManagers; - - private OkHttpClient httpClient; - private JSON json; - - private HttpLoggingInterceptor loggingInterceptor; - - /** - * Basic constructor for ApiClient - */ - public ApiClient() { - init(); - initHttpClient(); - - // Setup authentications (key: authentication name, value: authentication). - authentications.put("Bearer", new HttpBearerAuth("bearer")); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - /** - * Basic constructor with custom OkHttpClient - * - * @param client a {@link okhttp3.OkHttpClient} object - */ - public ApiClient(OkHttpClient client) { - init(); - - httpClient = client; - - // Setup authentications (key: authentication name, value: authentication). - authentications.put("Bearer", new HttpBearerAuth("bearer")); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - private void initHttpClient() { - initHttpClient(Collections.emptyList()); - } - - private void initHttpClient(List interceptors) { - OkHttpClient.Builder builder = new OkHttpClient.Builder(); - builder.addNetworkInterceptor(getProgressInterceptor()); - for (Interceptor interceptor: interceptors) { - builder.addInterceptor(interceptor); - } - - httpClient = builder.build(); - } - - private void init() { - verifyingSsl = true; - - json = new JSON(); - - // Set default User-Agent. - setUserAgent("OpenAPI-Generator/v1/java"); - - authentications = new HashMap(); - } - - /** - * Get base path - * - * @return Base path - */ - public String getBasePath() { - return basePath; - } - - /** - * Set base path - * - * @param basePath Base path of the URL (e.g https://identifier.vault.skyflowapis.com - * @return An instance of OkHttpClient - */ - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - this.serverIndex = null; - return this; - } - - public List getServers() { - return servers; - } - - public ApiClient setServers(List servers) { - this.servers = servers; - return this; - } - - public Integer getServerIndex() { - return serverIndex; - } - - public ApiClient setServerIndex(Integer serverIndex) { - this.serverIndex = serverIndex; - return this; - } - - public Map getServerVariables() { - return serverVariables; - } - - public ApiClient setServerVariables(Map serverVariables) { - this.serverVariables = 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 - * - * @return JSON object - */ - public JSON getJSON() { - return json; - } - - /** - * Set JSON - * - * @param json JSON object - * @return Api client - */ - public ApiClient setJSON(JSON json) { - this.json = json; - return this; - } - - /** - * True if isVerifyingSsl flag is on - * - * @return True if isVerifySsl flag is on - */ - public boolean isVerifyingSsl() { - return verifyingSsl; - } - - /** - * Configure whether to verify certificate and hostname when making https requests. - * Default to true. - * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. - * - * @param verifyingSsl True to verify TLS/SSL connection - * @return ApiClient - */ - public ApiClient setVerifyingSsl(boolean verifyingSsl) { - this.verifyingSsl = verifyingSsl; - applySslSettings(); - return this; - } - - /** - * Get SSL CA cert. - * - * @return Input stream to the SSL CA cert - */ - public InputStream getSslCaCert() { - return sslCaCert; - } - - /** - * Configure the CA certificate to be trusted when making https requests. - * Use null to reset to default. - * - * @param sslCaCert input stream for SSL CA cert - * @return ApiClient - */ - public ApiClient setSslCaCert(InputStream sslCaCert) { - this.sslCaCert = sslCaCert; - applySslSettings(); - return this; - } - - /** - *

Getter for the field keyManagers.

- * - * @return an array of {@link javax.net.ssl.KeyManager} objects - */ - public KeyManager[] getKeyManagers() { - return keyManagers; - } - - /** - * Configure client keys to use for authorization in an SSL session. - * Use null to reset to default. - * - * @param managers The KeyManagers to use - * @return ApiClient - */ - public ApiClient setKeyManagers(KeyManager[] managers) { - this.keyManagers = managers; - applySslSettings(); - return this; - } - - /** - *

Getter for the field dateFormat.

- * - * @return a {@link java.text.DateFormat} object - */ - public DateFormat getDateFormat() { - return dateFormat; - } - - /** - *

Setter for the field dateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link com.skyflow.generated.rest.ApiClient} object - */ - public ApiClient setDateFormat(DateFormat dateFormat) { - JSON.setDateFormat(dateFormat); - return this; - } - - /** - *

Set SqlDateFormat.

- * - * @param dateFormat a {@link java.text.DateFormat} object - * @return a {@link com.skyflow.generated.rest.ApiClient} object - */ - public ApiClient setSqlDateFormat(DateFormat dateFormat) { - JSON.setSqlDateFormat(dateFormat); - return this; - } - - /** - *

Set OffsetDateTimeFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link com.skyflow.generated.rest.ApiClient} object - */ - public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - JSON.setOffsetDateTimeFormat(dateFormat); - return this; - } - - /** - *

Set LocalDateFormat.

- * - * @param dateFormat a {@link java.time.format.DateTimeFormatter} object - * @return a {@link com.skyflow.generated.rest.ApiClient} object - */ - public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { - JSON.setLocalDateFormat(dateFormat); - return this; - } - - /** - *

Set LenientOnJson.

- * - * @param lenientOnJson a boolean - * @return a {@link com.skyflow.generated.rest.ApiClient} object - */ - public ApiClient setLenientOnJson(boolean lenientOnJson) { - JSON.setLenientOnJson(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 access token for the first Bearer authentication. - * @param bearerToken Bearer token - */ - public void setBearerToken(String bearerToken) { - setBearerToken(() -> bearerToken); - } - - /** - * Helper method to set the supplier of access tokens for Bearer authentication. - * - * @param tokenSupplier The supplier of bearer tokens - */ - public void setBearerToken(Supplier tokenSupplier) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBearerAuth) { - ((HttpBearerAuth) auth).setBearerToken(tokenSupplier); - return; - } - } - throw new RuntimeException("No Bearer authentication configured!"); - } - - /** - * 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). - * - * @param userAgent HTTP request's user agent - * @return ApiClient - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - * @return ApiClient - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * Add a default cookie. - * - * @param key The cookie's key - * @param value The cookie's value - * @return ApiClient - */ - public ApiClient addDefaultCookie(String key, String value) { - defaultCookieMap.put(key, value); - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - * - * @return True if debugging is enabled, false otherwise. - */ - public boolean isDebugging() { - return debugging; - } + protected final Supplier auditClient; - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - * @return ApiClient - */ - public ApiClient setDebugging(boolean debugging) { - if (debugging != this.debugging) { - if (debugging) { - loggingInterceptor = new HttpLoggingInterceptor(); - loggingInterceptor.setLevel(Level.BODY); - httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); - } else { - final OkHttpClient.Builder builder = httpClient.newBuilder(); - builder.interceptors().remove(loggingInterceptor); - httpClient = builder.build(); - loggingInterceptor = null; - } - } - this.debugging = debugging; - return this; - } + protected final Supplier binLookupClient; - /** - * The path of temporary folder used to store downloaded files from endpoints - * with file response. The default value is null, i.e. using - * the system's default temporary folder. - * - * @see createTempFile - * @return Temporary folder path - */ - public String getTempFolderPath() { - return tempFolderPath; - } + protected final Supplier recordsClient; - /** - * Set the temporary folder path (for downloading files) - * - * @param tempFolderPath Temporary folder path - * @return ApiClient - */ - public ApiClient setTempFolderPath(String tempFolderPath) { - this.tempFolderPath = tempFolderPath; - return this; - } + protected final Supplier tokensClient; - /** - * Get connection timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getConnectTimeout() { - return httpClient.connectTimeoutMillis(); - } + protected final Supplier queryClient; - /** - * Sets the connect timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param connectionTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setConnectTimeout(int connectionTimeout) { - httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } + protected final Supplier authenticationClient; - /** - * Get read timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getReadTimeout() { - return httpClient.readTimeoutMillis(); - } + protected final Supplier deprecatedClient; - /** - * Sets the read timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param readTimeout read timeout in milliseconds - * @return Api client - */ - public ApiClient setReadTimeout(int readTimeout) { - httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); - return this; - } + protected final Supplier stringsClient; - /** - * Get write timeout (in milliseconds). - * - * @return Timeout in milliseconds - */ - public int getWriteTimeout() { - return httpClient.writeTimeoutMillis(); - } + protected final Supplier filesClient; - /** - * Sets the write timeout (in milliseconds). - * A value of 0 means no timeout, otherwise values must be between 1 and - * {@link java.lang.Integer#MAX_VALUE}. - * - * @param writeTimeout connection timeout in milliseconds - * @return Api client - */ - public ApiClient setWriteTimeout(int writeTimeout) { - httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); - return this; + public ApiClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.auditClient = Suppliers.memoize(() -> new AuditClient(clientOptions)); + this.binLookupClient = Suppliers.memoize(() -> new BinLookupClient(clientOptions)); + this.recordsClient = Suppliers.memoize(() -> new RecordsClient(clientOptions)); + this.tokensClient = Suppliers.memoize(() -> new TokensClient(clientOptions)); + this.queryClient = Suppliers.memoize(() -> new QueryClient(clientOptions)); + this.authenticationClient = Suppliers.memoize(() -> new AuthenticationClient(clientOptions)); + this.deprecatedClient = Suppliers.memoize(() -> new DeprecatedClient(clientOptions)); + this.stringsClient = Suppliers.memoize(() -> new StringsClient(clientOptions)); + this.filesClient = Suppliers.memoize(() -> new FilesClient(clientOptions)); } - - /** - * Format the given parameter object into string. - * - * @param param Parameter - * @return String representation of the parameter - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) { - //Serialize to json string and remove the " enclosing characters - String jsonStr = JSON.serialize(param); - return jsonStr.substring(1, jsonStr.length() - 1); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for (Object o : (Collection) param) { - if (b.length() > 0) { - b.append(","); - } - b.append(o); - } - return b.toString(); - } else { - return String.valueOf(param); - } + public AuditClient audit() { + return this.auditClient.get(); } - /** - * Formats the specified query parameter to a list containing a single {@code Pair} object. - * - * Note that {@code value} must not be a collection. - * - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list containing a single {@code Pair} object. - */ - public List parameterToPair(String name, Object value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value instanceof Collection) { - return params; - } - - params.add(new Pair(name, parameterToString(value))); - return params; + public BinLookupClient binLookup() { + return this.binLookupClient.get(); } - /** - * Formats the specified collection query parameters to a list of {@code Pair} objects. - * - * Note that the values of each of the returned Pair objects are percent-encoded. - * - * @param collectionFormat The collection format of the parameter. - * @param name The name of the parameter. - * @param value The value of the parameter. - * @return A list of {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Collection value) { - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null || value.isEmpty()) { - return params; - } - - // create the params based on the collection format - if ("multi".equals(collectionFormat)) { - for (Object item : value) { - params.add(new Pair(name, escapeString(parameterToString(item)))); - } - return params; - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - // escape all delimiters except commas, which are URI reserved - // characters - if ("ssv".equals(collectionFormat)) { - delimiter = escapeString(" "); - } else if ("tsv".equals(collectionFormat)) { - delimiter = escapeString("\t"); - } else if ("pipes".equals(collectionFormat)) { - delimiter = escapeString("|"); - } - - StringBuilder sb = new StringBuilder(); - for (Object item : value) { - sb.append(delimiter); - sb.append(escapeString(parameterToString(item))); - } - - params.add(new Pair(name, sb.substring(delimiter.length()))); - - return params; + public RecordsClient records() { + return this.recordsClient.get(); } - /** - * Formats the specified free-form query parameters to a list of {@code Pair} objects. - * - * @param value The free-form query parameters. - * @return A list of {@code Pair} objects. - */ - public List freeFormParameterToPairs(Object value) { - List params = new ArrayList<>(); - - // preconditions - if (value == null || !(value instanceof Map )) { - return params; - } - - final Map valuesMap = (Map) value; - - for (Map.Entry entry : valuesMap.entrySet()) { - params.add(new Pair(entry.getKey(), parameterToString(entry.getValue()))); - } - - return params; + public TokensClient tokens() { + return this.tokensClient.get(); } - - /** - * Formats the specified collection path parameter to a string value. - * - * @param collectionFormat The collection format of the parameter. - * @param value The value of the parameter. - * @return String representation of the parameter - */ - public String collectionPathParameterToString(String collectionFormat, Collection value) { - // create the value based on the collection format - if ("multi".equals(collectionFormat)) { - // not valid for path params - return parameterToString(value); - } - - // collectionFormat is assumed to be "csv" by default - String delimiter = ","; - - if ("ssv".equals(collectionFormat)) { - delimiter = " "; - } else if ("tsv".equals(collectionFormat)) { - delimiter = "\t"; - } else if ("pipes".equals(collectionFormat)) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : value) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - return sb.substring(delimiter.length()); - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param filename The filename to be sanitized - * @return The sanitized filename - */ - public String sanitizeFilename(String filename) { - return filename.replaceAll(".*[/\\\\]", ""); - } - - /** - * Check if the given MIME is a JSON MIME. - * JSON MIME examples: - * application/json - * application/json; charset=UTF8 - * APPLICATION/JSON - * application/vnd.company+json - * "* / *" is also default to JSON - * @param mime MIME (Multipurpose Internet Mail Extensions) - * @return True if the given MIME is JSON, false otherwise. - */ - public boolean isJsonMime(String mime) { - String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; - return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) { - return null; - } - for (String accept : accepts) { - if (isJsonMime(accept)) { - return accept; - } - } - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * returns null. If it matches "any", JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) { - return null; - } - - if (contentTypes[0].equals("*/*")) { - return "application/json"; - } - - for (String contentType : contentTypes) { - if (isJsonMime(contentType)) { - return contentType; - } - } - - return contentTypes[0]; + public QueryClient query() { + return this.queryClient.get(); } - /** - * Escape the given string to be used as URL query value. - * - * @param str String to be escaped - * @return Escaped string - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } + public AuthenticationClient authentication() { + return this.authenticationClient.get(); } - /** - * Deserialize response body to Java object, according to the return type and - * the Content-Type response header. - * - * @param Type - * @param response HTTP response - * @param returnType The type of the Java object - * @return The deserialized Java object - * @throws com.skyflow.generated.rest.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") - public T deserialize(Response response, Type returnType) throws ApiException { - if (response == null || returnType == null) { - return null; - } - - if ("byte[]".equals(returnType.toString())) { - // Handle binary response (byte array). - try { - return (T) response.body().bytes(); - } catch (IOException e) { - throw new ApiException(e); - } - } else if (returnType.equals(File.class)) { - // Handle file downloading. - return (T) downloadFileFromResponse(response); - } - - String respBody; - try { - if (response.body() != null) - respBody = response.body().string(); - else - respBody = null; - } catch (IOException e) { - throw new ApiException(e); - } - - if (respBody == null || "".equals(respBody)) { - return null; - } - - String contentType = response.headers().get("Content-Type"); - if (contentType == null) { - // ensuring a default content type - contentType = "application/json"; - } - if (isJsonMime(contentType)) { - return JSON.deserialize(respBody, returnType); - } else if (returnType.equals(String.class)) { - // Expecting string, return the raw response body. - return (T) respBody; - } else { - throw new ApiException( - "Content type \"" + contentType + "\" is not supported for type: " + returnType, - response.code(), - response.headers().toMultimap(), - respBody); - } + public DeprecatedClient deprecated() { + return this.deprecatedClient.get(); } - /** - * Serialize the given Java object into request body according to the object's - * class and the request Content-Type. - * - * @param obj The Java object - * @param contentType The request Content-Type - * @return The serialized request body - * @throws com.skyflow.generated.rest.ApiException If fail to serialize the given object - */ - public RequestBody serialize(Object obj, String contentType) throws ApiException { - if (obj instanceof byte[]) { - // Binary (byte array) body parameter support. - return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); - } else if (obj instanceof File) { - // File body parameter support. - return RequestBody.create((File) obj, MediaType.parse(contentType)); - } else if ("text/plain".equals(contentType) && obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else if (isJsonMime(contentType)) { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - return RequestBody.create(content, MediaType.parse(contentType)); - } else if (obj instanceof String) { - return RequestBody.create((String) obj, MediaType.parse(contentType)); - } else { - throw new ApiException("Content type \"" + contentType + "\" is not supported"); - } + public StringsClient strings() { + return this.stringsClient.get(); } - /** - * Download file from the given response. - * - * @param response An instance of the Response object - * @throws com.skyflow.generated.rest.ApiException If fail to read file content from response and write to disk - * @return Downloaded file - */ - public File downloadFileFromResponse(Response response) throws ApiException { - try { - File file = prepareDownloadFile(response); - BufferedSink sink = Okio.buffer(Okio.sink(file)); - sink.writeAll(response.body().source()); - sink.close(); - return file; - } catch (IOException e) { - throw new ApiException(e); - } + public FilesClient files() { + return this.filesClient.get(); } - /** - * Prepare file for download - * - * @param response An instance of the Response object - * @return Prepared file for the download - * @throws java.io.IOException If fail to prepare file for download - */ - public File prepareDownloadFile(Response response) throws IOException { - String filename = null; - String contentDisposition = response.header("Content-Disposition"); - if (contentDisposition != null && !"".equals(contentDisposition)) { - // Get filename from the Content-Disposition header. - Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); - Matcher matcher = pattern.matcher(contentDisposition); - if (matcher.find()) { - filename = sanitizeFilename(matcher.group(1)); - } - } - - String prefix = null; - String suffix = null; - if (filename == null) { - prefix = "download-"; - suffix = ""; - } else { - int pos = filename.lastIndexOf("."); - if (pos == -1) { - prefix = filename + "-"; - } else { - prefix = filename.substring(0, pos) + "-"; - suffix = filename.substring(pos); - } - // Files.createTempFile requires the prefix to be at least three characters long - if (prefix.length() < 3) - prefix = "download-"; - } - - if (tempFolderPath == null) - return Files.createTempFile(prefix, suffix).toFile(); - else - return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); - } - - /** - * {@link #execute(Call, Type)} - * - * @param Type - * @param call An instance of the Call object - * @return ApiResponse<T> - * @throws com.skyflow.generated.rest.ApiException If fail to execute the call - */ - public ApiResponse execute(Call call) throws ApiException { - return execute(call, null); - } - - /** - * Execute HTTP call and deserialize the HTTP response body into the given return type. - * - * @param returnType The return type used to deserialize HTTP response body - * @param The return type corresponding to (same with) returnType - * @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 com.skyflow.generated.rest.ApiException If fail to execute the call - */ - public ApiResponse execute(Call call, Type returnType) throws ApiException { - try { - Response response = call.execute(); - T data = handleResponse(response, returnType); - return new ApiResponse(response.code(), response.headers().toMultimap(), data); - } catch (IOException e) { - throw new ApiException(e); - } - } - - /** - * {@link #executeAsync(Call, Type, ApiCallback)} - * - * @param Type - * @param call An instance of the Call object - * @param callback ApiCallback<T> - */ - public void executeAsync(Call call, ApiCallback callback) { - executeAsync(call, null, callback); - } - - /** - * Execute HTTP call asynchronously. - * - * @param Type - * @param call The callback to be executed when the API call finishes - * @param returnType Return type - * @param callback ApiCallback - * @see #execute(Call, Type) - */ - @SuppressWarnings("unchecked") - public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { - call.enqueue(new Callback() { - @Override - public void onFailure(Call call, IOException e) { - callback.onFailure(new ApiException(e), 0, null); - } - - @Override - public void onResponse(Call call, Response response) throws IOException { - T result; - try { - result = (T) handleResponse(response, returnType); - } catch (ApiException e) { - callback.onFailure(e, response.code(), response.headers().toMultimap()); - return; - } catch (Exception e) { - callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); - return; - } - callback.onSuccess(result, response.code(), response.headers().toMultimap()); - } - }); - } - - /** - * Handle the given response, return the deserialized object when the response is successful. - * - * @param Type - * @param response Response - * @param returnType Return type - * @return Type - * @throws com.skyflow.generated.rest.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 { - if (response.isSuccessful()) { - if (returnType == null || response.code() == 204) { - // returning null if the returnType is not defined, - // or the status code is 204 (No Content) - if (response.body() != null) { - try { - response.body().close(); - } catch (Exception e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - return null; - } else { - return deserialize(response, returnType); - } - } else { - String respBody = null; - if (response.body() != null) { - try { - respBody = response.body().string(); - } catch (IOException e) { - throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); - } - } - throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); - } - } - - /** - * Build HTTP call with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP call - * @throws com.skyflow.generated.rest.ApiException If fail to serialize the request body object - */ - public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); - - return httpClient.newCall(request); - } - - /** - * Build an HTTP request with the given options. - * - * @param baseUrl The base URL - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param cookieParams The cookie parameters - * @param formParams The form parameters - * @param authNames The authentications to apply - * @param callback Callback for upload/download progress - * @return The HTTP request - * @throws com.skyflow.generated.rest.ApiException If fail to serialize the request body object - */ - public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); - - // prepare HTTP request body - RequestBody reqBody; - String contentType = headerParams.get("Content-Type"); - String contentTypePure = contentType; - if (contentTypePure != null && contentTypePure.contains(";")) { - contentTypePure = contentType.substring(0, contentType.indexOf(";")); - } - if (!HttpMethod.permitsRequestBody(method)) { - reqBody = null; - } else if ("application/x-www-form-urlencoded".equals(contentTypePure)) { - reqBody = buildRequestBodyFormEncoding(formParams); - } else if ("multipart/form-data".equals(contentTypePure)) { - reqBody = buildRequestBodyMultipart(formParams); - } else if (body == null) { - if ("DELETE".equals(method)) { - // allow calling DELETE without sending a request body - reqBody = null; - } else { - // use an empty request body (for POST, PUT and PATCH) - reqBody = RequestBody.create("", contentType == null ? null : MediaType.parse(contentType)); - } - } else { - reqBody = serialize(body, contentType); - } - - 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)); - processHeaderParams(headerParams, reqBuilder); - processCookieParams(cookieParams, reqBuilder); - - // Associate callback with request (if not null) so interceptor can - // access it when creating ProgressResponseBody - reqBuilder.tag(callback); - - Request request = null; - - if (callback != null && reqBody != null) { - ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); - request = reqBuilder.method(method, progressRequestBody).build(); - } else { - request = reqBuilder.method(method, reqBody).build(); - } - - return request; - } - - /** - * Build full URL by concatenating base path, the given sub path and query parameters. - * - * @param baseUrl The base URL - * @param path The sub path - * @param queryParams The query parameters - * @param collectionQueryParams The collection query parameters - * @return The full URL - */ - public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { - final StringBuilder url = new StringBuilder(); - if (baseUrl != null) { - url.append(baseUrl).append(path); - } else { - String baseURL; - if (serverIndex != null) { - if (serverIndex < 0 || serverIndex >= servers.size()) { - throw new ArrayIndexOutOfBoundsException(String.format( - "Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size() - )); - } - baseURL = servers.get(serverIndex).URL(serverVariables); - } else { - baseURL = basePath; - } - url.append(baseURL).append(path); - } - - if (queryParams != null && !queryParams.isEmpty()) { - // support (constant) query string in `path`, e.g. "/posts?draft=1" - String prefix = path.contains("?") ? "&" : "?"; - for (Pair param : queryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - url.append(escapeString(param.getName())).append("=").append(escapeString(value)); - } - } - } - - if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { - String prefix = url.toString().contains("?") ? "&" : "?"; - for (Pair param : collectionQueryParams) { - if (param.getValue() != null) { - if (prefix != null) { - url.append(prefix); - prefix = null; - } else { - url.append("&"); - } - String value = parameterToString(param.getValue()); - // collection query parameter value already escaped as part of parameterToPairs - url.append(escapeString(param.getName())).append("=").append(value); - } - } - } - - return url.toString(); - } - - /** - * Set header parameters to the request builder, including default headers. - * - * @param headerParams Header parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { - for (Entry param : headerParams.entrySet()) { - reqBuilder.header(param.getKey(), parameterToString(param.getValue())); - } - for (Entry header : defaultHeaderMap.entrySet()) { - if (!headerParams.containsKey(header.getKey())) { - reqBuilder.header(header.getKey(), parameterToString(header.getValue())); - } - } - } - - /** - * Set cookie parameters to the request builder, including default cookies. - * - * @param cookieParams Cookie parameters in the form of Map - * @param reqBuilder Request.Builder - */ - public void processCookieParams(Map cookieParams, Request.Builder reqBuilder) { - for (Entry param : cookieParams.entrySet()) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - for (Entry param : defaultCookieMap.entrySet()) { - if (!cookieParams.containsKey(param.getKey())) { - reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); - } - } - } - - /** - * 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 com.skyflow.generated.rest.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. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyFormEncoding(Map formParams) { - okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); - for (Entry param : formParams.entrySet()) { - formBuilder.add(param.getKey(), parameterToString(param.getValue())); - } - return formBuilder.build(); - } - - /** - * Build a multipart (file uploading) request body with the given form parameters, - * which could contain text fields and file fields. - * - * @param formParams Form parameters in the form of Map - * @return RequestBody - */ - public RequestBody buildRequestBodyMultipart(Map formParams) { - MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); - for (Entry param : formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - addPartToMultiPartBuilder(mpBuilder, param.getKey(), file); - } else if (param.getValue() instanceof List) { - List list = (List) param.getValue(); - for (Object item: list) { - if (item instanceof File) { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item); - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - } else { - addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); - } - } - return mpBuilder.build(); - } - - /** - * Guess Content-Type header from the given file (defaults to "application/octet-stream"). - * - * @param file The given file - * @return The guessed Content-Type - */ - public String guessContentTypeFromFile(File file) { - String contentType = URLConnection.guessContentTypeFromName(file.getName()); - if (contentType == null) { - return "application/octet-stream"; - } else { - return contentType; - } - } - - /** - * Add a Content-Disposition Header for the given key and file to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param file The file to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, File file) { - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\""); - MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); - mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); - } - - /** - * Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder. - * - * @param mpBuilder MultipartBody.Builder - * @param key The key of the Header element - * @param obj The complex object to add to the Header - */ - private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) { - RequestBody requestBody; - if (obj instanceof String) { - requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain")); - } else { - String content; - if (obj != null) { - content = JSON.serialize(obj); - } else { - content = null; - } - requestBody = RequestBody.create(content, MediaType.parse("application/json")); - } - - Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""); - mpBuilder.addPart(partHeaders, requestBody); - } - - /** - * Get network interceptor to add it to the httpClient to track download progress for - * async requests. - */ - private Interceptor getProgressInterceptor() { - return new Interceptor() { - @Override - public Response intercept(Interceptor.Chain chain) throws IOException { - final Request request = chain.request(); - final Response originalResponse = chain.proceed(request); - if (request.tag() instanceof ApiCallback) { - final ApiCallback callback = (ApiCallback) request.tag(); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), callback)) - .build(); - } - return originalResponse; - } - }; - } - - /** - * Apply SSL related settings to httpClient according to the current values of - * verifyingSsl and sslCaCert. - */ - private void applySslSettings() { - try { - TrustManager[] trustManagers; - HostnameVerifier hostnameVerifier; - if (!verifyingSsl) { - trustManagers = new TrustManager[]{ - new X509TrustManager() { - @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { - } - - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[]{}; - } - } - }; - hostnameVerifier = new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - } else { - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - - if (sslCaCert == null) { - trustManagerFactory.init((KeyStore) null); - } else { - char[] password = null; // Any password will work. - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - Collection certificates = certificateFactory.generateCertificates(sslCaCert); - if (certificates.isEmpty()) { - throw new IllegalArgumentException("expected non-empty set of trusted certificates"); - } - KeyStore caKeyStore = newEmptyKeyStore(password); - int index = 0; - for (Certificate certificate : certificates) { - String certificateAlias = "ca" + (index++); - caKeyStore.setCertificateEntry(certificateAlias, certificate); - } - trustManagerFactory.init(caKeyStore); - } - trustManagers = trustManagerFactory.getTrustManagers(); - hostnameVerifier = OkHostnameVerifier.INSTANCE; - } - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, trustManagers, new SecureRandom()); - httpClient = httpClient.newBuilder() - .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) - .hostnameVerifier(hostnameVerifier) - .build(); - } catch (GeneralSecurityException e) { - throw new RuntimeException(e); - } - } - - private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { - try { - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - return keyStore; - } catch (IOException e) { - throw new AssertionError(e); - } - } - - /** - * Convert the HTTP request body to a string. - * - * @param requestBody The HTTP request object - * @return The string representation of the HTTP request body - * @throws com.skyflow.generated.rest.ApiException If fail to serialize the request body object into a string - */ - private String requestBodyToString(RequestBody requestBody) throws ApiException { - if (requestBody != null) { - try { - final Buffer buffer = new Buffer(); - requestBody.writeTo(buffer); - return buffer.readUtf8(); - } catch (final IOException e) { - throw new ApiException(e); - } - } - - // empty http request body - return ""; + public static ApiClientBuilder builder() { + return new ApiClientBuilder(); } } diff --git a/src/main/java/com/skyflow/generated/rest/ApiClientBuilder.java b/src/main/java/com/skyflow/generated/rest/ApiClientBuilder.java new file mode 100644 index 00000000..b361812a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/ApiClientBuilder.java @@ -0,0 +1,67 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.Environment; +import okhttp3.OkHttpClient; + +public final class ApiClientBuilder { + private ClientOptions.Builder clientOptionsBuilder = ClientOptions.builder(); + + private String token = null; + + private Environment environment = Environment.PRODUCTION; + + /** + * Sets token + */ + public ApiClientBuilder token(String token) { + this.token = token; + return this; + } + + public ApiClientBuilder environment(Environment environment) { + this.environment = environment; + return this; + } + + public ApiClientBuilder url(String url) { + this.environment = Environment.custom(url); + return this; + } + + /** + * Sets the timeout (in seconds) for the client. Defaults to 60 seconds. + */ + public ApiClientBuilder timeout(int timeout) { + this.clientOptionsBuilder.timeout(timeout); + return this; + } + + /** + * Sets the maximum number of retries for the client. Defaults to 2 retries. + */ + public ApiClientBuilder maxRetries(int maxRetries) { + this.clientOptionsBuilder.maxRetries(maxRetries); + return this; + } + + /** + * Sets the underlying OkHttp client + */ + public ApiClientBuilder httpClient(OkHttpClient httpClient) { + this.clientOptionsBuilder.httpClient(httpClient); + return this; + } + + public ApiClient build() { + if (token == null) { + throw new RuntimeException("Please provide token"); + } + this.clientOptionsBuilder.addHeader("Authorization", "Bearer " + this.token); + clientOptionsBuilder.environment(this.environment); + return new ApiClient(clientOptionsBuilder.build()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/ApiException.java b/src/main/java/com/skyflow/generated/rest/ApiException.java deleted file mode 100644 index d10c995e..00000000 --- a/src/main/java/com/skyflow/generated/rest/ApiException.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest; - -import java.util.Map; -import java.util.List; - - -/** - *

ApiException class.

- */ -@SuppressWarnings("serial") -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.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/src/main/java/com/skyflow/generated/rest/ApiResponse.java b/src/main/java/com/skyflow/generated/rest/ApiResponse.java deleted file mode 100644 index d3cdb698..00000000 --- a/src/main/java/com/skyflow/generated/rest/ApiResponse.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest; - -import java.util.List; -import java.util.Map; - -/** - * API response returned by API call. - */ -public class ApiResponse { - final private int statusCode; - final private Map> headers; - final private T data; - - /** - *

Constructor for ApiResponse.

- * - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - */ - public ApiResponse(int statusCode, Map> headers) { - this(statusCode, headers, null); - } - - /** - *

Constructor for ApiResponse.

- * - * @param statusCode The status code of HTTP response - * @param headers The headers of HTTP response - * @param data The object deserialized from response bod - */ - public ApiResponse(int statusCode, Map> headers, T data) { - this.statusCode = statusCode; - this.headers = headers; - this.data = data; - } - - /** - *

Get the status code.

- * - * @return the status code - */ - public int getStatusCode() { - return statusCode; - } - - /** - *

Get the headers.

- * - * @return a {@link java.util.Map} of headers - */ - public Map> getHeaders() { - return headers; - } - - /** - *

Get the data.

- * - * @return the data - */ - public T getData() { - return data; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java b/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java new file mode 100644 index 00000000..d36c8141 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java @@ -0,0 +1,92 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.Suppliers; +import com.skyflow.generated.rest.resources.audit.AsyncAuditClient; +import com.skyflow.generated.rest.resources.authentication.AsyncAuthenticationClient; +import com.skyflow.generated.rest.resources.binlookup.AsyncBinLookupClient; +import com.skyflow.generated.rest.resources.deprecated.AsyncDeprecatedClient; +import com.skyflow.generated.rest.resources.files.AsyncFilesClient; +import com.skyflow.generated.rest.resources.query.AsyncQueryClient; +import com.skyflow.generated.rest.resources.records.AsyncRecordsClient; +import com.skyflow.generated.rest.resources.strings.AsyncStringsClient; +import com.skyflow.generated.rest.resources.tokens.AsyncTokensClient; +import java.util.function.Supplier; + +public class AsyncApiClient { + protected final ClientOptions clientOptions; + + protected final Supplier auditClient; + + protected final Supplier binLookupClient; + + protected final Supplier recordsClient; + + protected final Supplier tokensClient; + + protected final Supplier queryClient; + + protected final Supplier authenticationClient; + + protected final Supplier deprecatedClient; + + protected final Supplier stringsClient; + + protected final Supplier filesClient; + + public AsyncApiClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.auditClient = Suppliers.memoize(() -> new AsyncAuditClient(clientOptions)); + this.binLookupClient = Suppliers.memoize(() -> new AsyncBinLookupClient(clientOptions)); + this.recordsClient = Suppliers.memoize(() -> new AsyncRecordsClient(clientOptions)); + this.tokensClient = Suppliers.memoize(() -> new AsyncTokensClient(clientOptions)); + this.queryClient = Suppliers.memoize(() -> new AsyncQueryClient(clientOptions)); + this.authenticationClient = Suppliers.memoize(() -> new AsyncAuthenticationClient(clientOptions)); + this.deprecatedClient = Suppliers.memoize(() -> new AsyncDeprecatedClient(clientOptions)); + this.stringsClient = Suppliers.memoize(() -> new AsyncStringsClient(clientOptions)); + this.filesClient = Suppliers.memoize(() -> new AsyncFilesClient(clientOptions)); + } + + public AsyncAuditClient audit() { + return this.auditClient.get(); + } + + public AsyncBinLookupClient binLookup() { + return this.binLookupClient.get(); + } + + public AsyncRecordsClient records() { + return this.recordsClient.get(); + } + + public AsyncTokensClient tokens() { + return this.tokensClient.get(); + } + + public AsyncQueryClient query() { + return this.queryClient.get(); + } + + public AsyncAuthenticationClient authentication() { + return this.authenticationClient.get(); + } + + public AsyncDeprecatedClient deprecated() { + return this.deprecatedClient.get(); + } + + public AsyncStringsClient strings() { + return this.stringsClient.get(); + } + + public AsyncFilesClient files() { + return this.filesClient.get(); + } + + public static AsyncApiClientBuilder builder() { + return new AsyncApiClientBuilder(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/AsyncApiClientBuilder.java b/src/main/java/com/skyflow/generated/rest/AsyncApiClientBuilder.java new file mode 100644 index 00000000..8e4b8474 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/AsyncApiClientBuilder.java @@ -0,0 +1,67 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.Environment; +import okhttp3.OkHttpClient; + +public final class AsyncApiClientBuilder { + private ClientOptions.Builder clientOptionsBuilder = ClientOptions.builder(); + + private String token = null; + + private Environment environment = Environment.PRODUCTION; + + /** + * Sets token + */ + public AsyncApiClientBuilder token(String token) { + this.token = token; + return this; + } + + public AsyncApiClientBuilder environment(Environment environment) { + this.environment = environment; + return this; + } + + public AsyncApiClientBuilder url(String url) { + this.environment = Environment.custom(url); + return this; + } + + /** + * Sets the timeout (in seconds) for the client. Defaults to 60 seconds. + */ + public AsyncApiClientBuilder timeout(int timeout) { + this.clientOptionsBuilder.timeout(timeout); + return this; + } + + /** + * Sets the maximum number of retries for the client. Defaults to 2 retries. + */ + public AsyncApiClientBuilder maxRetries(int maxRetries) { + this.clientOptionsBuilder.maxRetries(maxRetries); + return this; + } + + /** + * Sets the underlying OkHttp client + */ + public AsyncApiClientBuilder httpClient(OkHttpClient httpClient) { + this.clientOptionsBuilder.httpClient(httpClient); + return this; + } + + public AsyncApiClient build() { + if (token == null) { + throw new RuntimeException("Please provide token"); + } + this.clientOptionsBuilder.addHeader("Authorization", "Bearer " + this.token); + clientOptionsBuilder.environment(this.environment); + return new AsyncApiClient(clientOptionsBuilder.build()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/Configuration.java b/src/main/java/com/skyflow/generated/rest/Configuration.java deleted file mode 100644 index 6b12e8bb..00000000 --- a/src/main/java/com/skyflow/generated/rest/Configuration.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class Configuration { - public static final String VERSION = "v1"; - - private static ApiClient defaultApiClient = new ApiClient(); - - /** - * 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() { - return defaultApiClient; - } - - /** - * 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 = apiClient; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java b/src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java deleted file mode 100644 index 2b69f358..00000000 --- a/src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest; - -import okhttp3.*; -import okio.Buffer; -import okio.BufferedSink; -import okio.GzipSink; -import okio.Okio; - -import java.io.IOException; - -/** - * Encodes request bodies using gzip. - * - * Taken from https://github.com/square/okhttp/issues/350 - */ -class GzipRequestInterceptor implements Interceptor { - @Override - public Response intercept(Chain chain) throws IOException { - Request originalRequest = chain.request(); - if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) { - return chain.proceed(originalRequest); - } - - Request compressedRequest = originalRequest.newBuilder() - .header("Content-Encoding", "gzip") - .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))) - .build(); - return chain.proceed(compressedRequest); - } - - private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { - final Buffer buffer = new Buffer(); - requestBody.writeTo(buffer); - return new RequestBody() { - @Override - public MediaType contentType() { - return requestBody.contentType(); - } - - @Override - public long contentLength() { - return buffer.size(); - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - sink.write(buffer.snapshot()); - } - }; - } - - private RequestBody gzip(final RequestBody body) { - return new RequestBody() { - @Override - public MediaType contentType() { - return body.contentType(); - } - - @Override - public long contentLength() { - return -1; // We don't know the compressed length in advance! - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); - body.writeTo(gzipSink); - gzipSink.close(); - } - }; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/JSON.java b/src/main/java/com/skyflow/generated/rest/JSON.java deleted file mode 100644 index 8e6e8375..00000000 --- a/src/main/java/com/skyflow/generated/rest/JSON.java +++ /dev/null @@ -1,440 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.internal.bind.util.ISO8601Utils; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonElement; -import io.gsonfire.GsonFireBuilder; -import io.gsonfire.TypeSelector; - -import okio.ByteString; - -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Type; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.ParsePosition; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.Locale; -import java.util.Map; -import java.util.HashMap; - -/* - * A JSON utility class - * - * NOTE: in the future, this class may be converted to static, which may break - * backward-compatibility - */ -public class JSON { - private static Gson gson; - private static boolean isLenientOnJson = false; - private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); - private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); - private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); - private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); - private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - - @SuppressWarnings("unchecked") - public static GsonBuilder createGson() { - GsonFireBuilder fireBuilder = new GsonFireBuilder() - ; - GsonBuilder builder = fireBuilder.createGsonBuilder(); - return builder; - } - - private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { - JsonElement element = readElement.getAsJsonObject().get(discriminatorField); - if (null == element) { - throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); - } - return element.getAsString(); - } - - /** - * Returns the Java class that implements the OpenAPI schema for the specified discriminator value. - * - * @param classByDiscriminatorValue The map of discriminator values to Java classes. - * @param discriminatorValue The value of the OpenAPI discriminator in the input data. - * @return The Java class that implements the OpenAPI schema - */ - private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { - Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue); - if (null == clazz) { - throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); - } - return clazz; - } - - static { - GsonBuilder gsonBuilder = createGson(); - gsonBuilder.registerTypeAdapter(Date.class, dateTypeAdapter); - gsonBuilder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); - gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); - gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); - gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.AuditEventContext.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.AuditEventData.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.AuditEventHTTPInfo.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.GooglerpcStatus.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.ProtobufAny.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.QueryServiceExecuteQueryBody.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.RecordServiceBatchOperationBody.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.RecordServiceBulkDeleteRecordBody.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.RecordServiceInsertRecordBody.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.RecordServiceUpdateRecordBody.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1AuditAfterOptions.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1AuditEventResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1AuditResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1AuditResponseEvent.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1AuditResponseEventRequest.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1BINListRequest.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1BINListResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1BatchOperationResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1BatchRecord.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1BulkDeleteRecordResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1BulkGetRecordResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1Card.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1DeleteFileResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1DeleteRecordResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1DetokenizePayload.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1DetokenizeRecordRequest.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1DetokenizeRecordResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1DetokenizeResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1FieldRecords.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1GetFileScanStatusResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1GetQueryResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1InsertRecordResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1RecordMetaProperties.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1TokenizePayload.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1TokenizeRecordRequest.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1TokenizeRecordResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1TokenizeResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1UpdateRecordResponse.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1VaultFieldMapping.CustomTypeAdapterFactory()); - gsonBuilder.registerTypeAdapterFactory(new com.skyflow.generated.rest.models.V1VaultSchemaConfig.CustomTypeAdapterFactory()); - gson = gsonBuilder.create(); - } - - /** - * Get Gson. - * - * @return Gson - */ - public static Gson getGson() { - return gson; - } - - /** - * Set Gson. - * - * @param gson Gson - */ - public static void setGson(Gson gson) { - JSON.gson = gson; - } - - public static void setLenientOnJson(boolean lenientOnJson) { - isLenientOnJson = lenientOnJson; - } - - /** - * Serialize the given Java object into JSON string. - * - * @param obj Object - * @return String representation of the JSON - */ - public static String serialize(Object obj) { - return gson.toJson(obj); - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param Type - * @param body The JSON string - * @param returnType The type to deserialize into - * @return The deserialized Java object - */ - @SuppressWarnings("unchecked") - public static T deserialize(String body, Type returnType) { - try { - if (isLenientOnJson) { - JsonReader jsonReader = new JsonReader(new StringReader(body)); - // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) - jsonReader.setLenient(true); - return gson.fromJson(jsonReader, returnType); - } else { - return gson.fromJson(body, returnType); - } - } catch (JsonParseException e) { - // Fallback processing when failed to parse JSON form response body: - // return the response body string directly for the String return type; - if (returnType.equals(String.class)) { - return (T) body; - } else { - throw (e); - } - } - } - - /** - * Gson TypeAdapter for Byte Array type - */ - public static class ByteArrayAdapter extends TypeAdapter { - - @Override - public void write(JsonWriter out, byte[] value) throws IOException { - if (value == null) { - out.nullValue(); - } else { - out.value(ByteString.of(value).base64()); - } - } - - @Override - public byte[] read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String bytesAsBase64 = in.nextString(); - ByteString byteString = ByteString.decodeBase64(bytesAsBase64); - return byteString.toByteArray(); - } - } - } - - /** - * Gson TypeAdapter for JSR310 OffsetDateTime type - */ - public static class OffsetDateTimeTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public OffsetDateTimeTypeAdapter() { - this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); - } - - public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, OffsetDateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public OffsetDateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - if (date.endsWith("+0000")) { - date = date.substring(0, date.length()-5) + "Z"; - } - return OffsetDateTime.parse(date, formatter); - } - } - } - - /** - * Gson TypeAdapter for JSR310 LocalDate type - */ - public static class LocalDateTypeAdapter extends TypeAdapter { - - private DateTimeFormatter formatter; - - public LocalDateTypeAdapter() { - this(DateTimeFormatter.ISO_LOCAL_DATE); - } - - public LocalDateTypeAdapter(DateTimeFormatter formatter) { - this.formatter = formatter; - } - - public void setFormat(DateTimeFormatter dateFormat) { - this.formatter = dateFormat; - } - - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.format(date)); - } - } - - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return LocalDate.parse(date, formatter); - } - } - } - - public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { - offsetDateTimeTypeAdapter.setFormat(dateFormat); - } - - public static void setLocalDateFormat(DateTimeFormatter dateFormat) { - localDateTypeAdapter.setFormat(dateFormat); - } - - /** - * Gson TypeAdapter for java.sql.Date type - * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used - * (more efficient than SimpleDateFormat). - */ - public static class SqlDateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public SqlDateTypeAdapter() {} - - public SqlDateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, java.sql.Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = date.toString(); - } - out.value(value); - } - } - - @Override - public java.sql.Date read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return new java.sql.Date(dateFormat.parse(date).getTime()); - } - return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } - } - - /** - * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, ISO8601Utils will be used. - */ - public static class DateTypeAdapter extends TypeAdapter { - - private DateFormat dateFormat; - - public DateTypeAdapter() {} - - public DateTypeAdapter(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - public void setFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - } - - @Override - public void write(JsonWriter out, Date date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - String value; - if (dateFormat != null) { - value = dateFormat.format(date); - } else { - value = ISO8601Utils.format(date, true); - } - out.value(value); - } - } - - @Override - public Date read(JsonReader in) throws IOException { - try { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - try { - if (dateFormat != null) { - return dateFormat.parse(date); - } - return ISO8601Utils.parse(date, new ParsePosition(0)); - } catch (ParseException e) { - throw new JsonParseException(e); - } - } - } catch (IllegalArgumentException e) { - throw new JsonParseException(e); - } - } - } - - public static void setDateFormat(DateFormat dateFormat) { - dateTypeAdapter.setFormat(dateFormat); - } - - public static void setSqlDateFormat(DateFormat dateFormat) { - sqlDateTypeAdapter.setFormat(dateFormat); - } -} diff --git a/src/main/java/com/skyflow/generated/rest/Pair.java b/src/main/java/com/skyflow/generated/rest/Pair.java deleted file mode 100644 index 0f182d02..00000000 --- a/src/main/java/com/skyflow/generated/rest/Pair.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class Pair { - private String name = ""; - private String value = ""; - - public Pair (String name, String value) { - setName(name); - setValue(value); - } - - private void setName(String name) { - if (!isValidString(name)) { - return; - } - - this.name = name; - } - - private void setValue(String value) { - if (!isValidString(value)) { - return; - } - - this.value = value; - } - - public String getName() { - return this.name; - } - - public String getValue() { - return this.value; - } - - private boolean isValidString(String arg) { - if (arg == null) { - return false; - } - - return true; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java b/src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java deleted file mode 100644 index 38d16e94..00000000 --- a/src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest; - -import okhttp3.MediaType; -import okhttp3.RequestBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSink; -import okio.ForwardingSink; -import okio.Okio; -import okio.Sink; - -public class ProgressRequestBody extends RequestBody { - - private final RequestBody requestBody; - - private final ApiCallback callback; - - public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) { - this.requestBody = requestBody; - this.callback = callback; - } - - @Override - public MediaType contentType() { - return requestBody.contentType(); - } - - @Override - public long contentLength() throws IOException { - return requestBody.contentLength(); - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - BufferedSink bufferedSink = Okio.buffer(sink(sink)); - requestBody.writeTo(bufferedSink); - bufferedSink.flush(); - } - - private Sink sink(Sink sink) { - return new ForwardingSink(sink) { - - long bytesWritten = 0L; - long contentLength = 0L; - - @Override - public void write(Buffer source, long byteCount) throws IOException { - super.write(source, byteCount); - if (contentLength == 0) { - contentLength = contentLength(); - } - - bytesWritten += byteCount; - callback.onUploadProgress(bytesWritten, contentLength, bytesWritten == contentLength); - } - }; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java b/src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java deleted file mode 100644 index 6bd61b5a..00000000 --- a/src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest; - -import okhttp3.MediaType; -import okhttp3.ResponseBody; - -import java.io.IOException; - -import okio.Buffer; -import okio.BufferedSource; -import okio.ForwardingSource; -import okio.Okio; -import okio.Source; - -public class ProgressResponseBody extends ResponseBody { - - private final ResponseBody responseBody; - private final ApiCallback callback; - private BufferedSource bufferedSource; - - public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) { - this.responseBody = responseBody; - this.callback = callback; - } - - @Override - public MediaType contentType() { - return responseBody.contentType(); - } - - @Override - public long contentLength() { - return responseBody.contentLength(); - } - - @Override - public BufferedSource source() { - if (bufferedSource == null) { - bufferedSource = Okio.buffer(source(responseBody.source())); - } - return bufferedSource; - } - - private Source source(Source source) { - return new ForwardingSource(source) { - long totalBytesRead = 0L; - - @Override - public long read(Buffer sink, long byteCount) throws IOException { - long bytesRead = super.read(sink, byteCount); - // read() returns the number of bytes read, or -1 if this source is exhausted. - totalBytesRead += bytesRead != -1 ? bytesRead : 0; - callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1); - return bytesRead; - } - }; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/ServerConfiguration.java b/src/main/java/com/skyflow/generated/rest/ServerConfiguration.java deleted file mode 100644 index f91ef52d..00000000 --- a/src/main/java/com/skyflow/generated/rest/ServerConfiguration.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest; - -import java.util.Map; - -/** - * Representing a Server configuration. - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class ServerConfiguration { - public String URL; - public String description; - public Map variables; - - /** - * @param URL A URL to the target host. - * @param description A description of the host designated by the URL. - * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. - */ - public ServerConfiguration(String URL, String description, Map variables) { - this.URL = URL; - this.description = description; - this.variables = variables; - } - - /** - * Format URL template using given variables. - * - * @param variables A map between a variable name and its value. - * @return Formatted URL. - */ - public String URL(Map variables) { - String url = this.URL; - - // go through variables and replace placeholders - for (Map.Entry variable: this.variables.entrySet()) { - String name = variable.getKey(); - ServerVariable serverVariable = variable.getValue(); - String value = serverVariable.defaultValue; - - if (variables != null && variables.containsKey(name)) { - value = variables.get(name); - if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { - throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + "."); - } - } - url = url.replace("{" + name + "}", value); - } - return url; - } - - /** - * Format URL template using default server variables. - * - * @return Formatted URL. - */ - public String URL() { - return URL(null); - } -} diff --git a/src/main/java/com/skyflow/generated/rest/ServerVariable.java b/src/main/java/com/skyflow/generated/rest/ServerVariable.java deleted file mode 100644 index 53b17180..00000000 --- a/src/main/java/com/skyflow/generated/rest/ServerVariable.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest; - -import java.util.HashSet; - -/** - * Representing a Server Variable for server URL template substitution. - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class ServerVariable { - public String description; - public String defaultValue; - public HashSet enumValues = null; - - /** - * @param description A description for the server variable. - * @param defaultValue The default value to use for substitution. - * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. - */ - public ServerVariable(String description, String defaultValue, HashSet enumValues) { - this.description = description; - this.defaultValue = defaultValue; - this.enumValues = enumValues; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/StringUtil.java b/src/main/java/com/skyflow/generated/rest/StringUtil.java deleted file mode 100644 index 433e15d7..00000000 --- a/src/main/java/com/skyflow/generated/rest/StringUtil.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest; - -import java.util.Collection; -import java.util.Iterator; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class StringUtil { - /** - * Check if the given array contains the given value (with case-insensitive comparison). - * - * @param array The array - * @param value The value to search - * @return true if the array contains the value - */ - public static boolean containsIgnoreCase(String[] array, String value) { - for (String str : array) { - if (value == null && str == null) { - return true; - } - if (value != null && value.equalsIgnoreCase(str)) { - return true; - } - } - return false; - } - - /** - * Join an array of strings with the given separator. - *

- * Note: This might be replaced by utility method from commons-lang or guava someday - * if one of those libraries is added as dependency. - *

- * - * @param array The array of strings - * @param separator The separator - * @return the resulting string - */ - public static String join(String[] array, String separator) { - int len = array.length; - if (len == 0) { - return ""; - } - - StringBuilder out = new StringBuilder(); - out.append(array[0]); - for (int i = 1; i < len; i++) { - out.append(separator).append(array[i]); - } - return out.toString(); - } - - /** - * Join a list of strings with the given separator. - * - * @param list The list of strings - * @param separator The separator - * @return the resulting string - */ - public static String join(Collection list, String separator) { - Iterator iterator = list.iterator(); - StringBuilder out = new StringBuilder(); - if (iterator.hasNext()) { - out.append(iterator.next()); - } - while (iterator.hasNext()) { - out.append(separator).append(iterator.next()); - } - return out.toString(); - } -} diff --git a/src/main/java/com/skyflow/generated/rest/api/AuditApi.java b/src/main/java/com/skyflow/generated/rest/api/AuditApi.java deleted file mode 100644 index 6b441971..00000000 --- a/src/main/java/com/skyflow/generated/rest/api/AuditApi.java +++ /dev/null @@ -1,466 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.api; - -import com.skyflow.generated.rest.ApiCallback; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.ApiException; -import com.skyflow.generated.rest.ApiResponse; -import com.skyflow.generated.rest.Configuration; -import com.skyflow.generated.rest.Pair; -import com.skyflow.generated.rest.ProgressRequestBody; -import com.skyflow.generated.rest.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import com.skyflow.generated.rest.models.GooglerpcStatus; -import com.skyflow.generated.rest.models.V1AuditResponse; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class AuditApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public AuditApi() { - this(Configuration.getDefaultApiClient()); - } - - public AuditApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for auditServiceListAuditEvents - * @param filterOpsAccountID Resources with the specified account ID. (required) - * @param filterOpsContextChangeID ID for the audit event. (optional) - * @param filterOpsContextRequestID ID for the request that caused the event. (optional) - * @param filterOpsContextTraceID ID for the request set by the service that received the request. (optional) - * @param filterOpsContextSessionID ID for the session in which the request was sent. (optional) - * @param filterOpsContextActor Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. (optional) - * @param filterOpsContextActorType Type of member who sent the request. (optional, default to NONE) - * @param filterOpsContextAccessType Type of access for the request. (optional, default to ACCESS_NONE) - * @param filterOpsContextIpAddress IP Address of the client that made the request. (optional) - * @param filterOpsContextOrigin HTTP Origin request header (including scheme, hostname, and port) of the request. (optional) - * @param filterOpsContextAuthMode Authentication mode the `actor` used. (optional, default to AUTH_NONE) - * @param filterOpsContextJwtID ID of the JWT token. (optional) - * @param filterOpsContextBearerTokenContextID Embedded User Context. (optional) - * @param filterOpsParentAccountID Resources with the specified parent account ID. (optional) - * @param filterOpsWorkspaceID Resources with the specified workspace ID. (optional) - * @param filterOpsVaultID Resources with the specified vault ID. (optional) - * @param filterOpsResourceIDs Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\<resourceType\\>/\\<resourceID\\>\". For example, \"VAULT/12345, USER/67890\". (optional) - * @param filterOpsActionType Events with the specified action type. (optional, default to NONE) - * @param filterOpsResourceType Resources with the specified type. (optional, default to NONE_API) - * @param filterOpsTags Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\". (optional) - * @param filterOpsResponseCode HTTP response code of the request. (optional) - * @param filterOpsStartTime Start timestamp for the query, in SQL format. (optional) - * @param filterOpsEndTime End timestamp for the query, in SQL format. (optional) - * @param filterOpsApiName Name of the API called in the request. (optional) - * @param filterOpsResponseMessage Response message of the request. (optional) - * @param filterOpsHttpMethod HTTP method of the request. (optional) - * @param filterOpsHttpURI HTTP URI of the request. (optional) - * @param sortOpsSortBy Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\"). (optional) - * @param sortOpsOrderBy Ascending or descending ordering of results. (optional, default to ASCENDING) - * @param afterOpsTimestamp Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) - * @param afterOpsChangeID Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) - * @param limit Number of results to return. (optional, default to 25) - * @param offset Record position at which to start returning results. (optional, default to 0) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details -
- - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call auditServiceListAuditEventsCall(String filterOpsAccountID, String filterOpsContextChangeID, String filterOpsContextRequestID, String filterOpsContextTraceID, String filterOpsContextSessionID, String filterOpsContextActor, String filterOpsContextActorType, String filterOpsContextAccessType, String filterOpsContextIpAddress, String filterOpsContextOrigin, String filterOpsContextAuthMode, String filterOpsContextJwtID, String filterOpsContextBearerTokenContextID, String filterOpsParentAccountID, String filterOpsWorkspaceID, String filterOpsVaultID, String filterOpsResourceIDs, String filterOpsActionType, String filterOpsResourceType, String filterOpsTags, Integer filterOpsResponseCode, String filterOpsStartTime, String filterOpsEndTime, String filterOpsApiName, String filterOpsResponseMessage, String filterOpsHttpMethod, String filterOpsHttpURI, String sortOpsSortBy, String sortOpsOrderBy, String afterOpsTimestamp, String afterOpsChangeID, Long limit, Long offset, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/v1/audit/events"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - if (filterOpsContextChangeID != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.changeID", filterOpsContextChangeID)); - } - - if (filterOpsContextRequestID != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.requestID", filterOpsContextRequestID)); - } - - if (filterOpsContextTraceID != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.traceID", filterOpsContextTraceID)); - } - - if (filterOpsContextSessionID != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.sessionID", filterOpsContextSessionID)); - } - - if (filterOpsContextActor != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.actor", filterOpsContextActor)); - } - - if (filterOpsContextActorType != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.actorType", filterOpsContextActorType)); - } - - if (filterOpsContextAccessType != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.accessType", filterOpsContextAccessType)); - } - - if (filterOpsContextIpAddress != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.ipAddress", filterOpsContextIpAddress)); - } - - if (filterOpsContextOrigin != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.origin", filterOpsContextOrigin)); - } - - if (filterOpsContextAuthMode != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.authMode", filterOpsContextAuthMode)); - } - - if (filterOpsContextJwtID != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.jwtID", filterOpsContextJwtID)); - } - - if (filterOpsContextBearerTokenContextID != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.context.bearerTokenContextID", filterOpsContextBearerTokenContextID)); - } - - if (filterOpsParentAccountID != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.parentAccountID", filterOpsParentAccountID)); - } - - if (filterOpsAccountID != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.accountID", filterOpsAccountID)); - } - - if (filterOpsWorkspaceID != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.workspaceID", filterOpsWorkspaceID)); - } - - if (filterOpsVaultID != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.vaultID", filterOpsVaultID)); - } - - if (filterOpsResourceIDs != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.resourceIDs", filterOpsResourceIDs)); - } - - if (filterOpsActionType != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.actionType", filterOpsActionType)); - } - - if (filterOpsResourceType != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.resourceType", filterOpsResourceType)); - } - - if (filterOpsTags != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.tags", filterOpsTags)); - } - - if (filterOpsResponseCode != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.responseCode", filterOpsResponseCode)); - } - - if (filterOpsStartTime != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.startTime", filterOpsStartTime)); - } - - if (filterOpsEndTime != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.endTime", filterOpsEndTime)); - } - - if (filterOpsApiName != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.apiName", filterOpsApiName)); - } - - if (filterOpsResponseMessage != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.responseMessage", filterOpsResponseMessage)); - } - - if (filterOpsHttpMethod != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.httpMethod", filterOpsHttpMethod)); - } - - if (filterOpsHttpURI != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("filterOps.httpURI", filterOpsHttpURI)); - } - - if (sortOpsSortBy != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("sortOps.sortBy", sortOpsSortBy)); - } - - if (sortOpsOrderBy != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("sortOps.orderBy", sortOpsOrderBy)); - } - - if (afterOpsTimestamp != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("afterOps.timestamp", afterOpsTimestamp)); - } - - if (afterOpsChangeID != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("afterOps.changeID", afterOpsChangeID)); - } - - if (limit != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("limit", limit)); - } - - if (offset != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("offset", offset)); - } - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call auditServiceListAuditEventsValidateBeforeCall(String filterOpsAccountID, String filterOpsContextChangeID, String filterOpsContextRequestID, String filterOpsContextTraceID, String filterOpsContextSessionID, String filterOpsContextActor, String filterOpsContextActorType, String filterOpsContextAccessType, String filterOpsContextIpAddress, String filterOpsContextOrigin, String filterOpsContextAuthMode, String filterOpsContextJwtID, String filterOpsContextBearerTokenContextID, String filterOpsParentAccountID, String filterOpsWorkspaceID, String filterOpsVaultID, String filterOpsResourceIDs, String filterOpsActionType, String filterOpsResourceType, String filterOpsTags, Integer filterOpsResponseCode, String filterOpsStartTime, String filterOpsEndTime, String filterOpsApiName, String filterOpsResponseMessage, String filterOpsHttpMethod, String filterOpsHttpURI, String sortOpsSortBy, String sortOpsOrderBy, String afterOpsTimestamp, String afterOpsChangeID, Long limit, Long offset, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'filterOpsAccountID' is set - if (filterOpsAccountID == null) { - throw new ApiException("Missing the required parameter 'filterOpsAccountID' when calling auditServiceListAuditEvents(Async)"); - } - - return auditServiceListAuditEventsCall(filterOpsAccountID, filterOpsContextChangeID, filterOpsContextRequestID, filterOpsContextTraceID, filterOpsContextSessionID, filterOpsContextActor, filterOpsContextActorType, filterOpsContextAccessType, filterOpsContextIpAddress, filterOpsContextOrigin, filterOpsContextAuthMode, filterOpsContextJwtID, filterOpsContextBearerTokenContextID, filterOpsParentAccountID, filterOpsWorkspaceID, filterOpsVaultID, filterOpsResourceIDs, filterOpsActionType, filterOpsResourceType, filterOpsTags, filterOpsResponseCode, filterOpsStartTime, filterOpsEndTime, filterOpsApiName, filterOpsResponseMessage, filterOpsHttpMethod, filterOpsHttpURI, sortOpsSortBy, sortOpsOrderBy, afterOpsTimestamp, afterOpsChangeID, limit, offset, _callback); - - } - - /** - * List Audit Events - * Lists audit events that match query parameters. - * @param filterOpsAccountID Resources with the specified account ID. (required) - * @param filterOpsContextChangeID ID for the audit event. (optional) - * @param filterOpsContextRequestID ID for the request that caused the event. (optional) - * @param filterOpsContextTraceID ID for the request set by the service that received the request. (optional) - * @param filterOpsContextSessionID ID for the session in which the request was sent. (optional) - * @param filterOpsContextActor Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. (optional) - * @param filterOpsContextActorType Type of member who sent the request. (optional, default to NONE) - * @param filterOpsContextAccessType Type of access for the request. (optional, default to ACCESS_NONE) - * @param filterOpsContextIpAddress IP Address of the client that made the request. (optional) - * @param filterOpsContextOrigin HTTP Origin request header (including scheme, hostname, and port) of the request. (optional) - * @param filterOpsContextAuthMode Authentication mode the `actor` used. (optional, default to AUTH_NONE) - * @param filterOpsContextJwtID ID of the JWT token. (optional) - * @param filterOpsContextBearerTokenContextID Embedded User Context. (optional) - * @param filterOpsParentAccountID Resources with the specified parent account ID. (optional) - * @param filterOpsWorkspaceID Resources with the specified workspace ID. (optional) - * @param filterOpsVaultID Resources with the specified vault ID. (optional) - * @param filterOpsResourceIDs Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\<resourceType\\>/\\<resourceID\\>\". For example, \"VAULT/12345, USER/67890\". (optional) - * @param filterOpsActionType Events with the specified action type. (optional, default to NONE) - * @param filterOpsResourceType Resources with the specified type. (optional, default to NONE_API) - * @param filterOpsTags Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\". (optional) - * @param filterOpsResponseCode HTTP response code of the request. (optional) - * @param filterOpsStartTime Start timestamp for the query, in SQL format. (optional) - * @param filterOpsEndTime End timestamp for the query, in SQL format. (optional) - * @param filterOpsApiName Name of the API called in the request. (optional) - * @param filterOpsResponseMessage Response message of the request. (optional) - * @param filterOpsHttpMethod HTTP method of the request. (optional) - * @param filterOpsHttpURI HTTP URI of the request. (optional) - * @param sortOpsSortBy Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\"). (optional) - * @param sortOpsOrderBy Ascending or descending ordering of results. (optional, default to ASCENDING) - * @param afterOpsTimestamp Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) - * @param afterOpsChangeID Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) - * @param limit Number of results to return. (optional, default to 25) - * @param offset Record position at which to start returning results. (optional, default to 0) - * @return V1AuditResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1AuditResponse auditServiceListAuditEvents(String filterOpsAccountID, String filterOpsContextChangeID, String filterOpsContextRequestID, String filterOpsContextTraceID, String filterOpsContextSessionID, String filterOpsContextActor, String filterOpsContextActorType, String filterOpsContextAccessType, String filterOpsContextIpAddress, String filterOpsContextOrigin, String filterOpsContextAuthMode, String filterOpsContextJwtID, String filterOpsContextBearerTokenContextID, String filterOpsParentAccountID, String filterOpsWorkspaceID, String filterOpsVaultID, String filterOpsResourceIDs, String filterOpsActionType, String filterOpsResourceType, String filterOpsTags, Integer filterOpsResponseCode, String filterOpsStartTime, String filterOpsEndTime, String filterOpsApiName, String filterOpsResponseMessage, String filterOpsHttpMethod, String filterOpsHttpURI, String sortOpsSortBy, String sortOpsOrderBy, String afterOpsTimestamp, String afterOpsChangeID, Long limit, Long offset) throws ApiException { - ApiResponse localVarResp = auditServiceListAuditEventsWithHttpInfo(filterOpsAccountID, filterOpsContextChangeID, filterOpsContextRequestID, filterOpsContextTraceID, filterOpsContextSessionID, filterOpsContextActor, filterOpsContextActorType, filterOpsContextAccessType, filterOpsContextIpAddress, filterOpsContextOrigin, filterOpsContextAuthMode, filterOpsContextJwtID, filterOpsContextBearerTokenContextID, filterOpsParentAccountID, filterOpsWorkspaceID, filterOpsVaultID, filterOpsResourceIDs, filterOpsActionType, filterOpsResourceType, filterOpsTags, filterOpsResponseCode, filterOpsStartTime, filterOpsEndTime, filterOpsApiName, filterOpsResponseMessage, filterOpsHttpMethod, filterOpsHttpURI, sortOpsSortBy, sortOpsOrderBy, afterOpsTimestamp, afterOpsChangeID, limit, offset); - return localVarResp.getData(); - } - - /** - * List Audit Events - * Lists audit events that match query parameters. - * @param filterOpsAccountID Resources with the specified account ID. (required) - * @param filterOpsContextChangeID ID for the audit event. (optional) - * @param filterOpsContextRequestID ID for the request that caused the event. (optional) - * @param filterOpsContextTraceID ID for the request set by the service that received the request. (optional) - * @param filterOpsContextSessionID ID for the session in which the request was sent. (optional) - * @param filterOpsContextActor Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. (optional) - * @param filterOpsContextActorType Type of member who sent the request. (optional, default to NONE) - * @param filterOpsContextAccessType Type of access for the request. (optional, default to ACCESS_NONE) - * @param filterOpsContextIpAddress IP Address of the client that made the request. (optional) - * @param filterOpsContextOrigin HTTP Origin request header (including scheme, hostname, and port) of the request. (optional) - * @param filterOpsContextAuthMode Authentication mode the `actor` used. (optional, default to AUTH_NONE) - * @param filterOpsContextJwtID ID of the JWT token. (optional) - * @param filterOpsContextBearerTokenContextID Embedded User Context. (optional) - * @param filterOpsParentAccountID Resources with the specified parent account ID. (optional) - * @param filterOpsWorkspaceID Resources with the specified workspace ID. (optional) - * @param filterOpsVaultID Resources with the specified vault ID. (optional) - * @param filterOpsResourceIDs Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\<resourceType\\>/\\<resourceID\\>\". For example, \"VAULT/12345, USER/67890\". (optional) - * @param filterOpsActionType Events with the specified action type. (optional, default to NONE) - * @param filterOpsResourceType Resources with the specified type. (optional, default to NONE_API) - * @param filterOpsTags Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\". (optional) - * @param filterOpsResponseCode HTTP response code of the request. (optional) - * @param filterOpsStartTime Start timestamp for the query, in SQL format. (optional) - * @param filterOpsEndTime End timestamp for the query, in SQL format. (optional) - * @param filterOpsApiName Name of the API called in the request. (optional) - * @param filterOpsResponseMessage Response message of the request. (optional) - * @param filterOpsHttpMethod HTTP method of the request. (optional) - * @param filterOpsHttpURI HTTP URI of the request. (optional) - * @param sortOpsSortBy Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\"). (optional) - * @param sortOpsOrderBy Ascending or descending ordering of results. (optional, default to ASCENDING) - * @param afterOpsTimestamp Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) - * @param afterOpsChangeID Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) - * @param limit Number of results to return. (optional, default to 25) - * @param offset Record position at which to start returning results. (optional, default to 0) - * @return ApiResponse<V1AuditResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse auditServiceListAuditEventsWithHttpInfo(String filterOpsAccountID, String filterOpsContextChangeID, String filterOpsContextRequestID, String filterOpsContextTraceID, String filterOpsContextSessionID, String filterOpsContextActor, String filterOpsContextActorType, String filterOpsContextAccessType, String filterOpsContextIpAddress, String filterOpsContextOrigin, String filterOpsContextAuthMode, String filterOpsContextJwtID, String filterOpsContextBearerTokenContextID, String filterOpsParentAccountID, String filterOpsWorkspaceID, String filterOpsVaultID, String filterOpsResourceIDs, String filterOpsActionType, String filterOpsResourceType, String filterOpsTags, Integer filterOpsResponseCode, String filterOpsStartTime, String filterOpsEndTime, String filterOpsApiName, String filterOpsResponseMessage, String filterOpsHttpMethod, String filterOpsHttpURI, String sortOpsSortBy, String sortOpsOrderBy, String afterOpsTimestamp, String afterOpsChangeID, Long limit, Long offset) throws ApiException { - okhttp3.Call localVarCall = auditServiceListAuditEventsValidateBeforeCall(filterOpsAccountID, filterOpsContextChangeID, filterOpsContextRequestID, filterOpsContextTraceID, filterOpsContextSessionID, filterOpsContextActor, filterOpsContextActorType, filterOpsContextAccessType, filterOpsContextIpAddress, filterOpsContextOrigin, filterOpsContextAuthMode, filterOpsContextJwtID, filterOpsContextBearerTokenContextID, filterOpsParentAccountID, filterOpsWorkspaceID, filterOpsVaultID, filterOpsResourceIDs, filterOpsActionType, filterOpsResourceType, filterOpsTags, filterOpsResponseCode, filterOpsStartTime, filterOpsEndTime, filterOpsApiName, filterOpsResponseMessage, filterOpsHttpMethod, filterOpsHttpURI, sortOpsSortBy, sortOpsOrderBy, afterOpsTimestamp, afterOpsChangeID, limit, offset, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * List Audit Events (asynchronously) - * Lists audit events that match query parameters. - * @param filterOpsAccountID Resources with the specified account ID. (required) - * @param filterOpsContextChangeID ID for the audit event. (optional) - * @param filterOpsContextRequestID ID for the request that caused the event. (optional) - * @param filterOpsContextTraceID ID for the request set by the service that received the request. (optional) - * @param filterOpsContextSessionID ID for the session in which the request was sent. (optional) - * @param filterOpsContextActor Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. (optional) - * @param filterOpsContextActorType Type of member who sent the request. (optional, default to NONE) - * @param filterOpsContextAccessType Type of access for the request. (optional, default to ACCESS_NONE) - * @param filterOpsContextIpAddress IP Address of the client that made the request. (optional) - * @param filterOpsContextOrigin HTTP Origin request header (including scheme, hostname, and port) of the request. (optional) - * @param filterOpsContextAuthMode Authentication mode the `actor` used. (optional, default to AUTH_NONE) - * @param filterOpsContextJwtID ID of the JWT token. (optional) - * @param filterOpsContextBearerTokenContextID Embedded User Context. (optional) - * @param filterOpsParentAccountID Resources with the specified parent account ID. (optional) - * @param filterOpsWorkspaceID Resources with the specified workspace ID. (optional) - * @param filterOpsVaultID Resources with the specified vault ID. (optional) - * @param filterOpsResourceIDs Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of \"\\<resourceType\\>/\\<resourceID\\>\". For example, \"VAULT/12345, USER/67890\". (optional) - * @param filterOpsActionType Events with the specified action type. (optional, default to NONE) - * @param filterOpsResourceType Resources with the specified type. (optional, default to NONE_API) - * @param filterOpsTags Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, \"login, get\". (optional) - * @param filterOpsResponseCode HTTP response code of the request. (optional) - * @param filterOpsStartTime Start timestamp for the query, in SQL format. (optional) - * @param filterOpsEndTime End timestamp for the query, in SQL format. (optional) - * @param filterOpsApiName Name of the API called in the request. (optional) - * @param filterOpsResponseMessage Response message of the request. (optional) - * @param filterOpsHttpMethod HTTP method of the request. (optional) - * @param filterOpsHttpURI HTTP URI of the request. (optional) - * @param sortOpsSortBy Fully-qualified field by which to sort results. Field names should be in camel case (for example, \"capitalization.camelCase\"). (optional) - * @param sortOpsOrderBy Ascending or descending ordering of results. (optional, default to ASCENDING) - * @param afterOpsTimestamp Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) - * @param afterOpsChangeID Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. (optional) - * @param limit Number of results to return. (optional, default to 25) - * @param offset Record position at which to start returning results. (optional, default to 0) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call auditServiceListAuditEventsAsync(String filterOpsAccountID, String filterOpsContextChangeID, String filterOpsContextRequestID, String filterOpsContextTraceID, String filterOpsContextSessionID, String filterOpsContextActor, String filterOpsContextActorType, String filterOpsContextAccessType, String filterOpsContextIpAddress, String filterOpsContextOrigin, String filterOpsContextAuthMode, String filterOpsContextJwtID, String filterOpsContextBearerTokenContextID, String filterOpsParentAccountID, String filterOpsWorkspaceID, String filterOpsVaultID, String filterOpsResourceIDs, String filterOpsActionType, String filterOpsResourceType, String filterOpsTags, Integer filterOpsResponseCode, String filterOpsStartTime, String filterOpsEndTime, String filterOpsApiName, String filterOpsResponseMessage, String filterOpsHttpMethod, String filterOpsHttpURI, String sortOpsSortBy, String sortOpsOrderBy, String afterOpsTimestamp, String afterOpsChangeID, Long limit, Long offset, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = auditServiceListAuditEventsValidateBeforeCall(filterOpsAccountID, filterOpsContextChangeID, filterOpsContextRequestID, filterOpsContextTraceID, filterOpsContextSessionID, filterOpsContextActor, filterOpsContextActorType, filterOpsContextAccessType, filterOpsContextIpAddress, filterOpsContextOrigin, filterOpsContextAuthMode, filterOpsContextJwtID, filterOpsContextBearerTokenContextID, filterOpsParentAccountID, filterOpsWorkspaceID, filterOpsVaultID, filterOpsResourceIDs, filterOpsActionType, filterOpsResourceType, filterOpsTags, filterOpsResponseCode, filterOpsStartTime, filterOpsEndTime, filterOpsApiName, filterOpsResponseMessage, filterOpsHttpMethod, filterOpsHttpURI, sortOpsSortBy, sortOpsOrderBy, afterOpsTimestamp, afterOpsChangeID, limit, offset, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java b/src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java deleted file mode 100644 index e26da776..00000000 --- a/src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Skyflow Management API - * # Management API This API controls aspects of your account and schema, including workspaces, vaults, keys, users, permissions, and more. The Management API is available from two base URIs:
  • Sandbox: https://manage.skyflowapis-preview.com
  • Production: https://manage.skyflowapis.com
When you make an API call, you need to add two headers:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
X-SKYFLOW-ACCOUNT-IDYour Skyflow account ID.X-SKYFLOW-ACCOUNT-ID: h451b763713e4424a7jke1bbkbbc84ef
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.api; - -import com.skyflow.generated.rest.ApiCallback; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.ApiException; -import com.skyflow.generated.rest.ApiResponse; -import com.skyflow.generated.rest.Configuration; -import com.skyflow.generated.rest.Pair; -import com.skyflow.generated.rest.ProgressRequestBody; -import com.skyflow.generated.rest.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import com.skyflow.generated.rest.models.GooglerpcStatus; -import com.skyflow.generated.rest.models.V1GetAuthTokenRequest; -import com.skyflow.generated.rest.models.V1GetAuthTokenResponse; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class AuthenticationApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public AuthenticationApi() { - this(Configuration.getDefaultApiClient()); - } - - public AuthenticationApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for authenticationServiceGetAuthToken - * @param body (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details -
- - - - - - -
Status Code Description Response Headers
200 A successful response. -
400 Invalid scope format. -
401 Key expired or JWT token unparseable. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call authenticationServiceGetAuthTokenCall(V1GetAuthTokenRequest body, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/v1/auth/sa/oauth/token"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call authenticationServiceGetAuthTokenValidateBeforeCall(V1GetAuthTokenRequest body, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling authenticationServiceGetAuthToken(Async)"); - } - - return authenticationServiceGetAuthTokenCall(body, _callback); - - } - - /** - * Get Bearer Token - * <p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p> - * @param body (required) - * @return V1GetAuthTokenResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - - - -
Status Code Description Response Headers
200 A successful response. -
400 Invalid scope format. -
401 Key expired or JWT token unparseable. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1GetAuthTokenResponse authenticationServiceGetAuthToken(V1GetAuthTokenRequest body) throws ApiException { - ApiResponse localVarResp = authenticationServiceGetAuthTokenWithHttpInfo(body); - return localVarResp.getData(); - } - - /** - * Get Bearer Token - * <p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p> - * @param body (required) - * @return ApiResponse<V1GetAuthTokenResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - - - -
Status Code Description Response Headers
200 A successful response. -
400 Invalid scope format. -
401 Key expired or JWT token unparseable. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse authenticationServiceGetAuthTokenWithHttpInfo(V1GetAuthTokenRequest body) throws ApiException { - okhttp3.Call localVarCall = authenticationServiceGetAuthTokenValidateBeforeCall(body, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Get Bearer Token (asynchronously) - * <p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p> - * @param body (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - - - -
Status Code Description Response Headers
200 A successful response. -
400 Invalid scope format. -
401 Key expired or JWT token unparseable. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call authenticationServiceGetAuthTokenAsync(V1GetAuthTokenRequest body, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = authenticationServiceGetAuthTokenValidateBeforeCall(body, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java b/src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java deleted file mode 100644 index da1a862a..00000000 --- a/src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.api; - -import com.skyflow.generated.rest.ApiCallback; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.ApiException; -import com.skyflow.generated.rest.ApiResponse; -import com.skyflow.generated.rest.Configuration; -import com.skyflow.generated.rest.Pair; -import com.skyflow.generated.rest.ProgressRequestBody; -import com.skyflow.generated.rest.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import com.skyflow.generated.rest.models.GooglerpcStatus; -import com.skyflow.generated.rest.models.V1BINListRequest; -import com.skyflow.generated.rest.models.V1BINListResponse; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class BinLookupApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public BinLookupApi() { - this(Configuration.getDefaultApiClient()); - } - - public BinLookupApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for bINListServiceListCardsOfBIN - * @param body Request to return specific card metadata. (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details -
- - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call bINListServiceListCardsOfBINCall(V1BINListRequest body, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/v1/card_lookup"; - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call bINListServiceListCardsOfBINValidateBeforeCall(V1BINListRequest body, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling bINListServiceListCardsOfBIN(Async)"); - } - - return bINListServiceListCardsOfBINCall(body, _callback); - - } - - /** - * Get BIN - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - * @param body Request to return specific card metadata. (required) - * @return V1BINListResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1BINListResponse bINListServiceListCardsOfBIN(V1BINListRequest body) throws ApiException { - ApiResponse localVarResp = bINListServiceListCardsOfBINWithHttpInfo(body); - return localVarResp.getData(); - } - - /** - * Get BIN - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - * @param body Request to return specific card metadata. (required) - * @return ApiResponse<V1BINListResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse bINListServiceListCardsOfBINWithHttpInfo(V1BINListRequest body) throws ApiException { - okhttp3.Call localVarCall = bINListServiceListCardsOfBINValidateBeforeCall(body, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Get BIN (asynchronously) - * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. - * @param body Request to return specific card metadata. (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call bINListServiceListCardsOfBINAsync(V1BINListRequest body, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = bINListServiceListCardsOfBINValidateBeforeCall(body, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/api/QueryApi.java b/src/main/java/com/skyflow/generated/rest/api/QueryApi.java deleted file mode 100644 index fad624ce..00000000 --- a/src/main/java/com/skyflow/generated/rest/api/QueryApi.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.api; - -import com.skyflow.generated.rest.ApiCallback; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.ApiException; -import com.skyflow.generated.rest.ApiResponse; -import com.skyflow.generated.rest.Configuration; -import com.skyflow.generated.rest.Pair; -import com.skyflow.generated.rest.ProgressRequestBody; -import com.skyflow.generated.rest.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import com.skyflow.generated.rest.models.GooglerpcStatus; -import com.skyflow.generated.rest.models.QueryServiceExecuteQueryBody; -import com.skyflow.generated.rest.models.V1GetQueryResponse; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class QueryApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public QueryApi() { - this(Configuration.getDefaultApiClient()); - } - - public QueryApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for queryServiceExecuteQuery - * @param vaultID ID of the vault. (required) - * @param body (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details -
- - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call queryServiceExecuteQueryCall(String vaultID, QueryServiceExecuteQueryBody body, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/v1/vaults/{vaultID}/query" - .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())); - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call queryServiceExecuteQueryValidateBeforeCall(String vaultID, QueryServiceExecuteQueryBody body, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'vaultID' is set - if (vaultID == null) { - throw new ApiException("Missing the required parameter 'vaultID' when calling queryServiceExecuteQuery(Async)"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling queryServiceExecuteQuery(Async)"); - } - - return queryServiceExecuteQueryCall(vaultID, body, _callback); - - } - - /** - * Execute Query - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support `?` conditional for columns with column-level encryption disabled.</li><ul> - * @param vaultID ID of the vault. (required) - * @param body (required) - * @return V1GetQueryResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1GetQueryResponse queryServiceExecuteQuery(String vaultID, QueryServiceExecuteQueryBody body) throws ApiException { - ApiResponse localVarResp = queryServiceExecuteQueryWithHttpInfo(vaultID, body); - return localVarResp.getData(); - } - - /** - * Execute Query - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support `?` conditional for columns with column-level encryption disabled.</li><ul> - * @param vaultID ID of the vault. (required) - * @param body (required) - * @return ApiResponse<V1GetQueryResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse queryServiceExecuteQueryWithHttpInfo(String vaultID, QueryServiceExecuteQueryBody body) throws ApiException { - okhttp3.Call localVarCall = queryServiceExecuteQueryValidateBeforeCall(vaultID, body, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Execute Query (asynchronously) - * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support `?` conditional for columns with column-level encryption disabled.</li><ul> - * @param vaultID ID of the vault. (required) - * @param body (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call queryServiceExecuteQueryAsync(String vaultID, QueryServiceExecuteQueryBody body, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = queryServiceExecuteQueryValidateBeforeCall(vaultID, body, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/api/RecordsApi.java b/src/main/java/com/skyflow/generated/rest/api/RecordsApi.java deleted file mode 100644 index d8d8257b..00000000 --- a/src/main/java/com/skyflow/generated/rest/api/RecordsApi.java +++ /dev/null @@ -1,1730 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.api; - -import com.skyflow.generated.rest.ApiCallback; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.ApiException; -import com.skyflow.generated.rest.ApiResponse; -import com.skyflow.generated.rest.Configuration; -import com.skyflow.generated.rest.Pair; -import com.skyflow.generated.rest.ProgressRequestBody; -import com.skyflow.generated.rest.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import java.io.File; -import com.skyflow.generated.rest.models.GooglerpcStatus; -import com.skyflow.generated.rest.models.RecordServiceBatchOperationBody; -import com.skyflow.generated.rest.models.RecordServiceBulkDeleteRecordBody; -import com.skyflow.generated.rest.models.RecordServiceInsertRecordBody; -import com.skyflow.generated.rest.models.RecordServiceUpdateRecordBody; -import com.skyflow.generated.rest.models.V1BatchOperationResponse; -import com.skyflow.generated.rest.models.V1BulkDeleteRecordResponse; -import com.skyflow.generated.rest.models.V1BulkGetRecordResponse; -import com.skyflow.generated.rest.models.V1DeleteFileResponse; -import com.skyflow.generated.rest.models.V1DeleteRecordResponse; -import com.skyflow.generated.rest.models.V1FieldRecords; -import com.skyflow.generated.rest.models.V1GetFileScanStatusResponse; -import com.skyflow.generated.rest.models.V1InsertRecordResponse; -import com.skyflow.generated.rest.models.V1UpdateRecordResponse; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class RecordsApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public RecordsApi() { - this(Configuration.getDefaultApiClient()); - } - - public RecordsApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for fileServiceDeleteFile - * @param vaultID ID of the vault. (required) - * @param tableName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param columnName Name of the column that contains the file. (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details -
- - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call fileServiceDeleteFileCall(String vaultID, String tableName, String ID, String columnName, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/v1/vaults/{vaultID}/{tableName}/{ID}/files/{columnName}" - .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) - .replace("{" + "tableName" + "}", localVarApiClient.escapeString(tableName.toString())) - .replace("{" + "ID" + "}", localVarApiClient.escapeString(ID.toString())) - .replace("{" + "columnName" + "}", localVarApiClient.escapeString(columnName.toString())); - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call fileServiceDeleteFileValidateBeforeCall(String vaultID, String tableName, String ID, String columnName, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'vaultID' is set - if (vaultID == null) { - throw new ApiException("Missing the required parameter 'vaultID' when calling fileServiceDeleteFile(Async)"); - } - - // verify the required parameter 'tableName' is set - if (tableName == null) { - throw new ApiException("Missing the required parameter 'tableName' when calling fileServiceDeleteFile(Async)"); - } - - // verify the required parameter 'ID' is set - if (ID == null) { - throw new ApiException("Missing the required parameter 'ID' when calling fileServiceDeleteFile(Async)"); - } - - // verify the required parameter 'columnName' is set - if (columnName == null) { - throw new ApiException("Missing the required parameter 'columnName' when calling fileServiceDeleteFile(Async)"); - } - - return fileServiceDeleteFileCall(vaultID, tableName, ID, columnName, _callback); - - } - - /** - * Delete File - * Deletes a file from the specified record. - * @param vaultID ID of the vault. (required) - * @param tableName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param columnName Name of the column that contains the file. (required) - * @return V1DeleteFileResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1DeleteFileResponse fileServiceDeleteFile(String vaultID, String tableName, String ID, String columnName) throws ApiException { - ApiResponse localVarResp = fileServiceDeleteFileWithHttpInfo(vaultID, tableName, ID, columnName); - return localVarResp.getData(); - } - - /** - * Delete File - * Deletes a file from the specified record. - * @param vaultID ID of the vault. (required) - * @param tableName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param columnName Name of the column that contains the file. (required) - * @return ApiResponse<V1DeleteFileResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse fileServiceDeleteFileWithHttpInfo(String vaultID, String tableName, String ID, String columnName) throws ApiException { - okhttp3.Call localVarCall = fileServiceDeleteFileValidateBeforeCall(vaultID, tableName, ID, columnName, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Delete File (asynchronously) - * Deletes a file from the specified record. - * @param vaultID ID of the vault. (required) - * @param tableName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param columnName Name of the column that contains the file. (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call fileServiceDeleteFileAsync(String vaultID, String tableName, String ID, String columnName, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = fileServiceDeleteFileValidateBeforeCall(vaultID, tableName, ID, columnName, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for fileServiceGetFileScanStatus - * @param vaultID ID of the vault. (required) - * @param tableName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param columnName Name of the column that contains the file. (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call fileServiceGetFileScanStatusCall(String vaultID, String tableName, String ID, String columnName, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/v1/vaults/{vaultID}/{tableName}/{ID}/files/{columnName}/scan-status" - .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) - .replace("{" + "tableName" + "}", localVarApiClient.escapeString(tableName.toString())) - .replace("{" + "ID" + "}", localVarApiClient.escapeString(ID.toString())) - .replace("{" + "columnName" + "}", localVarApiClient.escapeString(columnName.toString())); - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call fileServiceGetFileScanStatusValidateBeforeCall(String vaultID, String tableName, String ID, String columnName, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'vaultID' is set - if (vaultID == null) { - throw new ApiException("Missing the required parameter 'vaultID' when calling fileServiceGetFileScanStatus(Async)"); - } - - // verify the required parameter 'tableName' is set - if (tableName == null) { - throw new ApiException("Missing the required parameter 'tableName' when calling fileServiceGetFileScanStatus(Async)"); - } - - // verify the required parameter 'ID' is set - if (ID == null) { - throw new ApiException("Missing the required parameter 'ID' when calling fileServiceGetFileScanStatus(Async)"); - } - - // verify the required parameter 'columnName' is set - if (columnName == null) { - throw new ApiException("Missing the required parameter 'columnName' when calling fileServiceGetFileScanStatus(Async)"); - } - - return fileServiceGetFileScanStatusCall(vaultID, tableName, ID, columnName, _callback); - - } - - /** - * Get File Scan Status - * Returns the anti-virus scan status of a file. - * @param vaultID ID of the vault. (required) - * @param tableName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param columnName Name of the column that contains the file. (required) - * @return V1GetFileScanStatusResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1GetFileScanStatusResponse fileServiceGetFileScanStatus(String vaultID, String tableName, String ID, String columnName) throws ApiException { - ApiResponse localVarResp = fileServiceGetFileScanStatusWithHttpInfo(vaultID, tableName, ID, columnName); - return localVarResp.getData(); - } - - /** - * Get File Scan Status - * Returns the anti-virus scan status of a file. - * @param vaultID ID of the vault. (required) - * @param tableName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param columnName Name of the column that contains the file. (required) - * @return ApiResponse<V1GetFileScanStatusResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse fileServiceGetFileScanStatusWithHttpInfo(String vaultID, String tableName, String ID, String columnName) throws ApiException { - okhttp3.Call localVarCall = fileServiceGetFileScanStatusValidateBeforeCall(vaultID, tableName, ID, columnName, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Get File Scan Status (asynchronously) - * Returns the anti-virus scan status of a file. - * @param vaultID ID of the vault. (required) - * @param tableName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param columnName Name of the column that contains the file. (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call fileServiceGetFileScanStatusAsync(String vaultID, String tableName, String ID, String columnName, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = fileServiceGetFileScanStatusValidateBeforeCall(vaultID, tableName, ID, columnName, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for fileServiceUploadFile - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param fileColumnName Name of the column to store the file in. The column must have a file data type. (optional) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call fileServiceUploadFileCall(String vaultID, String objectName, String ID, File fileColumnName, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/v1/vaults/{vaultID}/{objectName}/{ID}/files" - .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) - .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())) - .replace("{" + "ID" + "}", localVarApiClient.escapeString(ID.toString())); - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - if (fileColumnName != null) { - localVarFormParams.put("fileColumnName", fileColumnName); - } - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call fileServiceUploadFileValidateBeforeCall(String vaultID, String objectName, String ID, File fileColumnName, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'vaultID' is set - if (vaultID == null) { - throw new ApiException("Missing the required parameter 'vaultID' when calling fileServiceUploadFile(Async)"); - } - - // verify the required parameter 'objectName' is set - if (objectName == null) { - throw new ApiException("Missing the required parameter 'objectName' when calling fileServiceUploadFile(Async)"); - } - - // verify the required parameter 'ID' is set - if (ID == null) { - throw new ApiException("Missing the required parameter 'ID' when calling fileServiceUploadFile(Async)"); - } - - return fileServiceUploadFileCall(vaultID, objectName, ID, fileColumnName, _callback); - - } - - /** - * Upload File - * Uploads a file to the specified record. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param fileColumnName Name of the column to store the file in. The column must have a file data type. (optional) - * @return V1UpdateRecordResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1UpdateRecordResponse fileServiceUploadFile(String vaultID, String objectName, String ID, File fileColumnName) throws ApiException { - ApiResponse localVarResp = fileServiceUploadFileWithHttpInfo(vaultID, objectName, ID, fileColumnName); - return localVarResp.getData(); - } - - /** - * Upload File - * Uploads a file to the specified record. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param fileColumnName Name of the column to store the file in. The column must have a file data type. (optional) - * @return ApiResponse<V1UpdateRecordResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse fileServiceUploadFileWithHttpInfo(String vaultID, String objectName, String ID, File fileColumnName) throws ApiException { - okhttp3.Call localVarCall = fileServiceUploadFileValidateBeforeCall(vaultID, objectName, ID, fileColumnName, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Upload File (asynchronously) - * Uploads a file to the specified record. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param fileColumnName Name of the column to store the file in. The column must have a file data type. (optional) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call fileServiceUploadFileAsync(String vaultID, String objectName, String ID, File fileColumnName, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = fileServiceUploadFileValidateBeforeCall(vaultID, objectName, ID, fileColumnName, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for recordServiceBatchOperation - * @param vaultID ID of the vault. (required) - * @param body (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceBatchOperationCall(String vaultID, RecordServiceBatchOperationBody body, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/v1/vaults/{vaultID}" - .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())); - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call recordServiceBatchOperationValidateBeforeCall(String vaultID, RecordServiceBatchOperationBody body, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'vaultID' is set - if (vaultID == null) { - throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceBatchOperation(Async)"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling recordServiceBatchOperation(Async)"); - } - - return recordServiceBatchOperationCall(vaultID, body, _callback); - - } - - /** - * Batch Operation - * Performs multiple record operations in a single transaction. - * @param vaultID ID of the vault. (required) - * @param body (required) - * @return V1BatchOperationResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1BatchOperationResponse recordServiceBatchOperation(String vaultID, RecordServiceBatchOperationBody body) throws ApiException { - ApiResponse localVarResp = recordServiceBatchOperationWithHttpInfo(vaultID, body); - return localVarResp.getData(); - } - - /** - * Batch Operation - * Performs multiple record operations in a single transaction. - * @param vaultID ID of the vault. (required) - * @param body (required) - * @return ApiResponse<V1BatchOperationResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse recordServiceBatchOperationWithHttpInfo(String vaultID, RecordServiceBatchOperationBody body) throws ApiException { - okhttp3.Call localVarCall = recordServiceBatchOperationValidateBeforeCall(vaultID, body, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Batch Operation (asynchronously) - * Performs multiple record operations in a single transaction. - * @param vaultID ID of the vault. (required) - * @param body (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceBatchOperationAsync(String vaultID, RecordServiceBatchOperationBody body, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = recordServiceBatchOperationValidateBeforeCall(vaultID, body, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for recordServiceBulkDeleteRecord - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param body (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceBulkDeleteRecordCall(String vaultID, String objectName, RecordServiceBulkDeleteRecordBody body, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/v1/vaults/{vaultID}/{objectName}" - .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) - .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())); - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call recordServiceBulkDeleteRecordValidateBeforeCall(String vaultID, String objectName, RecordServiceBulkDeleteRecordBody body, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'vaultID' is set - if (vaultID == null) { - throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceBulkDeleteRecord(Async)"); - } - - // verify the required parameter 'objectName' is set - if (objectName == null) { - throw new ApiException("Missing the required parameter 'objectName' when calling recordServiceBulkDeleteRecord(Async)"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling recordServiceBulkDeleteRecord(Async)"); - } - - return recordServiceBulkDeleteRecordCall(vaultID, objectName, body, _callback); - - } - - /** - * Bulk Delete Records - * Deletes the specified records from a table. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param body (required) - * @return V1BulkDeleteRecordResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1BulkDeleteRecordResponse recordServiceBulkDeleteRecord(String vaultID, String objectName, RecordServiceBulkDeleteRecordBody body) throws ApiException { - ApiResponse localVarResp = recordServiceBulkDeleteRecordWithHttpInfo(vaultID, objectName, body); - return localVarResp.getData(); - } - - /** - * Bulk Delete Records - * Deletes the specified records from a table. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param body (required) - * @return ApiResponse<V1BulkDeleteRecordResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse recordServiceBulkDeleteRecordWithHttpInfo(String vaultID, String objectName, RecordServiceBulkDeleteRecordBody body) throws ApiException { - okhttp3.Call localVarCall = recordServiceBulkDeleteRecordValidateBeforeCall(vaultID, objectName, body, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Bulk Delete Records (asynchronously) - * Deletes the specified records from a table. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param body (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceBulkDeleteRecordAsync(String vaultID, String objectName, RecordServiceBulkDeleteRecordBody body, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = recordServiceBulkDeleteRecordValidateBeforeCall(vaultID, objectName, body, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for recordServiceBulkGetRecord - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table that contains the records. (required) - * @param skyflowIds `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.<br /><br />If not specified, returns the first 25 records in the table. (optional) - * @param redaction Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. (optional, default to DEFAULT) - * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) - * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) - * @param offset Record position at which to start receiving data. (optional, default to 0) - * @param limit Number of record to return. Maximum 25. (optional, default to 25) - * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) - * @param columnName Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) - * @param columnValues Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.<br /><br />`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) - * @param orderBy Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. (optional, default to ASCENDING) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceBulkGetRecordCall(String vaultID, String objectName, List skyflowIds, String redaction, Boolean tokenization, List fields, String offset, String limit, Boolean downloadURL, String columnName, List columnValues, String orderBy, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/v1/vaults/{vaultID}/{objectName}" - .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) - .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())); - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - if (skyflowIds != null) { - localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "skyflow_ids", skyflowIds)); - } - - if (redaction != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("redaction", redaction)); - } - - if (tokenization != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("tokenization", tokenization)); - } - - if (fields != null) { - localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "fields", fields)); - } - - if (offset != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("offset", offset)); - } - - if (limit != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("limit", limit)); - } - - if (downloadURL != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("downloadURL", downloadURL)); - } - - if (columnName != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("column_name", columnName)); - } - - if (columnValues != null) { - localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "column_values", columnValues)); - } - - if (orderBy != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("order_by", orderBy)); - } - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call recordServiceBulkGetRecordValidateBeforeCall(String vaultID, String objectName, List skyflowIds, String redaction, Boolean tokenization, List fields, String offset, String limit, Boolean downloadURL, String columnName, List columnValues, String orderBy, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'vaultID' is set - if (vaultID == null) { - throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceBulkGetRecord(Async)"); - } - - // verify the required parameter 'objectName' is set - if (objectName == null) { - throw new ApiException("Missing the required parameter 'objectName' when calling recordServiceBulkGetRecord(Async)"); - } - - return recordServiceBulkGetRecordCall(vaultID, objectName, skyflowIds, redaction, tokenization, fields, offset, limit, downloadURL, columnName, columnValues, orderBy, _callback); - - } - - /** - * Get Record(s) - * Gets the specified records from a table. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table that contains the records. (required) - * @param skyflowIds `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.<br /><br />If not specified, returns the first 25 records in the table. (optional) - * @param redaction Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. (optional, default to DEFAULT) - * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) - * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) - * @param offset Record position at which to start receiving data. (optional, default to 0) - * @param limit Number of record to return. Maximum 25. (optional, default to 25) - * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) - * @param columnName Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) - * @param columnValues Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.<br /><br />`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) - * @param orderBy Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. (optional, default to ASCENDING) - * @return V1BulkGetRecordResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1BulkGetRecordResponse recordServiceBulkGetRecord(String vaultID, String objectName, List skyflowIds, String redaction, Boolean tokenization, List fields, String offset, String limit, Boolean downloadURL, String columnName, List columnValues, String orderBy) throws ApiException { - ApiResponse localVarResp = recordServiceBulkGetRecordWithHttpInfo(vaultID, objectName, skyflowIds, redaction, tokenization, fields, offset, limit, downloadURL, columnName, columnValues, orderBy); - return localVarResp.getData(); - } - - /** - * Get Record(s) - * Gets the specified records from a table. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table that contains the records. (required) - * @param skyflowIds `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.<br /><br />If not specified, returns the first 25 records in the table. (optional) - * @param redaction Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. (optional, default to DEFAULT) - * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) - * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) - * @param offset Record position at which to start receiving data. (optional, default to 0) - * @param limit Number of record to return. Maximum 25. (optional, default to 25) - * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) - * @param columnName Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) - * @param columnValues Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.<br /><br />`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) - * @param orderBy Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. (optional, default to ASCENDING) - * @return ApiResponse<V1BulkGetRecordResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse recordServiceBulkGetRecordWithHttpInfo(String vaultID, String objectName, List skyflowIds, String redaction, Boolean tokenization, List fields, String offset, String limit, Boolean downloadURL, String columnName, List columnValues, String orderBy) throws ApiException { - okhttp3.Call localVarCall = recordServiceBulkGetRecordValidateBeforeCall(vaultID, objectName, skyflowIds, redaction, tokenization, fields, offset, limit, downloadURL, columnName, columnValues, orderBy, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Get Record(s) (asynchronously) - * Gets the specified records from a table. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table that contains the records. (required) - * @param skyflowIds `skyflow_id` values of the records to return, with one value per `skyflow_ids` URL parameter. For example, `?skyflow_ids=abc&skyflow_ids=123`.<br /><br />If not specified, returns the first 25 records in the table. (optional) - * @param redaction Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. (optional, default to DEFAULT) - * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) - * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) - * @param offset Record position at which to start receiving data. (optional, default to 0) - * @param limit Number of record to return. Maximum 25. (optional, default to 25) - * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) - * @param columnName Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) - * @param columnValues Column values of the records to return, with one value per `column_values` URL parameter. For example, `?column_values=abc&column_values=123`.<br /><br />`column_name` is mandatory when providing `column_values`. If you use column name or column value, you cannot use `skyflow_ids`. Passing either of these parameters with `skyflow_ids` returns an error. (optional) - * @param orderBy Order to return records, based on `skyflow_id` values. To disable, set to `NONE`. (optional, default to ASCENDING) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceBulkGetRecordAsync(String vaultID, String objectName, List skyflowIds, String redaction, Boolean tokenization, List fields, String offset, String limit, Boolean downloadURL, String columnName, List columnValues, String orderBy, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = recordServiceBulkGetRecordValidateBeforeCall(vaultID, objectName, skyflowIds, redaction, tokenization, fields, offset, limit, downloadURL, columnName, columnValues, orderBy, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for recordServiceDeleteRecord - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record to delete. (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceDeleteRecordCall(String vaultID, String objectName, String ID, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/v1/vaults/{vaultID}/{objectName}/{ID}" - .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) - .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())) - .replace("{" + "ID" + "}", localVarApiClient.escapeString(ID.toString())); - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call recordServiceDeleteRecordValidateBeforeCall(String vaultID, String objectName, String ID, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'vaultID' is set - if (vaultID == null) { - throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceDeleteRecord(Async)"); - } - - // verify the required parameter 'objectName' is set - if (objectName == null) { - throw new ApiException("Missing the required parameter 'objectName' when calling recordServiceDeleteRecord(Async)"); - } - - // verify the required parameter 'ID' is set - if (ID == null) { - throw new ApiException("Missing the required parameter 'ID' when calling recordServiceDeleteRecord(Async)"); - } - - return recordServiceDeleteRecordCall(vaultID, objectName, ID, _callback); - - } - - /** - * Delete Record - * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record to delete. (required) - * @return V1DeleteRecordResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1DeleteRecordResponse recordServiceDeleteRecord(String vaultID, String objectName, String ID) throws ApiException { - ApiResponse localVarResp = recordServiceDeleteRecordWithHttpInfo(vaultID, objectName, ID); - return localVarResp.getData(); - } - - /** - * Delete Record - * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record to delete. (required) - * @return ApiResponse<V1DeleteRecordResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse recordServiceDeleteRecordWithHttpInfo(String vaultID, String objectName, String ID) throws ApiException { - okhttp3.Call localVarCall = recordServiceDeleteRecordValidateBeforeCall(vaultID, objectName, ID, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Delete Record (asynchronously) - * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record to delete. (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceDeleteRecordAsync(String vaultID, String objectName, String ID, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = recordServiceDeleteRecordValidateBeforeCall(vaultID, objectName, ID, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for recordServiceGetRecord - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param redaction Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. (optional, default to DEFAULT) - * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) - * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) - * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceGetRecordCall(String vaultID, String objectName, String ID, String redaction, Boolean tokenization, List fields, Boolean downloadURL, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/v1/vaults/{vaultID}/{objectName}/{ID}" - .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) - .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())) - .replace("{" + "ID" + "}", localVarApiClient.escapeString(ID.toString())); - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - if (redaction != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("redaction", redaction)); - } - - if (tokenization != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("tokenization", tokenization)); - } - - if (fields != null) { - localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "fields", fields)); - } - - if (downloadURL != null) { - localVarQueryParams.addAll(localVarApiClient.parameterToPair("downloadURL", downloadURL)); - } - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call recordServiceGetRecordValidateBeforeCall(String vaultID, String objectName, String ID, String redaction, Boolean tokenization, List fields, Boolean downloadURL, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'vaultID' is set - if (vaultID == null) { - throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceGetRecord(Async)"); - } - - // verify the required parameter 'objectName' is set - if (objectName == null) { - throw new ApiException("Missing the required parameter 'objectName' when calling recordServiceGetRecord(Async)"); - } - - // verify the required parameter 'ID' is set - if (ID == null) { - throw new ApiException("Missing the required parameter 'ID' when calling recordServiceGetRecord(Async)"); - } - - return recordServiceGetRecordCall(vaultID, objectName, ID, redaction, tokenization, fields, downloadURL, _callback); - - } - - /** - * Get Record By ID - * Returns the specified record from a table. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param redaction Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. (optional, default to DEFAULT) - * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) - * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) - * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) - * @return V1FieldRecords - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1FieldRecords recordServiceGetRecord(String vaultID, String objectName, String ID, String redaction, Boolean tokenization, List fields, Boolean downloadURL) throws ApiException { - ApiResponse localVarResp = recordServiceGetRecordWithHttpInfo(vaultID, objectName, ID, redaction, tokenization, fields, downloadURL); - return localVarResp.getData(); - } - - /** - * Get Record By ID - * Returns the specified record from a table. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param redaction Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. (optional, default to DEFAULT) - * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) - * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) - * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) - * @return ApiResponse<V1FieldRecords> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse recordServiceGetRecordWithHttpInfo(String vaultID, String objectName, String ID, String redaction, Boolean tokenization, List fields, Boolean downloadURL) throws ApiException { - okhttp3.Call localVarCall = recordServiceGetRecordValidateBeforeCall(vaultID, objectName, ID, redaction, tokenization, fields, downloadURL, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Get Record By ID (asynchronously) - * Returns the specified record from a table. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param redaction Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. (optional, default to DEFAULT) - * @param tokenization If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. (optional) - * @param fields Fields to return for the record, with one value per `fields` URL parameter. For example, `?fields=abc&fields=123`.<br /><br />If not specified, returns all fields. (optional) - * @param downloadURL If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. (optional) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceGetRecordAsync(String vaultID, String objectName, String ID, String redaction, Boolean tokenization, List fields, Boolean downloadURL, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = recordServiceGetRecordValidateBeforeCall(vaultID, objectName, ID, redaction, tokenization, fields, downloadURL, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for recordServiceInsertRecord - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param body (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceInsertRecordCall(String vaultID, String objectName, RecordServiceInsertRecordBody body, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/v1/vaults/{vaultID}/{objectName}" - .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) - .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())); - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call recordServiceInsertRecordValidateBeforeCall(String vaultID, String objectName, RecordServiceInsertRecordBody body, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'vaultID' is set - if (vaultID == null) { - throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceInsertRecord(Async)"); - } - - // verify the required parameter 'objectName' is set - if (objectName == null) { - throw new ApiException("Missing the required parameter 'objectName' when calling recordServiceInsertRecord(Async)"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling recordServiceInsertRecord(Async)"); - } - - return recordServiceInsertRecordCall(vaultID, objectName, body, _callback); - - } - - /** - * Insert Records - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param body (required) - * @return V1InsertRecordResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1InsertRecordResponse recordServiceInsertRecord(String vaultID, String objectName, RecordServiceInsertRecordBody body) throws ApiException { - ApiResponse localVarResp = recordServiceInsertRecordWithHttpInfo(vaultID, objectName, body); - return localVarResp.getData(); - } - - /** - * Insert Records - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param body (required) - * @return ApiResponse<V1InsertRecordResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse recordServiceInsertRecordWithHttpInfo(String vaultID, String objectName, RecordServiceInsertRecordBody body) throws ApiException { - okhttp3.Call localVarCall = recordServiceInsertRecordValidateBeforeCall(vaultID, objectName, body, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Insert Records (asynchronously) - * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param body (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceInsertRecordAsync(String vaultID, String objectName, RecordServiceInsertRecordBody body, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = recordServiceInsertRecordValidateBeforeCall(vaultID, objectName, body, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for recordServiceUpdateRecord - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param body (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceUpdateRecordCall(String vaultID, String objectName, String ID, RecordServiceUpdateRecordBody body, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/v1/vaults/{vaultID}/{objectName}/{ID}" - .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())) - .replace("{" + "objectName" + "}", localVarApiClient.escapeString(objectName.toString())) - .replace("{" + "ID" + "}", localVarApiClient.escapeString(ID.toString())); - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call recordServiceUpdateRecordValidateBeforeCall(String vaultID, String objectName, String ID, RecordServiceUpdateRecordBody body, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'vaultID' is set - if (vaultID == null) { - throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceUpdateRecord(Async)"); - } - - // verify the required parameter 'objectName' is set - if (objectName == null) { - throw new ApiException("Missing the required parameter 'objectName' when calling recordServiceUpdateRecord(Async)"); - } - - // verify the required parameter 'ID' is set - if (ID == null) { - throw new ApiException("Missing the required parameter 'ID' when calling recordServiceUpdateRecord(Async)"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling recordServiceUpdateRecord(Async)"); - } - - return recordServiceUpdateRecordCall(vaultID, objectName, ID, body, _callback); - - } - - /** - * Update Record - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param body (required) - * @return V1UpdateRecordResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1UpdateRecordResponse recordServiceUpdateRecord(String vaultID, String objectName, String ID, RecordServiceUpdateRecordBody body) throws ApiException { - ApiResponse localVarResp = recordServiceUpdateRecordWithHttpInfo(vaultID, objectName, ID, body); - return localVarResp.getData(); - } - - /** - * Update Record - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param body (required) - * @return ApiResponse<V1UpdateRecordResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse recordServiceUpdateRecordWithHttpInfo(String vaultID, String objectName, String ID, RecordServiceUpdateRecordBody body) throws ApiException { - okhttp3.Call localVarCall = recordServiceUpdateRecordValidateBeforeCall(vaultID, objectName, ID, body, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Update Record (asynchronously) - * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. - * @param vaultID ID of the vault. (required) - * @param objectName Name of the table. (required) - * @param ID `skyflow_id` of the record. (required) - * @param body (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceUpdateRecordAsync(String vaultID, String objectName, String ID, RecordServiceUpdateRecordBody body, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = recordServiceUpdateRecordValidateBeforeCall(vaultID, objectName, ID, body, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/api/TokensApi.java b/src/main/java/com/skyflow/generated/rest/api/TokensApi.java deleted file mode 100644 index f2ec51a3..00000000 --- a/src/main/java/com/skyflow/generated/rest/api/TokensApi.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.api; - -import com.skyflow.generated.rest.ApiCallback; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.ApiException; -import com.skyflow.generated.rest.ApiResponse; -import com.skyflow.generated.rest.Configuration; -import com.skyflow.generated.rest.Pair; -import com.skyflow.generated.rest.ProgressRequestBody; -import com.skyflow.generated.rest.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import com.skyflow.generated.rest.models.GooglerpcStatus; -import com.skyflow.generated.rest.models.V1DetokenizePayload; -import com.skyflow.generated.rest.models.V1DetokenizeResponse; -import com.skyflow.generated.rest.models.V1TokenizePayload; -import com.skyflow.generated.rest.models.V1TokenizeResponse; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class TokensApi { - private ApiClient localVarApiClient; - private int localHostIndex; - private String localCustomBaseUrl; - - public TokensApi() { - this(Configuration.getDefaultApiClient()); - } - - public TokensApi(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public ApiClient getApiClient() { - return localVarApiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.localVarApiClient = apiClient; - } - - public int getHostIndex() { - return localHostIndex; - } - - public void setHostIndex(int hostIndex) { - this.localHostIndex = hostIndex; - } - - public String getCustomBaseUrl() { - return localCustomBaseUrl; - } - - public void setCustomBaseUrl(String customBaseUrl) { - this.localCustomBaseUrl = customBaseUrl; - } - - /** - * Build call for recordServiceDetokenize - * @param vaultID ID of the vault. (required) - * @param detokenizePayload (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details -
- - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceDetokenizeCall(String vaultID, V1DetokenizePayload detokenizePayload, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = detokenizePayload; - - // create path and map variables - String localVarPath = "/v1/vaults/{vaultID}/detokenize" - .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())); - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call recordServiceDetokenizeValidateBeforeCall(String vaultID, V1DetokenizePayload detokenizePayload, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'vaultID' is set - if (vaultID == null) { - throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceDetokenize(Async)"); - } - - // verify the required parameter 'detokenizePayload' is set - if (detokenizePayload == null) { - throw new ApiException("Missing the required parameter 'detokenizePayload' when calling recordServiceDetokenize(Async)"); - } - - return recordServiceDetokenizeCall(vaultID, detokenizePayload, _callback); - - } - - /** - * Detokenize - * Returns records that correspond to the specified tokens. - * @param vaultID ID of the vault. (required) - * @param detokenizePayload (required) - * @return V1DetokenizeResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1DetokenizeResponse recordServiceDetokenize(String vaultID, V1DetokenizePayload detokenizePayload) throws ApiException { - ApiResponse localVarResp = recordServiceDetokenizeWithHttpInfo(vaultID, detokenizePayload); - return localVarResp.getData(); - } - - /** - * Detokenize - * Returns records that correspond to the specified tokens. - * @param vaultID ID of the vault. (required) - * @param detokenizePayload (required) - * @return ApiResponse<V1DetokenizeResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse recordServiceDetokenizeWithHttpInfo(String vaultID, V1DetokenizePayload detokenizePayload) throws ApiException { - okhttp3.Call localVarCall = recordServiceDetokenizeValidateBeforeCall(vaultID, detokenizePayload, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Detokenize (asynchronously) - * Returns records that correspond to the specified tokens. - * @param vaultID ID of the vault. (required) - * @param detokenizePayload (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceDetokenizeAsync(String vaultID, V1DetokenizePayload detokenizePayload, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = recordServiceDetokenizeValidateBeforeCall(vaultID, detokenizePayload, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } - /** - * Build call for recordServiceTokenize - * @param vaultID ID of the vault. (required) - * @param tokenizePayload (required) - * @param _callback Callback for upload/download progress - * @return Call to execute - * @throws ApiException If fail to serialize the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceTokenizeCall(String vaultID, V1TokenizePayload tokenizePayload, final ApiCallback _callback) throws ApiException { - String basePath = null; - // Operation Servers - String[] localBasePaths = new String[] { }; - - // Determine Base Path to Use - if (localCustomBaseUrl != null){ - basePath = localCustomBaseUrl; - } else if ( localBasePaths.length > 0 ) { - basePath = localBasePaths[localHostIndex]; - } else { - basePath = null; - } - - Object localVarPostBody = tokenizePayload; - - // create path and map variables - String localVarPath = "/v1/vaults/{vaultID}/tokenize" - .replace("{" + "vaultID" + "}", localVarApiClient.escapeString(vaultID.toString())); - - List localVarQueryParams = new ArrayList(); - List localVarCollectionQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarCookieParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) { - localVarHeaderParams.put("Accept", localVarAccept); - } - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); - if (localVarContentType != null) { - localVarHeaderParams.put("Content-Type", localVarContentType); - } - - String[] localVarAuthNames = new String[] { "Bearer" }; - return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); - } - - @SuppressWarnings("rawtypes") - private okhttp3.Call recordServiceTokenizeValidateBeforeCall(String vaultID, V1TokenizePayload tokenizePayload, final ApiCallback _callback) throws ApiException { - // verify the required parameter 'vaultID' is set - if (vaultID == null) { - throw new ApiException("Missing the required parameter 'vaultID' when calling recordServiceTokenize(Async)"); - } - - // verify the required parameter 'tokenizePayload' is set - if (tokenizePayload == null) { - throw new ApiException("Missing the required parameter 'tokenizePayload' when calling recordServiceTokenize(Async)"); - } - - return recordServiceTokenizeCall(vaultID, tokenizePayload, _callback); - - } - - /** - * Tokenize - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. - * @param vaultID ID of the vault. (required) - * @param tokenizePayload (required) - * @return V1TokenizeResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public V1TokenizeResponse recordServiceTokenize(String vaultID, V1TokenizePayload tokenizePayload) throws ApiException { - ApiResponse localVarResp = recordServiceTokenizeWithHttpInfo(vaultID, tokenizePayload); - return localVarResp.getData(); - } - - /** - * Tokenize - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. - * @param vaultID ID of the vault. (required) - * @param tokenizePayload (required) - * @return ApiResponse<V1TokenizeResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public ApiResponse recordServiceTokenizeWithHttpInfo(String vaultID, V1TokenizePayload tokenizePayload) throws ApiException { - okhttp3.Call localVarCall = recordServiceTokenizeValidateBeforeCall(vaultID, tokenizePayload, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return localVarApiClient.execute(localVarCall, localVarReturnType); - } - - /** - * Tokenize (asynchronously) - * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. - * @param vaultID ID of the vault. (required) - * @param tokenizePayload (required) - * @param _callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - * @http.response.details - - - - - -
Status Code Description Response Headers
200 A successful response. -
404 Returned when the resource does not exist. -
0 An unexpected error response. -
- */ - public okhttp3.Call recordServiceTokenizeAsync(String vaultID, V1TokenizePayload tokenizePayload, final ApiCallback _callback) throws ApiException { - - okhttp3.Call localVarCall = recordServiceTokenizeValidateBeforeCall(vaultID, tokenizePayload, _callback); - Type localVarReturnType = new TypeToken(){}.getType(); - localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); - return localVarCall; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java b/src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java deleted file mode 100644 index 79949c2b..00000000 --- a/src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.auth; - -import com.skyflow.generated.rest.ApiException; -import com.skyflow.generated.rest.Pair; - -import java.net.URI; -import java.util.Map; -import java.util.List; - -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.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/src/main/java/com/skyflow/generated/rest/auth/Authentication.java b/src/main/java/com/skyflow/generated/rest/auth/Authentication.java deleted file mode 100644 index 219caa17..00000000 --- a/src/main/java/com/skyflow/generated/rest/auth/Authentication.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.auth; - -import com.skyflow.generated.rest.Pair; -import com.skyflow.generated.rest.ApiException; - -import java.net.URI; -import java.util.Map; -import java.util.List; - -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/src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java b/src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java deleted file mode 100644 index 5bf3124a..00000000 --- a/src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.auth; - -import com.skyflow.generated.rest.Pair; -import com.skyflow.generated.rest.ApiException; - -import okhttp3.Credentials; - -import java.net.URI; -import java.util.Map; -import java.util.List; - -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/src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java b/src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java deleted file mode 100644 index e8797964..00000000 --- a/src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.auth; - -import com.skyflow.generated.rest.ApiException; -import com.skyflow.generated.rest.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", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.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; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/core/ApiClientApiException.java b/src/main/java/com/skyflow/generated/rest/core/ApiClientApiException.java new file mode 100644 index 00000000..a4487b1e --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ApiClientApiException.java @@ -0,0 +1,73 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import okhttp3.Response; + +/** + * This exception type will be thrown for any non-2XX API responses. + */ +public class ApiClientApiException extends ApiClientException { + /** + * The error code of the response that triggered the exception. + */ + private final int statusCode; + + /** + * The body of the response that triggered the exception. + */ + private final Object body; + + private final Map> headers; + + public ApiClientApiException(String message, int statusCode, Object body) { + super(message); + this.statusCode = statusCode; + this.body = body; + this.headers = new HashMap<>(); + } + + public ApiClientApiException(String message, int statusCode, Object body, Response rawResponse) { + super(message); + this.statusCode = statusCode; + this.body = body; + this.headers = new HashMap<>(); + rawResponse.headers().forEach(header -> { + String key = header.component1(); + String value = header.component2(); + this.headers.computeIfAbsent(key, _str -> new ArrayList<>()).add(value); + }); + } + + /** + * @return the statusCode + */ + public int statusCode() { + return this.statusCode; + } + + /** + * @return the body + */ + public Object body() { + return this.body; + } + + /** + * @return the headers + */ + public Map> headers() { + return this.headers; + } + + @java.lang.Override + public String toString() { + return "ApiClientApiException{" + "message: " + getMessage() + ", statusCode: " + statusCode + ", body: " + body + + "}"; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/ApiClientException.java b/src/main/java/com/skyflow/generated/rest/core/ApiClientException.java new file mode 100644 index 00000000..7987eba6 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ApiClientException.java @@ -0,0 +1,17 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +/** + * This class serves as the base exception for all errors in the SDK. + */ +public class ApiClientException extends RuntimeException { + public ApiClientException(String message) { + super(message); + } + + public ApiClientException(String message, Exception e) { + super(message, e); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/ApiClientHttpResponse.java b/src/main/java/com/skyflow/generated/rest/core/ApiClientHttpResponse.java new file mode 100644 index 00000000..9c81f1f5 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ApiClientHttpResponse.java @@ -0,0 +1,37 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import okhttp3.Response; + +public final class ApiClientHttpResponse { + + private final T body; + + private final Map> headers; + + public ApiClientHttpResponse(T body, Response rawResponse) { + this.body = body; + + Map> headers = new HashMap<>(); + rawResponse.headers().forEach(header -> { + String key = header.component1(); + String value = header.component2(); + headers.computeIfAbsent(key, _str -> new ArrayList<>()).add(value); + }); + this.headers = headers; + } + + public T body() { + return this.body; + } + + public Map> headers() { + return headers; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java b/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java new file mode 100644 index 00000000..badaddd3 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java @@ -0,0 +1,170 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import okhttp3.OkHttpClient; + +public final class ClientOptions { + private final Environment environment; + + private final Map headers; + + private final Map> headerSuppliers; + + private final OkHttpClient httpClient; + + private final int timeout; + + private ClientOptions( + Environment environment, + Map headers, + Map> headerSuppliers, + OkHttpClient httpClient, + int timeout) { + this.environment = environment; + this.headers = new HashMap<>(); + this.headers.putAll(headers); + this.headers.putAll(new HashMap() { + { + put("X-Fern-Language", "JAVA"); + put("X-Fern-SDK-Name", "com.skyflow.fern:api-sdk"); + put("X-Fern-SDK-Version", "0.0.219"); + } + }); + this.headerSuppliers = headerSuppliers; + this.httpClient = httpClient; + this.timeout = timeout; + } + + public Environment environment() { + return this.environment; + } + + public Map headers(RequestOptions requestOptions) { + Map values = new HashMap<>(this.headers); + headerSuppliers.forEach((key, supplier) -> { + values.put(key, supplier.get()); + }); + if (requestOptions != null) { + values.putAll(requestOptions.getHeaders()); + } + return values; + } + + public int timeout(RequestOptions requestOptions) { + if (requestOptions == null) { + return this.timeout; + } + return requestOptions.getTimeout().orElse(this.timeout); + } + + public OkHttpClient httpClient() { + return this.httpClient; + } + + public OkHttpClient httpClientWithTimeout(RequestOptions requestOptions) { + if (requestOptions == null) { + return this.httpClient; + } + return this.httpClient + .newBuilder() + .callTimeout(requestOptions.getTimeout().get(), requestOptions.getTimeoutTimeUnit()) + .connectTimeout(0, TimeUnit.SECONDS) + .writeTimeout(0, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.SECONDS) + .build(); + } + + public static Builder builder() { + return new Builder(); + } + + public static final class Builder { + private Environment environment; + + private final Map headers = new HashMap<>(); + + private final Map> headerSuppliers = new HashMap<>(); + + private int maxRetries = 2; + + private Optional timeout = Optional.empty(); + + private OkHttpClient httpClient = null; + + public Builder environment(Environment environment) { + this.environment = environment; + return this; + } + + public Builder addHeader(String key, String value) { + this.headers.put(key, value); + return this; + } + + public Builder addHeader(String key, Supplier value) { + this.headerSuppliers.put(key, value); + return this; + } + + /** + * Override the timeout in seconds. Defaults to 60 seconds. + */ + public Builder timeout(int timeout) { + this.timeout = Optional.of(timeout); + return this; + } + + /** + * Override the timeout in seconds. Defaults to 60 seconds. + */ + public Builder timeout(Optional timeout) { + this.timeout = timeout; + return this; + } + + /** + * Override the maximum number of retries. Defaults to 2 retries. + */ + public Builder maxRetries(int maxRetries) { + this.maxRetries = maxRetries; + return this; + } + + public Builder httpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + public ClientOptions build() { + OkHttpClient.Builder httpClientBuilder = + this.httpClient != null ? this.httpClient.newBuilder() : new OkHttpClient.Builder(); + + if (this.httpClient != null) { + timeout.ifPresent(timeout -> httpClientBuilder + .callTimeout(timeout, TimeUnit.SECONDS) + .connectTimeout(0, TimeUnit.SECONDS) + .writeTimeout(0, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.SECONDS)); + } else { + httpClientBuilder + .callTimeout(this.timeout.orElse(60), TimeUnit.SECONDS) + .connectTimeout(0, TimeUnit.SECONDS) + .writeTimeout(0, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.SECONDS) + .addInterceptor(new RetryInterceptor(this.maxRetries)); + } + + this.httpClient = httpClientBuilder.build(); + this.timeout = Optional.of(httpClient.callTimeoutMillis() / 1000); + + return new ClientOptions(environment, headers, headerSuppliers, httpClient, this.timeout.get()); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/DateTimeDeserializer.java b/src/main/java/com/skyflow/generated/rest/core/DateTimeDeserializer.java new file mode 100644 index 00000000..6be10979 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/DateTimeDeserializer.java @@ -0,0 +1,55 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.module.SimpleModule; +import java.io.IOException; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.TemporalAccessor; +import java.time.temporal.TemporalQueries; + +/** + * Custom deserializer that handles converting ISO8601 dates into {@link OffsetDateTime} objects. + */ +class DateTimeDeserializer extends JsonDeserializer { + private static final SimpleModule MODULE; + + static { + MODULE = new SimpleModule().addDeserializer(OffsetDateTime.class, new DateTimeDeserializer()); + } + + /** + * Gets a module wrapping this deserializer as an adapter for the Jackson ObjectMapper. + * + * @return A {@link SimpleModule} to be plugged onto Jackson ObjectMapper. + */ + public static SimpleModule getModule() { + return MODULE; + } + + @Override + public OffsetDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException { + JsonToken token = parser.currentToken(); + if (token == JsonToken.VALUE_NUMBER_INT) { + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(parser.getValueAsLong()), ZoneOffset.UTC); + } else { + TemporalAccessor temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest( + parser.getValueAsString(), OffsetDateTime::from, LocalDateTime::from); + + if (temporal.query(TemporalQueries.offset()) == null) { + return LocalDateTime.from(temporal).atOffset(ZoneOffset.UTC); + } else { + return OffsetDateTime.from(temporal); + } + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/Environment.java b/src/main/java/com/skyflow/generated/rest/core/Environment.java new file mode 100644 index 00000000..c0adb233 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/Environment.java @@ -0,0 +1,24 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +public final class Environment { + public static final Environment PRODUCTION = new Environment("https://identifier.vault.skyflowapis.com"); + + public static final Environment SANDBOX = new Environment("https://identifier.vault.skyflowapis-preview.com"); + + private final String url; + + private Environment(String url) { + this.url = url; + } + + public String getUrl() { + return this.url; + } + + public static Environment custom(String url) { + return new Environment(url); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/FileStream.java b/src/main/java/com/skyflow/generated/rest/core/FileStream.java new file mode 100644 index 00000000..6b459431 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/FileStream.java @@ -0,0 +1,60 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.InputStream; +import java.util.Objects; +import okhttp3.MediaType; +import okhttp3.RequestBody; +import org.jetbrains.annotations.Nullable; + +/** + * Represents a file stream with associated metadata for file uploads. + */ +public class FileStream { + private final InputStream inputStream; + private final String fileName; + private final MediaType contentType; + + /** + * Constructs a FileStream with the given input stream and optional metadata. + * + * @param inputStream The input stream of the file content. Must not be null. + * @param fileName The name of the file, or null if unknown. + * @param contentType The MIME type of the file content, or null if unknown. + * @throws NullPointerException if inputStream is null + */ + public FileStream(InputStream inputStream, @Nullable String fileName, @Nullable MediaType contentType) { + this.inputStream = Objects.requireNonNull(inputStream, "Input stream cannot be null"); + this.fileName = fileName; + this.contentType = contentType; + } + + public FileStream(InputStream inputStream) { + this(inputStream, null, null); + } + + public InputStream getInputStream() { + return inputStream; + } + + @Nullable + public String getFileName() { + return fileName; + } + + @Nullable + public MediaType getContentType() { + return contentType; + } + + /** + * Creates a RequestBody suitable for use with OkHttp client. + * + * @return A RequestBody instance representing this file stream. + */ + public RequestBody toRequestBody() { + return new InputStreamRequestBody(contentType, inputStream); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/InputStreamRequestBody.java b/src/main/java/com/skyflow/generated/rest/core/InputStreamRequestBody.java new file mode 100644 index 00000000..545f6088 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/InputStreamRequestBody.java @@ -0,0 +1,79 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Objects; +import okhttp3.MediaType; +import okhttp3.RequestBody; +import okhttp3.internal.Util; +import okio.BufferedSink; +import okio.Okio; +import okio.Source; +import org.jetbrains.annotations.Nullable; + +/** + * A custom implementation of OkHttp's RequestBody that wraps an InputStream. + * This class allows streaming of data from an InputStream directly to an HTTP request body, + * which is useful for file uploads or sending large amounts of data without loading it all into memory. + */ +public class InputStreamRequestBody extends RequestBody { + private final InputStream inputStream; + private final MediaType contentType; + + /** + * Constructs an InputStreamRequestBody with the specified content type and input stream. + * + * @param contentType the MediaType of the content, or null if not known + * @param inputStream the InputStream containing the data to be sent + * @throws NullPointerException if inputStream is null + */ + public InputStreamRequestBody(@Nullable MediaType contentType, InputStream inputStream) { + this.contentType = contentType; + this.inputStream = Objects.requireNonNull(inputStream, "inputStream == null"); + } + + /** + * Returns the content type of this request body. + * + * @return the MediaType of the content, or null if not specified + */ + @Nullable + @Override + public MediaType contentType() { + return contentType; + } + + /** + * Returns the content length of this request body, if known. + * This method attempts to determine the length using the InputStream's available() method, + * which may not always accurately reflect the total length of the stream. + * + * @return the content length, or -1 if the length is unknown + * @throws IOException if an I/O error occurs + */ + @Override + public long contentLength() throws IOException { + return inputStream.available() == 0 ? -1 : inputStream.available(); + } + + /** + * Writes the content of the InputStream to the given BufferedSink. + * This method is responsible for transferring the data from the InputStream to the network request. + * + * @param sink the BufferedSink to write the content to + * @throws IOException if an I/O error occurs during writing + */ + @Override + public void writeTo(BufferedSink sink) throws IOException { + Source source = null; + try { + source = Okio.source(inputStream); + sink.writeAll(source); + } finally { + Util.closeQuietly(Objects.requireNonNull(source)); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/MediaTypes.java b/src/main/java/com/skyflow/generated/rest/core/MediaTypes.java new file mode 100644 index 00000000..11714cb8 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/MediaTypes.java @@ -0,0 +1,13 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import okhttp3.MediaType; + +public final class MediaTypes { + + public static final MediaType APPLICATION_JSON = MediaType.parse("application/json"); + + private MediaTypes() {} +} diff --git a/src/main/java/com/skyflow/generated/rest/core/Nullable.java b/src/main/java/com/skyflow/generated/rest/core/Nullable.java new file mode 100644 index 00000000..5929c12d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/Nullable.java @@ -0,0 +1,140 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.Optional; +import java.util.function.Function; + +public final class Nullable { + + private final Either, Null> value; + + private Nullable() { + this.value = Either.left(Optional.empty()); + } + + private Nullable(T value) { + if (value == null) { + this.value = Either.right(Null.INSTANCE); + } else { + this.value = Either.left(Optional.of(value)); + } + } + + public static Nullable ofNull() { + return new Nullable<>(null); + } + + public static Nullable of(T value) { + return new Nullable<>(value); + } + + public static Nullable empty() { + return new Nullable<>(); + } + + public static Nullable ofOptional(Optional value) { + if (value.isPresent()) { + return of(value.get()); + } else { + return empty(); + } + } + + public boolean isNull() { + return this.value.isRight(); + } + + public boolean isEmpty() { + return this.value.isLeft() && !this.value.getLeft().isPresent(); + } + + public T get() { + if (this.isNull()) { + return null; + } + + return this.value.getLeft().get(); + } + + public Nullable map(Function mapper) { + if (this.isNull()) { + return Nullable.ofNull(); + } + + return Nullable.ofOptional(this.value.getLeft().map(mapper)); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof Nullable)) { + return false; + } + + if (((Nullable) other).isNull() && this.isNull()) { + return true; + } + + return this.value.getLeft().equals(((Nullable) other).value.getLeft()); + } + + private static final class Either { + private L left = null; + private R right = null; + + private Either(L left, R right) { + if (left != null && right != null) { + throw new IllegalArgumentException("Left and right argument cannot both be non-null."); + } + + if (left == null && right == null) { + throw new IllegalArgumentException("Left and right argument cannot both be null."); + } + + if (left != null) { + this.left = left; + } + + if (right != null) { + this.right = right; + } + } + + public static Either left(L left) { + return new Either<>(left, null); + } + + public static Either right(R right) { + return new Either<>(null, right); + } + + public boolean isLeft() { + return this.left != null; + } + + public boolean isRight() { + return this.right != null; + } + + public L getLeft() { + if (!this.isLeft()) { + throw new IllegalArgumentException("Cannot get left from right Either."); + } + return this.left; + } + + public R getRight() { + if (!this.isRight()) { + throw new IllegalArgumentException("Cannot get right from left Either."); + } + return this.right; + } + } + + private static final class Null { + private static final Null INSTANCE = new Null(); + + private Null() {} + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/NullableNonemptyFilter.java b/src/main/java/com/skyflow/generated/rest/core/NullableNonemptyFilter.java new file mode 100644 index 00000000..98c33be4 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/NullableNonemptyFilter.java @@ -0,0 +1,19 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.Optional; + +public final class NullableNonemptyFilter { + @Override + public boolean equals(Object o) { + boolean isOptionalEmpty = isOptionalEmpty(o); + + return isOptionalEmpty; + } + + private boolean isOptionalEmpty(Object o) { + return o instanceof Optional && !((Optional) o).isPresent(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/ObjectMappers.java b/src/main/java/com/skyflow/generated/rest/core/ObjectMappers.java new file mode 100644 index 00000000..3b7894e0 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ObjectMappers.java @@ -0,0 +1,36 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import java.io.IOException; + +public final class ObjectMappers { + public static final ObjectMapper JSON_MAPPER = JsonMapper.builder() + .addModule(new Jdk8Module()) + .addModule(new JavaTimeModule()) + .addModule(DateTimeDeserializer.getModule()) + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .build(); + + private ObjectMappers() {} + + public static String stringify(Object o) { + try { + return JSON_MAPPER + .setSerializationInclusion(JsonInclude.Include.ALWAYS) + .writerWithDefaultPrettyPrinter() + .writeValueAsString(o); + } catch (IOException e) { + return o.getClass().getName() + "@" + Integer.toHexString(o.hashCode()); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/QueryStringMapper.java b/src/main/java/com/skyflow/generated/rest/core/QueryStringMapper.java new file mode 100644 index 00000000..e9e18fb9 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/QueryStringMapper.java @@ -0,0 +1,142 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import okhttp3.HttpUrl; +import okhttp3.MultipartBody; + +public class QueryStringMapper { + + private static final ObjectMapper MAPPER = ObjectMappers.JSON_MAPPER; + + public static void addQueryParameter(HttpUrl.Builder httpUrl, String key, Object value, boolean arraysAsRepeats) { + JsonNode valueNode = MAPPER.valueToTree(value); + + List> flat; + if (valueNode.isObject()) { + flat = flattenObject((ObjectNode) valueNode, arraysAsRepeats); + } else if (valueNode.isArray()) { + flat = flattenArray((ArrayNode) valueNode, "", arraysAsRepeats); + } else { + if (valueNode.isTextual()) { + httpUrl.addQueryParameter(key, valueNode.textValue()); + } else { + httpUrl.addQueryParameter(key, valueNode.toString()); + } + return; + } + + for (Map.Entry field : flat) { + if (field.getValue().isTextual()) { + httpUrl.addQueryParameter(key + field.getKey(), field.getValue().textValue()); + } else { + httpUrl.addQueryParameter(key + field.getKey(), field.getValue().toString()); + } + } + } + + public static void addFormDataPart( + MultipartBody.Builder multipartBody, String key, Object value, boolean arraysAsRepeats) { + JsonNode valueNode = MAPPER.valueToTree(value); + + List> flat; + if (valueNode.isObject()) { + flat = flattenObject((ObjectNode) valueNode, arraysAsRepeats); + } else if (valueNode.isArray()) { + flat = flattenArray((ArrayNode) valueNode, "", arraysAsRepeats); + } else { + if (valueNode.isTextual()) { + multipartBody.addFormDataPart(key, valueNode.textValue()); + } else { + multipartBody.addFormDataPart(key, valueNode.toString()); + } + return; + } + + for (Map.Entry field : flat) { + if (field.getValue().isTextual()) { + multipartBody.addFormDataPart( + key + field.getKey(), field.getValue().textValue()); + } else { + multipartBody.addFormDataPart( + key + field.getKey(), field.getValue().toString()); + } + } + } + + public static List> flattenObject(ObjectNode object, boolean arraysAsRepeats) { + List> flat = new ArrayList<>(); + + Iterator> fields = object.fields(); + while (fields.hasNext()) { + Map.Entry field = fields.next(); + + String key = "[" + field.getKey() + "]"; + + if (field.getValue().isObject()) { + List> flatField = + flattenObject((ObjectNode) field.getValue(), arraysAsRepeats); + addAll(flat, flatField, key); + } else if (field.getValue().isArray()) { + List> flatField = + flattenArray((ArrayNode) field.getValue(), key, arraysAsRepeats); + addAll(flat, flatField, ""); + } else { + flat.add(new AbstractMap.SimpleEntry<>(key, field.getValue())); + } + } + + return flat; + } + + private static List> flattenArray( + ArrayNode array, String key, boolean arraysAsRepeats) { + List> flat = new ArrayList<>(); + + Iterator elements = array.elements(); + + int index = 0; + while (elements.hasNext()) { + JsonNode element = elements.next(); + + String indexKey = key + "[" + index + "]"; + + if (arraysAsRepeats) { + indexKey = key; + } + + if (element.isObject()) { + List> flatField = flattenObject((ObjectNode) element, arraysAsRepeats); + addAll(flat, flatField, indexKey); + } else if (element.isArray()) { + List> flatField = flattenArray((ArrayNode) element, "", arraysAsRepeats); + addAll(flat, flatField, indexKey); + } else { + flat.add(new AbstractMap.SimpleEntry<>(indexKey, element)); + } + + index++; + } + + return flat; + } + + private static void addAll( + List> target, List> source, String prefix) { + for (Map.Entry entry : source) { + Map.Entry entryToAdd = + new AbstractMap.SimpleEntry<>(prefix + entry.getKey(), entry.getValue()); + target.add(entryToAdd); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/QueryStringMapperTest.java b/src/main/java/com/skyflow/generated/rest/core/QueryStringMapperTest.java new file mode 100644 index 00000000..c5728721 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/QueryStringMapperTest.java @@ -0,0 +1,339 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import okhttp3.HttpUrl; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public final class QueryStringMapperTest { + @Test + public void testObjectWithQuotedString_indexedArrays() { + Map map = new HashMap() { + { + put("hello", "\"world\""); + } + }; + + String expectedQueryString = "withquoted%5Bhello%5D=%22world%22"; + + String actualQueryString = queryString( + new HashMap() { + { + put("withquoted", map); + } + }, + false); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObjectWithQuotedString_arraysAsRepeats() { + Map map = new HashMap() { + { + put("hello", "\"world\""); + } + }; + + String expectedQueryString = "withquoted%5Bhello%5D=%22world%22"; + + String actualQueryString = queryString( + new HashMap() { + { + put("withquoted", map); + } + }, + true); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObject_indexedArrays() { + Map map = new HashMap() { + { + put("foo", "bar"); + put("baz", "qux"); + } + }; + + String expectedQueryString = "metadata%5Bfoo%5D=bar&metadata%5Bbaz%5D=qux"; + + String actualQueryString = queryString( + new HashMap() { + { + put("metadata", map); + } + }, + false); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObject_arraysAsRepeats() { + Map map = new HashMap() { + { + put("foo", "bar"); + put("baz", "qux"); + } + }; + + String expectedQueryString = "metadata%5Bfoo%5D=bar&metadata%5Bbaz%5D=qux"; + + String actualQueryString = queryString( + new HashMap() { + { + put("metadata", map); + } + }, + true); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testNestedObject_indexedArrays() { + Map> nestedMap = new HashMap>() { + { + put("mapkey1", new HashMap() { + { + put("mapkey1mapkey1", "mapkey1mapkey1value"); + put("mapkey1mapkey2", "mapkey1mapkey2value"); + } + }); + put("mapkey2", new HashMap() { + { + put("mapkey2mapkey1", "mapkey2mapkey1value"); + } + }); + } + }; + + String expectedQueryString = + "nested%5Bmapkey2%5D%5Bmapkey2mapkey1%5D=mapkey2mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey1" + + "%5D=mapkey1mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey2%5D=mapkey1mapkey2value"; + + String actualQueryString = queryString( + new HashMap() { + { + put("nested", nestedMap); + } + }, + false); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testNestedObject_arraysAsRepeats() { + Map> nestedMap = new HashMap>() { + { + put("mapkey1", new HashMap() { + { + put("mapkey1mapkey1", "mapkey1mapkey1value"); + put("mapkey1mapkey2", "mapkey1mapkey2value"); + } + }); + put("mapkey2", new HashMap() { + { + put("mapkey2mapkey1", "mapkey2mapkey1value"); + } + }); + } + }; + + String expectedQueryString = + "nested%5Bmapkey2%5D%5Bmapkey2mapkey1%5D=mapkey2mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey1" + + "%5D=mapkey1mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey2%5D=mapkey1mapkey2value"; + + String actualQueryString = queryString( + new HashMap() { + { + put("nested", nestedMap); + } + }, + true); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testDateTime_indexedArrays() { + OffsetDateTime dateTime = + OffsetDateTime.ofInstant(Instant.ofEpochSecond(1740412107L), ZoneId.of("America/New_York")); + + String expectedQueryString = "datetime=2025-02-24T10%3A48%3A27-05%3A00"; + + String actualQueryString = queryString( + new HashMap() { + { + put("datetime", dateTime); + } + }, + false); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testDateTime_arraysAsRepeats() { + OffsetDateTime dateTime = + OffsetDateTime.ofInstant(Instant.ofEpochSecond(1740412107L), ZoneId.of("America/New_York")); + + String expectedQueryString = "datetime=2025-02-24T10%3A48%3A27-05%3A00"; + + String actualQueryString = queryString( + new HashMap() { + { + put("datetime", dateTime); + } + }, + true); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObjectArray_indexedArrays() { + List> mapArray = new ArrayList>() { + { + add(new HashMap() { + { + put("key", "hello"); + put("value", "world"); + } + }); + add(new HashMap() { + { + put("key", "foo"); + put("value", "bar"); + } + }); + add(new HashMap<>()); + } + }; + + String expectedQueryString = "objects%5B0%5D%5Bvalue%5D=world&objects%5B0%5D%5Bkey%5D=hello&objects%5B1%5D" + + "%5Bvalue%5D=bar&objects%5B1%5D%5Bkey%5D=foo"; + + String actualQueryString = queryString( + new HashMap() { + { + put("objects", mapArray); + } + }, + false); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObjectArray_arraysAsRepeats() { + List> mapArray = new ArrayList>() { + { + add(new HashMap() { + { + put("key", "hello"); + put("value", "world"); + } + }); + add(new HashMap() { + { + put("key", "foo"); + put("value", "bar"); + } + }); + add(new HashMap<>()); + } + }; + + String expectedQueryString = + "objects%5Bvalue%5D=world&objects%5Bkey%5D=hello&objects%5Bvalue" + "%5D=bar&objects%5Bkey%5D=foo"; + + String actualQueryString = queryString( + new HashMap() { + { + put("objects", mapArray); + } + }, + true); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObjectWithArray_indexedArrays() { + Map objectWithArray = new HashMap() { + { + put("id", "abc123"); + put("contactIds", new ArrayList() { + { + add("id1"); + add("id2"); + add("id3"); + } + }); + } + }; + + String expectedQueryString = + "objectwitharray%5Bid%5D=abc123&objectwitharray%5BcontactIds%5D%5B0%5D=id1&objectwitharray" + + "%5BcontactIds%5D%5B1%5D=id2&objectwitharray%5BcontactIds%5D%5B2%5D=id3"; + + String actualQueryString = queryString( + new HashMap() { + { + put("objectwitharray", objectWithArray); + } + }, + false); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + @Test + public void testObjectWithArray_arraysAsRepeats() { + Map objectWithArray = new HashMap() { + { + put("id", "abc123"); + put("contactIds", new ArrayList() { + { + add("id1"); + add("id2"); + add("id3"); + } + }); + } + }; + + String expectedQueryString = "objectwitharray%5Bid%5D=abc123&objectwitharray%5BcontactIds" + + "%5D=id1&objectwitharray%5BcontactIds%5D=id2&objectwitharray%5BcontactIds%5D=id3"; + + String actualQueryString = queryString( + new HashMap() { + { + put("objectwitharray", objectWithArray); + } + }, + true); + + Assertions.assertEquals(expectedQueryString, actualQueryString); + } + + private static String queryString(Map params, boolean arraysAsRepeats) { + HttpUrl.Builder httpUrl = HttpUrl.parse("http://www.fakewebsite.com/").newBuilder(); + params.forEach((paramName, paramValue) -> + QueryStringMapper.addQueryParameter(httpUrl, paramName, paramValue, arraysAsRepeats)); + return httpUrl.build().encodedQuery(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/RequestOptions.java b/src/main/java/com/skyflow/generated/rest/core/RequestOptions.java new file mode 100644 index 00000000..edc6d0ae --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/RequestOptions.java @@ -0,0 +1,101 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +public final class RequestOptions { + private final String token; + + private final Optional timeout; + + private final TimeUnit timeoutTimeUnit; + + private final Map headers; + + private final Map> headerSuppliers; + + private RequestOptions( + String token, + Optional timeout, + TimeUnit timeoutTimeUnit, + Map headers, + Map> headerSuppliers) { + this.token = token; + this.timeout = timeout; + this.timeoutTimeUnit = timeoutTimeUnit; + this.headers = headers; + this.headerSuppliers = headerSuppliers; + } + + public Optional getTimeout() { + return timeout; + } + + public TimeUnit getTimeoutTimeUnit() { + return timeoutTimeUnit; + } + + public Map getHeaders() { + Map headers = new HashMap<>(); + if (this.token != null) { + headers.put("Authorization", "Bearer " + this.token); + } + headers.putAll(this.headers); + this.headerSuppliers.forEach((key, supplier) -> { + headers.put(key, supplier.get()); + }); + return headers; + } + + public static Builder builder() { + return new Builder(); + } + + public static final class Builder { + private String token = null; + + private Optional timeout = Optional.empty(); + + private TimeUnit timeoutTimeUnit = TimeUnit.SECONDS; + + private final Map headers = new HashMap<>(); + + private final Map> headerSuppliers = new HashMap<>(); + + public Builder token(String token) { + this.token = token; + return this; + } + + public Builder timeout(Integer timeout) { + this.timeout = Optional.of(timeout); + return this; + } + + public Builder timeout(Integer timeout, TimeUnit timeoutTimeUnit) { + this.timeout = Optional.of(timeout); + this.timeoutTimeUnit = timeoutTimeUnit; + return this; + } + + public Builder addHeader(String key, String value) { + this.headers.put(key, value); + return this; + } + + public Builder addHeader(String key, Supplier value) { + this.headerSuppliers.put(key, value); + return this; + } + + public RequestOptions build() { + return new RequestOptions(token, timeout, timeoutTimeUnit, headers, headerSuppliers); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/ResponseBodyInputStream.java b/src/main/java/com/skyflow/generated/rest/core/ResponseBodyInputStream.java new file mode 100644 index 00000000..d8df7715 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ResponseBodyInputStream.java @@ -0,0 +1,45 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.FilterInputStream; +import java.io.IOException; +import okhttp3.Response; + +/** + * A custom InputStream that wraps the InputStream from the OkHttp Response and ensures that the + * OkHttp Response object is properly closed when the stream is closed. + * + * This class extends FilterInputStream and takes an OkHttp Response object as a parameter. + * It retrieves the InputStream from the Response and overrides the close method to close + * both the InputStream and the Response object, ensuring proper resource management and preventing + * premature closure of the underlying HTTP connection. + */ +public class ResponseBodyInputStream extends FilterInputStream { + private final Response response; + + /** + * Constructs a ResponseBodyInputStream that wraps the InputStream from the given OkHttp + * Response object. + * + * @param response the OkHttp Response object from which the InputStream is retrieved + * @throws IOException if an I/O error occurs while retrieving the InputStream + */ + public ResponseBodyInputStream(Response response) throws IOException { + super(response.body().byteStream()); + this.response = response; + } + + /** + * Closes the InputStream and the associated OkHttp Response object. This ensures that the + * underlying HTTP connection is properly closed after the stream is no longer needed. + * + * @throws IOException if an I/O error occurs + */ + @Override + public void close() throws IOException { + super.close(); + response.close(); // Ensure the response is closed when the stream is closed + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/ResponseBodyReader.java b/src/main/java/com/skyflow/generated/rest/core/ResponseBodyReader.java new file mode 100644 index 00000000..ed894407 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ResponseBodyReader.java @@ -0,0 +1,44 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.FilterReader; +import java.io.IOException; +import okhttp3.Response; + +/** + * A custom Reader that wraps the Reader from the OkHttp Response and ensures that the + * OkHttp Response object is properly closed when the reader is closed. + * + * This class extends FilterReader and takes an OkHttp Response object as a parameter. + * It retrieves the Reader from the Response and overrides the close method to close + * both the Reader and the Response object, ensuring proper resource management and preventing + * premature closure of the underlying HTTP connection. + */ +public class ResponseBodyReader extends FilterReader { + private final Response response; + + /** + * Constructs a ResponseBodyReader that wraps the Reader from the given OkHttp Response object. + * + * @param response the OkHttp Response object from which the Reader is retrieved + * @throws IOException if an I/O error occurs while retrieving the Reader + */ + public ResponseBodyReader(Response response) throws IOException { + super(response.body().charStream()); + this.response = response; + } + + /** + * Closes the Reader and the associated OkHttp Response object. This ensures that the + * underlying HTTP connection is properly closed after the reader is no longer needed. + * + * @throws IOException if an I/O error occurs + */ + @Override + public void close() throws IOException { + super.close(); + response.close(); // Ensure the response is closed when the reader is closed + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/RetryInterceptor.java b/src/main/java/com/skyflow/generated/rest/core/RetryInterceptor.java new file mode 100644 index 00000000..eda7d265 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/RetryInterceptor.java @@ -0,0 +1,78 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.IOException; +import java.time.Duration; +import java.util.Optional; +import java.util.Random; +import okhttp3.Interceptor; +import okhttp3.Response; + +public class RetryInterceptor implements Interceptor { + + private static final Duration ONE_SECOND = Duration.ofSeconds(1); + private final ExponentialBackoff backoff; + private final Random random = new Random(); + + public RetryInterceptor(int maxRetries) { + this.backoff = new ExponentialBackoff(maxRetries); + } + + @Override + public Response intercept(Chain chain) throws IOException { + Response response = chain.proceed(chain.request()); + + if (shouldRetry(response.code())) { + return retryChain(response, chain); + } + + return response; + } + + private Response retryChain(Response response, Chain chain) throws IOException { + Optional nextBackoff = this.backoff.nextBackoff(); + while (nextBackoff.isPresent()) { + try { + Thread.sleep(nextBackoff.get().toMillis()); + } catch (InterruptedException e) { + throw new IOException("Interrupted while trying request", e); + } + response.close(); + response = chain.proceed(chain.request()); + if (shouldRetry(response.code())) { + nextBackoff = this.backoff.nextBackoff(); + } else { + return response; + } + } + + return response; + } + + private static boolean shouldRetry(int statusCode) { + return statusCode == 408 || statusCode == 429 || statusCode >= 500; + } + + private final class ExponentialBackoff { + + private final int maxNumRetries; + + private int retryNumber = 0; + + ExponentialBackoff(int maxNumRetries) { + this.maxNumRetries = maxNumRetries; + } + + public Optional nextBackoff() { + retryNumber += 1; + if (retryNumber > maxNumRetries) { + return Optional.empty(); + } + + int upperBound = (int) Math.pow(2, retryNumber); + return Optional.of(ONE_SECOND.multipliedBy(random.nextInt(upperBound))); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/Stream.java b/src/main/java/com/skyflow/generated/rest/core/Stream.java new file mode 100644 index 00000000..f037712a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/Stream.java @@ -0,0 +1,97 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.Reader; +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.Scanner; + +/** + * The {@code Stream} class implements {@link Iterable} to provide a simple mechanism for reading and parsing + * objects of a given type from data streamed via a {@link Reader} using a specified delimiter. + *

+ * {@code Stream} assumes that data is being pushed to the provided {@link Reader} asynchronously and utilizes a + * {@code Scanner} to block during iteration if the next object is not available. + * + * @param The type of objects in the stream. + */ +public final class Stream implements Iterable { + /** + * The {@link Class} of the objects in the stream. + */ + private final Class valueType; + /** + * The {@link Scanner} used for reading from the input stream and blocking when needed during iteration. + */ + private final Scanner scanner; + + /** + * Constructs a new {@code Stream} with the specified value type, reader, and delimiter. + * + * @param valueType The class of the objects in the stream. + * @param reader The reader that provides the streamed data. + * @param delimiter The delimiter used to separate elements in the stream. + */ + public Stream(Class valueType, Reader reader, String delimiter) { + this.scanner = new Scanner(reader).useDelimiter(delimiter); + this.valueType = valueType; + } + + /** + * Returns an iterator over the elements in this stream that blocks during iteration when the next object is + * not yet available. + * + * @return An iterator that can be used to traverse the elements in the stream. + */ + @Override + public Iterator iterator() { + return new Iterator() { + /** + * Returns {@code true} if there are more elements in the stream. + *

+ * Will block and wait for input if the stream has not ended and the next object is not yet available. + * + * @return {@code true} if there are more elements, {@code false} otherwise. + */ + @Override + public boolean hasNext() { + return scanner.hasNext(); + } + + /** + * Returns the next element in the stream. + *

+ * Will block and wait for input if the stream has not ended and the next object is not yet available. + * + * @return The next element in the stream. + * @throws NoSuchElementException If there are no more elements in the stream. + */ + @Override + public T next() { + if (!scanner.hasNext()) { + throw new NoSuchElementException(); + } else { + try { + T parsedResponse = ObjectMappers.JSON_MAPPER.readValue( + scanner.next().trim(), valueType); + return parsedResponse; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + /** + * Removing elements from {@code Stream} is not supported. + * + * @throws UnsupportedOperationException Always, as removal is not supported. + */ + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/Suppliers.java b/src/main/java/com/skyflow/generated/rest/core/Suppliers.java new file mode 100644 index 00000000..307d5852 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/Suppliers.java @@ -0,0 +1,23 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; + +public final class Suppliers { + private Suppliers() {} + + public static Supplier memoize(Supplier delegate) { + AtomicReference value = new AtomicReference<>(); + return () -> { + T val = value.get(); + if (val == null) { + val = value.updateAndGet(cur -> cur == null ? Objects.requireNonNull(delegate.get()) : cur); + } + return val; + }; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/errors/BadRequestError.java b/src/main/java/com/skyflow/generated/rest/errors/BadRequestError.java new file mode 100644 index 00000000..c8d4bb99 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/errors/BadRequestError.java @@ -0,0 +1,32 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.errors; + +import com.skyflow.generated.rest.core.ApiClientApiException; +import okhttp3.Response; + +public final class BadRequestError extends ApiClientApiException { + /** + * The body of the response that triggered the exception. + */ + private final Object body; + + public BadRequestError(Object body) { + super("BadRequestError", 400, body); + this.body = body; + } + + public BadRequestError(Object body, Response rawResponse) { + super("BadRequestError", 400, body, rawResponse); + this.body = body; + } + + /** + * @return the body + */ + @java.lang.Override + public Object body() { + return this.body; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/errors/InternalServerError.java b/src/main/java/com/skyflow/generated/rest/errors/InternalServerError.java new file mode 100644 index 00000000..d29f2b82 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/errors/InternalServerError.java @@ -0,0 +1,33 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.errors; + +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.types.ErrorResponse; +import okhttp3.Response; + +public final class InternalServerError extends ApiClientApiException { + /** + * The body of the response that triggered the exception. + */ + private final ErrorResponse body; + + public InternalServerError(ErrorResponse body) { + super("InternalServerError", 500, body); + this.body = body; + } + + public InternalServerError(ErrorResponse body, Response rawResponse) { + super("InternalServerError", 500, body, rawResponse); + this.body = body; + } + + /** + * @return the body + */ + @java.lang.Override + public ErrorResponse body() { + return this.body; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/errors/NotFoundError.java b/src/main/java/com/skyflow/generated/rest/errors/NotFoundError.java new file mode 100644 index 00000000..efa94aad --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/errors/NotFoundError.java @@ -0,0 +1,32 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.errors; + +import com.skyflow.generated.rest.core.ApiClientApiException; +import okhttp3.Response; + +public final class NotFoundError extends ApiClientApiException { + /** + * The body of the response that triggered the exception. + */ + private final Object body; + + public NotFoundError(Object body) { + super("NotFoundError", 404, body); + this.body = body; + } + + public NotFoundError(Object body, Response rawResponse) { + super("NotFoundError", 404, body, rawResponse); + this.body = body; + } + + /** + * @return the body + */ + @java.lang.Override + public Object body() { + return this.body; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/errors/UnauthorizedError.java b/src/main/java/com/skyflow/generated/rest/errors/UnauthorizedError.java new file mode 100644 index 00000000..3b6d6ae1 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/errors/UnauthorizedError.java @@ -0,0 +1,32 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.errors; + +import com.skyflow.generated.rest.core.ApiClientApiException; +import okhttp3.Response; + +public final class UnauthorizedError extends ApiClientApiException { + /** + * The body of the response that triggered the exception. + */ + private final Object body; + + public UnauthorizedError(Object body) { + super("UnauthorizedError", 401, body); + this.body = body; + } + + public UnauthorizedError(Object body, Response rawResponse) { + super("UnauthorizedError", 401, body, rawResponse); + this.body = body; + } + + /** + * @return the body + */ + @java.lang.Override + public Object body() { + return this.body; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java b/src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java deleted file mode 100644 index c506e085..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.

  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import com.skyflow.generated.rest.ApiException; -import java.util.Objects; -import java.lang.reflect.Type; -import java.util.Map; - -/** - * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public abstract class AbstractOpenApiSchema { - - // store the actual instance of the schema/object - private Object instance; - - // is nullable - private Boolean isNullable; - - // schema type (e.g. oneOf, anyOf) - private final String schemaType; - - public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { - this.schemaType = schemaType; - this.isNullable = isNullable; - } - - /** - * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object - * - * @return an instance of the actual schema/object - */ - public abstract Map> getSchemas(); - - /** - * Get the actual instance - * - * @return an instance of the actual schema/object - */ - //@JsonValue - public Object getActualInstance() {return instance;} - - /** - * Set the actual instance - * - * @param instance the actual instance of the schema/object - */ - public void setActualInstance(Object instance) {this.instance = instance;} - - /** - * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well - * - * @return an instance of the actual schema/object - */ - public Object getActualInstanceRecursively() { - return getActualInstanceRecursively(this); - } - - private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { - if (object.getActualInstance() == null) { - return null; - } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { - return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); - } else { - return object.getActualInstance(); - } - } - - /** - * Get the schema type (e.g. anyOf, oneOf) - * - * @return the schema type - */ - public String getSchemaType() { - return schemaType; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ").append(getClass()).append(" {\n"); - sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); - sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); - sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; - return Objects.equals(this.instance, a.instance) && - Objects.equals(this.isNullable, a.isNullable) && - Objects.equals(this.schemaType, a.schemaType); - } - - @Override - public int hashCode() { - return Objects.hash(instance, isNullable, schemaType); - } - - /** - * Is nullable - * - * @return true if it's nullable - */ - public Boolean isNullable() { - if (Boolean.TRUE.equals(isNullable)) { - return Boolean.TRUE; - } else { - return Boolean.FALSE; - } - } - - - -} diff --git a/src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java b/src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java deleted file mode 100644 index ee029542..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Type of the resource. - */ -@JsonAdapter(AuditEventAuditResourceType.Adapter.class) -public enum AuditEventAuditResourceType { - - NONE_API("NONE_API"), - - ACCOUNT("ACCOUNT"), - - AUDIT("AUDIT"), - - BASE_DATA_TYPE("BASE_DATA_TYPE"), - - FIELD_TEMPLATE("FIELD_TEMPLATE"), - - FILE("FILE"), - - KEY("KEY"), - - POLICY("POLICY"), - - PROTO_PARSE("PROTO_PARSE"), - - RECORD("RECORD"), - - ROLE("ROLE"), - - RULE("RULE"), - - SECRET("SECRET"), - - SERVICE_ACCOUNT("SERVICE_ACCOUNT"), - - TOKEN("TOKEN"), - - USER("USER"), - - VAULT("VAULT"), - - VAULT_TEMPLATE("VAULT_TEMPLATE"), - - WORKSPACE("WORKSPACE"), - - TABLE("TABLE"), - - POLICY_TEMPLATE("POLICY_TEMPLATE"), - - MEMBER("MEMBER"), - - TAG("TAG"), - - CONNECTION("CONNECTION"), - - MIGRATION("MIGRATION"), - - SCHEDULED_JOB("SCHEDULED_JOB"), - - JOB("JOB"), - - COLUMN_NAME("COLUMN_NAME"), - - NETWORK_TOKEN("NETWORK_TOKEN"), - - SUBSCRIPTION("SUBSCRIPTION"); - - private String value; - - AuditEventAuditResourceType(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static AuditEventAuditResourceType fromValue(String value) { - for (AuditEventAuditResourceType b : AuditEventAuditResourceType.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final AuditEventAuditResourceType enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public AuditEventAuditResourceType read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return AuditEventAuditResourceType.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - AuditEventAuditResourceType.fromValue(value); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java b/src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java deleted file mode 100644 index 5732e155..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java +++ /dev/null @@ -1,530 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.ContextAccessType; -import com.skyflow.generated.rest.models.ContextAuthMode; -import com.skyflow.generated.rest.models.V1MemberType; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * Context for an audit event. - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class AuditEventContext { - public static final String SERIALIZED_NAME_CHANGE_I_D = "changeID"; - @SerializedName(SERIALIZED_NAME_CHANGE_I_D) - private String changeID; - - public static final String SERIALIZED_NAME_REQUEST_I_D = "requestID"; - @SerializedName(SERIALIZED_NAME_REQUEST_I_D) - private String requestID; - - public static final String SERIALIZED_NAME_TRACE_I_D = "traceID"; - @SerializedName(SERIALIZED_NAME_TRACE_I_D) - private String traceID; - - public static final String SERIALIZED_NAME_SESSION_I_D = "sessionID"; - @SerializedName(SERIALIZED_NAME_SESSION_I_D) - private String sessionID; - - public static final String SERIALIZED_NAME_ACTOR = "actor"; - @SerializedName(SERIALIZED_NAME_ACTOR) - private String actor; - - public static final String SERIALIZED_NAME_ACTOR_TYPE = "actorType"; - @SerializedName(SERIALIZED_NAME_ACTOR_TYPE) - private V1MemberType actorType = V1MemberType.NONE; - - public static final String SERIALIZED_NAME_ACCESS_TYPE = "accessType"; - @SerializedName(SERIALIZED_NAME_ACCESS_TYPE) - private ContextAccessType accessType = ContextAccessType.ACCESS_NONE; - - public static final String SERIALIZED_NAME_IP_ADDRESS = "ipAddress"; - @SerializedName(SERIALIZED_NAME_IP_ADDRESS) - private String ipAddress; - - public static final String SERIALIZED_NAME_ORIGIN = "origin"; - @SerializedName(SERIALIZED_NAME_ORIGIN) - private String origin; - - public static final String SERIALIZED_NAME_AUTH_MODE = "authMode"; - @SerializedName(SERIALIZED_NAME_AUTH_MODE) - private ContextAuthMode authMode = ContextAuthMode.AUTH_NONE; - - public static final String SERIALIZED_NAME_JWT_I_D = "jwtID"; - @SerializedName(SERIALIZED_NAME_JWT_I_D) - private String jwtID; - - public static final String SERIALIZED_NAME_BEARER_TOKEN_CONTEXT_I_D = "bearerTokenContextID"; - @SerializedName(SERIALIZED_NAME_BEARER_TOKEN_CONTEXT_I_D) - private String bearerTokenContextID; - - public AuditEventContext() { - } - - public AuditEventContext changeID(String changeID) { - this.changeID = changeID; - return this; - } - - /** - * ID for the audit event. - * @return changeID - */ - @javax.annotation.Nullable - public String getChangeID() { - return changeID; - } - - public void setChangeID(String changeID) { - this.changeID = changeID; - } - - - public AuditEventContext requestID(String requestID) { - this.requestID = requestID; - return this; - } - - /** - * ID for the request that caused the event. - * @return requestID - */ - @javax.annotation.Nullable - public String getRequestID() { - return requestID; - } - - public void setRequestID(String requestID) { - this.requestID = requestID; - } - - - public AuditEventContext traceID(String traceID) { - this.traceID = traceID; - return this; - } - - /** - * ID for the request set by the service that received the request. - * @return traceID - */ - @javax.annotation.Nullable - public String getTraceID() { - return traceID; - } - - public void setTraceID(String traceID) { - this.traceID = traceID; - } - - - public AuditEventContext sessionID(String sessionID) { - this.sessionID = sessionID; - return this; - } - - /** - * ID for the session in which the request was sent. - * @return sessionID - */ - @javax.annotation.Nullable - public String getSessionID() { - return sessionID; - } - - public void setSessionID(String sessionID) { - this.sessionID = sessionID; - } - - - public AuditEventContext actor(String actor) { - this.actor = actor; - return this; - } - - /** - * Member who sent the request. Depending on `actorType`, this may be a user ID or a service account ID. - * @return actor - */ - @javax.annotation.Nullable - public String getActor() { - return actor; - } - - public void setActor(String actor) { - this.actor = actor; - } - - - public AuditEventContext actorType(V1MemberType actorType) { - this.actorType = actorType; - return this; - } - - /** - * Get actorType - * @return actorType - */ - @javax.annotation.Nullable - public V1MemberType getActorType() { - return actorType; - } - - public void setActorType(V1MemberType actorType) { - this.actorType = actorType; - } - - - public AuditEventContext accessType(ContextAccessType accessType) { - this.accessType = accessType; - return this; - } - - /** - * Get accessType - * @return accessType - */ - @javax.annotation.Nullable - public ContextAccessType getAccessType() { - return accessType; - } - - public void setAccessType(ContextAccessType accessType) { - this.accessType = accessType; - } - - - public AuditEventContext ipAddress(String ipAddress) { - this.ipAddress = ipAddress; - return this; - } - - /** - * IP Address of the client that made the request. - * @return ipAddress - */ - @javax.annotation.Nullable - public String getIpAddress() { - return ipAddress; - } - - public void setIpAddress(String ipAddress) { - this.ipAddress = ipAddress; - } - - - public AuditEventContext origin(String origin) { - this.origin = origin; - return this; - } - - /** - * HTTP Origin request header (including scheme, hostname, and port) of the request. - * @return origin - */ - @javax.annotation.Nullable - public String getOrigin() { - return origin; - } - - public void setOrigin(String origin) { - this.origin = origin; - } - - - public AuditEventContext authMode(ContextAuthMode authMode) { - this.authMode = authMode; - return this; - } - - /** - * Get authMode - * @return authMode - */ - @javax.annotation.Nullable - public ContextAuthMode getAuthMode() { - return authMode; - } - - public void setAuthMode(ContextAuthMode authMode) { - this.authMode = authMode; - } - - - public AuditEventContext jwtID(String jwtID) { - this.jwtID = jwtID; - return this; - } - - /** - * ID of the JWT token. - * @return jwtID - */ - @javax.annotation.Nullable - public String getJwtID() { - return jwtID; - } - - public void setJwtID(String jwtID) { - this.jwtID = jwtID; - } - - - public AuditEventContext bearerTokenContextID(String bearerTokenContextID) { - this.bearerTokenContextID = bearerTokenContextID; - return this; - } - - /** - * Embedded User Context. - * @return bearerTokenContextID - */ - @javax.annotation.Nullable - public String getBearerTokenContextID() { - return bearerTokenContextID; - } - - public void setBearerTokenContextID(String bearerTokenContextID) { - this.bearerTokenContextID = bearerTokenContextID; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AuditEventContext auditEventContext = (AuditEventContext) o; - return Objects.equals(this.changeID, auditEventContext.changeID) && - Objects.equals(this.requestID, auditEventContext.requestID) && - Objects.equals(this.traceID, auditEventContext.traceID) && - Objects.equals(this.sessionID, auditEventContext.sessionID) && - Objects.equals(this.actor, auditEventContext.actor) && - Objects.equals(this.actorType, auditEventContext.actorType) && - Objects.equals(this.accessType, auditEventContext.accessType) && - Objects.equals(this.ipAddress, auditEventContext.ipAddress) && - Objects.equals(this.origin, auditEventContext.origin) && - Objects.equals(this.authMode, auditEventContext.authMode) && - Objects.equals(this.jwtID, auditEventContext.jwtID) && - Objects.equals(this.bearerTokenContextID, auditEventContext.bearerTokenContextID); - } - - @Override - public int hashCode() { - return Objects.hash(changeID, requestID, traceID, sessionID, actor, actorType, accessType, ipAddress, origin, authMode, jwtID, bearerTokenContextID); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AuditEventContext {\n"); - sb.append(" changeID: ").append(toIndentedString(changeID)).append("\n"); - sb.append(" requestID: ").append(toIndentedString(requestID)).append("\n"); - sb.append(" traceID: ").append(toIndentedString(traceID)).append("\n"); - sb.append(" sessionID: ").append(toIndentedString(sessionID)).append("\n"); - sb.append(" actor: ").append(toIndentedString(actor)).append("\n"); - sb.append(" actorType: ").append(toIndentedString(actorType)).append("\n"); - sb.append(" accessType: ").append(toIndentedString(accessType)).append("\n"); - sb.append(" ipAddress: ").append(toIndentedString(ipAddress)).append("\n"); - sb.append(" origin: ").append(toIndentedString(origin)).append("\n"); - sb.append(" authMode: ").append(toIndentedString(authMode)).append("\n"); - sb.append(" jwtID: ").append(toIndentedString(jwtID)).append("\n"); - sb.append(" bearerTokenContextID: ").append(toIndentedString(bearerTokenContextID)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("changeID"); - openapiFields.add("requestID"); - openapiFields.add("traceID"); - openapiFields.add("sessionID"); - openapiFields.add("actor"); - openapiFields.add("actorType"); - openapiFields.add("accessType"); - openapiFields.add("ipAddress"); - openapiFields.add("origin"); - openapiFields.add("authMode"); - openapiFields.add("jwtID"); - openapiFields.add("bearerTokenContextID"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to AuditEventContext - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!AuditEventContext.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in AuditEventContext is not found in the empty JSON string", AuditEventContext.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!AuditEventContext.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AuditEventContext` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("changeID") != null && !jsonObj.get("changeID").isJsonNull()) && !jsonObj.get("changeID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `changeID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("changeID").toString())); - } - if ((jsonObj.get("requestID") != null && !jsonObj.get("requestID").isJsonNull()) && !jsonObj.get("requestID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `requestID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("requestID").toString())); - } - if ((jsonObj.get("traceID") != null && !jsonObj.get("traceID").isJsonNull()) && !jsonObj.get("traceID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `traceID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("traceID").toString())); - } - if ((jsonObj.get("sessionID") != null && !jsonObj.get("sessionID").isJsonNull()) && !jsonObj.get("sessionID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `sessionID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("sessionID").toString())); - } - if ((jsonObj.get("actor") != null && !jsonObj.get("actor").isJsonNull()) && !jsonObj.get("actor").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `actor` to be a primitive type in the JSON string but got `%s`", jsonObj.get("actor").toString())); - } - // validate the optional field `actorType` - if (jsonObj.get("actorType") != null && !jsonObj.get("actorType").isJsonNull()) { - V1MemberType.validateJsonElement(jsonObj.get("actorType")); - } - // validate the optional field `accessType` - if (jsonObj.get("accessType") != null && !jsonObj.get("accessType").isJsonNull()) { - ContextAccessType.validateJsonElement(jsonObj.get("accessType")); - } - if ((jsonObj.get("ipAddress") != null && !jsonObj.get("ipAddress").isJsonNull()) && !jsonObj.get("ipAddress").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `ipAddress` to be a primitive type in the JSON string but got `%s`", jsonObj.get("ipAddress").toString())); - } - if ((jsonObj.get("origin") != null && !jsonObj.get("origin").isJsonNull()) && !jsonObj.get("origin").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `origin` to be a primitive type in the JSON string but got `%s`", jsonObj.get("origin").toString())); - } - // validate the optional field `authMode` - if (jsonObj.get("authMode") != null && !jsonObj.get("authMode").isJsonNull()) { - ContextAuthMode.validateJsonElement(jsonObj.get("authMode")); - } - if ((jsonObj.get("jwtID") != null && !jsonObj.get("jwtID").isJsonNull()) && !jsonObj.get("jwtID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `jwtID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("jwtID").toString())); - } - if ((jsonObj.get("bearerTokenContextID") != null && !jsonObj.get("bearerTokenContextID").isJsonNull()) && !jsonObj.get("bearerTokenContextID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `bearerTokenContextID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bearerTokenContextID").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!AuditEventContext.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'AuditEventContext' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(AuditEventContext.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, AuditEventContext value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public AuditEventContext read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of AuditEventContext given an JSON string - * - * @param jsonString JSON string - * @return An instance of AuditEventContext - * @throws IOException if the JSON string is invalid with respect to AuditEventContext - */ - public static AuditEventContext fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, AuditEventContext.class); - } - - /** - * Convert an instance of AuditEventContext to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/AuditEventData.java b/src/main/java/com/skyflow/generated/rest/models/AuditEventData.java deleted file mode 100644 index 4631467b..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/AuditEventData.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * Any Sensitive data that needs to be wrapped. - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class AuditEventData { - public static final String SERIALIZED_NAME_CONTENT = "content"; - @SerializedName(SERIALIZED_NAME_CONTENT) - private String content; - - public AuditEventData() { - } - - public AuditEventData content(String content) { - this.content = content; - return this; - } - - /** - * The entire body of the data requested or the query fired. - * @return content - */ - @javax.annotation.Nullable - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AuditEventData auditEventData = (AuditEventData) o; - return Objects.equals(this.content, auditEventData.content); - } - - @Override - public int hashCode() { - return Objects.hash(content); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AuditEventData {\n"); - sb.append(" content: ").append(toIndentedString(content)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("content"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to AuditEventData - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!AuditEventData.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in AuditEventData is not found in the empty JSON string", AuditEventData.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!AuditEventData.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AuditEventData` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("content") != null && !jsonObj.get("content").isJsonNull()) && !jsonObj.get("content").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `content` to be a primitive type in the JSON string but got `%s`", jsonObj.get("content").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!AuditEventData.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'AuditEventData' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(AuditEventData.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, AuditEventData value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public AuditEventData read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of AuditEventData given an JSON string - * - * @param jsonString JSON string - * @return An instance of AuditEventData - * @throws IOException if the JSON string is invalid with respect to AuditEventData - */ - public static AuditEventData fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, AuditEventData.class); - } - - /** - * Convert an instance of AuditEventData to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java b/src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java deleted file mode 100644 index 8d35595f..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * AuditEventHTTPInfo - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class AuditEventHTTPInfo { - public static final String SERIALIZED_NAME_U_R_I = "URI"; - @SerializedName(SERIALIZED_NAME_U_R_I) - private String URI; - - public static final String SERIALIZED_NAME_METHOD = "method"; - @SerializedName(SERIALIZED_NAME_METHOD) - private String method; - - public AuditEventHTTPInfo() { - } - - public AuditEventHTTPInfo URI(String URI) { - this.URI = URI; - return this; - } - - /** - * The http URI that is used. - * @return URI - */ - @javax.annotation.Nullable - public String getURI() { - return URI; - } - - public void setURI(String URI) { - this.URI = URI; - } - - - public AuditEventHTTPInfo method(String method) { - this.method = method; - return this; - } - - /** - * http method used. - * @return method - */ - @javax.annotation.Nullable - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AuditEventHTTPInfo auditEventHTTPInfo = (AuditEventHTTPInfo) o; - return Objects.equals(this.URI, auditEventHTTPInfo.URI) && - Objects.equals(this.method, auditEventHTTPInfo.method); - } - - @Override - public int hashCode() { - return Objects.hash(URI, method); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AuditEventHTTPInfo {\n"); - sb.append(" URI: ").append(toIndentedString(URI)).append("\n"); - sb.append(" method: ").append(toIndentedString(method)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("URI"); - openapiFields.add("method"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to AuditEventHTTPInfo - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!AuditEventHTTPInfo.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in AuditEventHTTPInfo is not found in the empty JSON string", AuditEventHTTPInfo.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!AuditEventHTTPInfo.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AuditEventHTTPInfo` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("URI") != null && !jsonObj.get("URI").isJsonNull()) && !jsonObj.get("URI").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `URI` to be a primitive type in the JSON string but got `%s`", jsonObj.get("URI").toString())); - } - if ((jsonObj.get("method") != null && !jsonObj.get("method").isJsonNull()) && !jsonObj.get("method").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `method` to be a primitive type in the JSON string but got `%s`", jsonObj.get("method").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!AuditEventHTTPInfo.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'AuditEventHTTPInfo' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(AuditEventHTTPInfo.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, AuditEventHTTPInfo value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public AuditEventHTTPInfo read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of AuditEventHTTPInfo given an JSON string - * - * @param jsonString JSON string - * @return An instance of AuditEventHTTPInfo - * @throws IOException if the JSON string is invalid with respect to AuditEventHTTPInfo - */ - public static AuditEventHTTPInfo fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, AuditEventHTTPInfo.class); - } - - /** - * Convert an instance of AuditEventHTTPInfo to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java b/src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java deleted file mode 100644 index 4ef6d0f4..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Method of the operation. - */ -@JsonAdapter(BatchRecordMethod.Adapter.class) -public enum BatchRecordMethod { - - NONE("NONE"), - - POST("POST"), - - PUT("PUT"), - - GET("GET"), - - DELETE("DELETE"); - - private String value; - - BatchRecordMethod(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static BatchRecordMethod fromValue(String value) { - for (BatchRecordMethod b : BatchRecordMethod.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final BatchRecordMethod enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public BatchRecordMethod read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return BatchRecordMethod.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - BatchRecordMethod.fromValue(value); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java b/src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java deleted file mode 100644 index 92075e20..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Type of access for the request. - */ -@JsonAdapter(ContextAccessType.Adapter.class) -public enum ContextAccessType { - - ACCESS_NONE("ACCESS_NONE"), - - API("API"), - - SQL("SQL"); - - private String value; - - ContextAccessType(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static ContextAccessType fromValue(String value) { - for (ContextAccessType b : ContextAccessType.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final ContextAccessType enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public ContextAccessType read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return ContextAccessType.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - ContextAccessType.fromValue(value); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java b/src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java deleted file mode 100644 index d0fc0afc..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Authentication mode the `actor` used. - */ -@JsonAdapter(ContextAuthMode.Adapter.class) -public enum ContextAuthMode { - - AUTH_NONE("AUTH_NONE"), - - OKTA_JWT("OKTA_JWT"), - - SERVICE_ACCOUNT_JWT("SERVICE_ACCOUNT_JWT"), - - PAT_JWT("PAT_JWT"); - - private String value; - - ContextAuthMode(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static ContextAuthMode fromValue(String value) { - for (ContextAuthMode b : ContextAuthMode.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final ContextAuthMode enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public ContextAuthMode read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return ContextAuthMode.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - ContextAuthMode.fromValue(value); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java b/src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java deleted file mode 100644 index 346833e6..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets DetokenizeRecordResponseValueType - */ -@JsonAdapter(DetokenizeRecordResponseValueType.Adapter.class) -public enum DetokenizeRecordResponseValueType { - - NONE("NONE"), - - STRING("STRING"), - - INTEGER("INTEGER"), - - FLOAT("FLOAT"), - - BOOL("BOOL"), - - DATETIME("DATETIME"), - - JSON("JSON"), - - ARRAY("ARRAY"), - - DATE("DATE"); - - private String value; - - DetokenizeRecordResponseValueType(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static DetokenizeRecordResponseValueType fromValue(String value) { - for (DetokenizeRecordResponseValueType b : DetokenizeRecordResponseValueType.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final DetokenizeRecordResponseValueType enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public DetokenizeRecordResponseValueType read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return DetokenizeRecordResponseValueType.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - DetokenizeRecordResponseValueType.fromValue(value); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java b/src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java deleted file mode 100644 index 44ca3e7f..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.ProtobufAny; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * GooglerpcStatus - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class GooglerpcStatus { - public static final String SERIALIZED_NAME_CODE = "code"; - @SerializedName(SERIALIZED_NAME_CODE) - private Integer code; - - public static final String SERIALIZED_NAME_MESSAGE = "message"; - @SerializedName(SERIALIZED_NAME_MESSAGE) - private String message; - - public static final String SERIALIZED_NAME_DETAILS = "details"; - @SerializedName(SERIALIZED_NAME_DETAILS) - private List details = new ArrayList<>(); - - public GooglerpcStatus() { - } - - public GooglerpcStatus code(Integer code) { - this.code = code; - return this; - } - - /** - * Get code - * @return code - */ - @javax.annotation.Nullable - public Integer getCode() { - return code; - } - - public void setCode(Integer code) { - this.code = code; - } - - - public GooglerpcStatus message(String message) { - this.message = message; - return this; - } - - /** - * Get message - * @return message - */ - @javax.annotation.Nullable - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - - public GooglerpcStatus details(List details) { - this.details = details; - return this; - } - - public GooglerpcStatus addDetailsItem(ProtobufAny detailsItem) { - if (this.details == null) { - this.details = new ArrayList<>(); - } - this.details.add(detailsItem); - return this; - } - - /** - * Get details - * @return details - */ - @javax.annotation.Nullable - public List getDetails() { - return details; - } - - public void setDetails(List details) { - this.details = details; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - GooglerpcStatus googlerpcStatus = (GooglerpcStatus) o; - return Objects.equals(this.code, googlerpcStatus.code) && - Objects.equals(this.message, googlerpcStatus.message) && - Objects.equals(this.details, googlerpcStatus.details); - } - - @Override - public int hashCode() { - return Objects.hash(code, message, details); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class GooglerpcStatus {\n"); - sb.append(" code: ").append(toIndentedString(code)).append("\n"); - sb.append(" message: ").append(toIndentedString(message)).append("\n"); - sb.append(" details: ").append(toIndentedString(details)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("code"); - openapiFields.add("message"); - openapiFields.add("details"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to GooglerpcStatus - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!GooglerpcStatus.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in GooglerpcStatus is not found in the empty JSON string", GooglerpcStatus.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!GooglerpcStatus.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `GooglerpcStatus` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("message") != null && !jsonObj.get("message").isJsonNull()) && !jsonObj.get("message").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString())); - } - // ensure the optional json data is an array if present - if (jsonObj.get("details") != null && !jsonObj.get("details").isJsonNull() && !jsonObj.get("details").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `details` to be an array in the JSON string but got `%s`", jsonObj.get("details").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!GooglerpcStatus.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'GooglerpcStatus' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(GooglerpcStatus.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, GooglerpcStatus value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public GooglerpcStatus read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of GooglerpcStatus given an JSON string - * - * @param jsonString JSON string - * @return An instance of GooglerpcStatus - * @throws IOException if the JSON string is invalid with respect to GooglerpcStatus - */ - public static GooglerpcStatus fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, GooglerpcStatus.class); - } - - /** - * Convert an instance of GooglerpcStatus to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java b/src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java deleted file mode 100644 index 658d341e..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * ProtobufAny - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class ProtobufAny { - public static final String SERIALIZED_NAME_AT_TYPE = "@type"; - @SerializedName(SERIALIZED_NAME_AT_TYPE) - private String atType; - - public ProtobufAny() { - } - - public ProtobufAny atType(String atType) { - this.atType = atType; - return this; - } - - /** - * Get atType - * @return atType - */ - @javax.annotation.Nullable - public String getAtType() { - return atType; - } - - public void setAtType(String atType) { - this.atType = atType; - } - - /** - * A container for additional, undeclared properties. - * This is a holder for any undeclared properties as specified with - * the 'additionalProperties' keyword in the OAS document. - */ - private Map additionalProperties; - - /** - * Set the additional (undeclared) property with the specified name and value. - * If the property does not already exist, create it otherwise replace it. - * - * @param key name of the property - * @param value value of the property - * @return the ProtobufAny instance itself - */ - public ProtobufAny putAdditionalProperty(String key, Object value) { - if (this.additionalProperties == null) { - this.additionalProperties = new HashMap(); - } - this.additionalProperties.put(key, value); - return this; - } - - /** - * Return the additional (undeclared) property. - * - * @return a map of objects - */ - public Map getAdditionalProperties() { - return additionalProperties; - } - - /** - * Return the additional (undeclared) property with the specified name. - * - * @param key name of the property - * @return an object - */ - public Object getAdditionalProperty(String key) { - if (this.additionalProperties == null) { - return null; - } - return this.additionalProperties.get(key); - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ProtobufAny protobufAny = (ProtobufAny) o; - return Objects.equals(this.atType, protobufAny.atType)&& - Objects.equals(this.additionalProperties, protobufAny.additionalProperties); - } - - @Override - public int hashCode() { - return Objects.hash(atType, additionalProperties); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ProtobufAny {\n"); - sb.append(" atType: ").append(toIndentedString(atType)).append("\n"); - sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("@type"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to ProtobufAny - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!ProtobufAny.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in ProtobufAny is not found in the empty JSON string", ProtobufAny.openapiRequiredFields.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("@type") != null && !jsonObj.get("@type").isJsonNull()) && !jsonObj.get("@type").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `@type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("@type").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!ProtobufAny.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'ProtobufAny' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(ProtobufAny.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, ProtobufAny value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - obj.remove("additionalProperties"); - // serialize additional properties - if (value.getAdditionalProperties() != null) { - for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { - if (entry.getValue() instanceof String) - obj.addProperty(entry.getKey(), (String) entry.getValue()); - else if (entry.getValue() instanceof Number) - obj.addProperty(entry.getKey(), (Number) entry.getValue()); - else if (entry.getValue() instanceof Boolean) - obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); - else if (entry.getValue() instanceof Character) - obj.addProperty(entry.getKey(), (Character) entry.getValue()); - else { - JsonElement jsonElement = gson.toJsonTree(entry.getValue()); - if (jsonElement.isJsonArray()) { - obj.add(entry.getKey(), jsonElement.getAsJsonArray()); - } else { - obj.add(entry.getKey(), jsonElement.getAsJsonObject()); - } - } - } - } - elementAdapter.write(out, obj); - } - - @Override - public ProtobufAny read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // store additional fields in the deserialized instance - ProtobufAny instance = thisAdapter.fromJsonTree(jsonObj); - for (Map.Entry entry : jsonObj.entrySet()) { - if (!openapiFields.contains(entry.getKey())) { - if (entry.getValue().isJsonPrimitive()) { // primitive type - if (entry.getValue().getAsJsonPrimitive().isString()) - instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); - else if (entry.getValue().getAsJsonPrimitive().isNumber()) - instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); - else if (entry.getValue().getAsJsonPrimitive().isBoolean()) - instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); - else - throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); - } else if (entry.getValue().isJsonArray()) { - instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); - } else { // JSON object - instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); - } - } - } - return instance; - } - - }.nullSafe(); - } - } - - /** - * Create an instance of ProtobufAny given an JSON string - * - * @param jsonString JSON string - * @return An instance of ProtobufAny - * @throws IOException if the JSON string is invalid with respect to ProtobufAny - */ - public static ProtobufAny fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, ProtobufAny.class); - } - - /** - * Convert an instance of ProtobufAny to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java b/src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java deleted file mode 100644 index 3a7790a0..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * QueryServiceExecuteQueryBody - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class QueryServiceExecuteQueryBody { - public static final String SERIALIZED_NAME_QUERY = "query"; - @SerializedName(SERIALIZED_NAME_QUERY) - private String query; - - public QueryServiceExecuteQueryBody() { - } - - public QueryServiceExecuteQueryBody query(String query) { - this.query = query; - return this; - } - - /** - * The SQL query to execute.<br><br><b>Supported commands:</b> <ul> <li><code>SELECT</code></li> </ul> <b>Supported operators:</b> <ul> <li><code>&gt;</code></li> <li><code>&lt;</code></li> <li><code>=</code></li> <li><code>AND</code></li> <li><code>OR</code></li> <li><code>NOT</code></li> <li><code>LIKE</code></li> <li><code>ILIKE</code></li> <li><code>NULL</code></li> <li><code>NOT NULL</code></li> </ul> <b>Supported keywords:</b> <ul> <li><code>FROM</code></li> <li><code>JOIN</code></li> <li><code>INNER JOIN</code></li> <li><code>LEFT OUTER JOIN</code></li> <li><code>LEFT JOIN</code></li> <li><code>RIGHT OUTER JOIN</code></li> <li><code>RIGHT JOIN</code></li> <li><code>FULL OUTER JOIN</code></li> <li><code>FULL JOIN</code></li> <li><code>OFFSET</code></li> <li><code>LIMIT</code></li> <li><code>WHERE</code></li> </ul> <b>Supported functions:</b> <ul> <li><code>AVG()</code></li> <li><code>SUM()</code></li> <li><code>COUNT()</code></li> <li><code>MIN()</code></li> <li><code>MAX()</code></li> <li><code>REDACTION()</code></li> </ul> - * @return query - */ - @javax.annotation.Nullable - public String getQuery() { - return query; - } - - public void setQuery(String query) { - this.query = query; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - QueryServiceExecuteQueryBody queryServiceExecuteQueryBody = (QueryServiceExecuteQueryBody) o; - return Objects.equals(this.query, queryServiceExecuteQueryBody.query); - } - - @Override - public int hashCode() { - return Objects.hash(query); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class QueryServiceExecuteQueryBody {\n"); - sb.append(" query: ").append(toIndentedString(query)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("query"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to QueryServiceExecuteQueryBody - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!QueryServiceExecuteQueryBody.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in QueryServiceExecuteQueryBody is not found in the empty JSON string", QueryServiceExecuteQueryBody.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!QueryServiceExecuteQueryBody.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `QueryServiceExecuteQueryBody` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("query") != null && !jsonObj.get("query").isJsonNull()) && !jsonObj.get("query").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `query` to be a primitive type in the JSON string but got `%s`", jsonObj.get("query").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!QueryServiceExecuteQueryBody.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'QueryServiceExecuteQueryBody' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(QueryServiceExecuteQueryBody.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, QueryServiceExecuteQueryBody value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public QueryServiceExecuteQueryBody read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of QueryServiceExecuteQueryBody given an JSON string - * - * @param jsonString JSON string - * @return An instance of QueryServiceExecuteQueryBody - * @throws IOException if the JSON string is invalid with respect to QueryServiceExecuteQueryBody - */ - public static QueryServiceExecuteQueryBody fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, QueryServiceExecuteQueryBody.class); - } - - /** - * Convert an instance of QueryServiceExecuteQueryBody to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java b/src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java deleted file mode 100644 index ec0c3f95..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1BYOT; -import com.skyflow.generated.rest.models.V1BatchRecord; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * RecordServiceBatchOperationBody - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class RecordServiceBatchOperationBody { - public static final String SERIALIZED_NAME_RECORDS = "records"; - @SerializedName(SERIALIZED_NAME_RECORDS) - private List records = new ArrayList<>(); - - public static final String SERIALIZED_NAME_CONTINUE_ON_ERROR = "continueOnError"; - @SerializedName(SERIALIZED_NAME_CONTINUE_ON_ERROR) - private Boolean continueOnError; - - public static final String SERIALIZED_NAME_BYOT = "byot"; - @SerializedName(SERIALIZED_NAME_BYOT) - private V1BYOT byot = V1BYOT.DISABLE; - - public RecordServiceBatchOperationBody() { - } - - public RecordServiceBatchOperationBody records(List records) { - this.records = records; - return this; - } - - public RecordServiceBatchOperationBody addRecordsItem(V1BatchRecord recordsItem) { - if (this.records == null) { - this.records = new ArrayList<>(); - } - this.records.add(recordsItem); - return this; - } - - /** - * Record operations to perform. - * @return records - */ - @javax.annotation.Nullable - public List getRecords() { - return records; - } - - public void setRecords(List records) { - this.records = records; - } - - - public RecordServiceBatchOperationBody continueOnError(Boolean continueOnError) { - this.continueOnError = continueOnError; - return this; - } - - /** - * Continue performing operations on partial errors. - * @return continueOnError - */ - @javax.annotation.Nullable - public Boolean getContinueOnError() { - return continueOnError; - } - - public void setContinueOnError(Boolean continueOnError) { - this.continueOnError = continueOnError; - } - - - public RecordServiceBatchOperationBody byot(V1BYOT byot) { - this.byot = byot; - return this; - } - - /** - * Get byot - * @return byot - */ - @javax.annotation.Nullable - public V1BYOT getByot() { - return byot; - } - - public void setByot(V1BYOT byot) { - this.byot = byot; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - RecordServiceBatchOperationBody recordServiceBatchOperationBody = (RecordServiceBatchOperationBody) o; - return Objects.equals(this.records, recordServiceBatchOperationBody.records) && - Objects.equals(this.continueOnError, recordServiceBatchOperationBody.continueOnError) && - Objects.equals(this.byot, recordServiceBatchOperationBody.byot); - } - - @Override - public int hashCode() { - return Objects.hash(records, continueOnError, byot); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class RecordServiceBatchOperationBody {\n"); - sb.append(" records: ").append(toIndentedString(records)).append("\n"); - sb.append(" continueOnError: ").append(toIndentedString(continueOnError)).append("\n"); - sb.append(" byot: ").append(toIndentedString(byot)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("records"); - openapiFields.add("continueOnError"); - openapiFields.add("byot"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to RecordServiceBatchOperationBody - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!RecordServiceBatchOperationBody.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in RecordServiceBatchOperationBody is not found in the empty JSON string", RecordServiceBatchOperationBody.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!RecordServiceBatchOperationBody.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `RecordServiceBatchOperationBody` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { - JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); - if (jsonArrayrecords != null) { - // ensure the json data is an array - if (!jsonObj.get("records").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); - } - - // validate the optional field `records` (array) - for (int i = 0; i < jsonArrayrecords.size(); i++) { - V1BatchRecord.validateJsonElement(jsonArrayrecords.get(i)); - }; - } - } - // validate the optional field `byot` - if (jsonObj.get("byot") != null && !jsonObj.get("byot").isJsonNull()) { - V1BYOT.validateJsonElement(jsonObj.get("byot")); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!RecordServiceBatchOperationBody.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'RecordServiceBatchOperationBody' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(RecordServiceBatchOperationBody.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, RecordServiceBatchOperationBody value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public RecordServiceBatchOperationBody read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of RecordServiceBatchOperationBody given an JSON string - * - * @param jsonString JSON string - * @return An instance of RecordServiceBatchOperationBody - * @throws IOException if the JSON string is invalid with respect to RecordServiceBatchOperationBody - */ - public static RecordServiceBatchOperationBody fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, RecordServiceBatchOperationBody.class); - } - - /** - * Convert an instance of RecordServiceBatchOperationBody to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java b/src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java deleted file mode 100644 index b7358e49..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * RecordServiceBulkDeleteRecordBody - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class RecordServiceBulkDeleteRecordBody { - public static final String SERIALIZED_NAME_SKYFLOW_IDS = "skyflow_ids"; - @SerializedName(SERIALIZED_NAME_SKYFLOW_IDS) - private List skyflowIds = new ArrayList<>(); - - public RecordServiceBulkDeleteRecordBody() { - } - - public RecordServiceBulkDeleteRecordBody skyflowIds(List skyflowIds) { - this.skyflowIds = skyflowIds; - return this; - } - - public RecordServiceBulkDeleteRecordBody addSkyflowIdsItem(String skyflowIdsItem) { - if (this.skyflowIds == null) { - this.skyflowIds = new ArrayList<>(); - } - this.skyflowIds.add(skyflowIdsItem); - return this; - } - - /** - * `skyflow_id` values of the records to delete. If `*` is specified, this operation deletes all records in the table. - * @return skyflowIds - */ - @javax.annotation.Nullable - public List getSkyflowIds() { - return skyflowIds; - } - - public void setSkyflowIds(List skyflowIds) { - this.skyflowIds = skyflowIds; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - RecordServiceBulkDeleteRecordBody recordServiceBulkDeleteRecordBody = (RecordServiceBulkDeleteRecordBody) o; - return Objects.equals(this.skyflowIds, recordServiceBulkDeleteRecordBody.skyflowIds); - } - - @Override - public int hashCode() { - return Objects.hash(skyflowIds); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class RecordServiceBulkDeleteRecordBody {\n"); - sb.append(" skyflowIds: ").append(toIndentedString(skyflowIds)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("skyflow_ids"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to RecordServiceBulkDeleteRecordBody - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!RecordServiceBulkDeleteRecordBody.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in RecordServiceBulkDeleteRecordBody is not found in the empty JSON string", RecordServiceBulkDeleteRecordBody.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!RecordServiceBulkDeleteRecordBody.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `RecordServiceBulkDeleteRecordBody` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the optional json data is an array if present - if (jsonObj.get("skyflow_ids") != null && !jsonObj.get("skyflow_ids").isJsonNull() && !jsonObj.get("skyflow_ids").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `skyflow_ids` to be an array in the JSON string but got `%s`", jsonObj.get("skyflow_ids").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!RecordServiceBulkDeleteRecordBody.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'RecordServiceBulkDeleteRecordBody' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(RecordServiceBulkDeleteRecordBody.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, RecordServiceBulkDeleteRecordBody value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public RecordServiceBulkDeleteRecordBody read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of RecordServiceBulkDeleteRecordBody given an JSON string - * - * @param jsonString JSON string - * @return An instance of RecordServiceBulkDeleteRecordBody - * @throws IOException if the JSON string is invalid with respect to RecordServiceBulkDeleteRecordBody - */ - public static RecordServiceBulkDeleteRecordBody fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, RecordServiceBulkDeleteRecordBody.class); - } - - /** - * Convert an instance of RecordServiceBulkDeleteRecordBody to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java b/src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java deleted file mode 100644 index 0ffe7ce8..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java +++ /dev/null @@ -1,339 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1BYOT; -import com.skyflow.generated.rest.models.V1FieldRecords; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * RecordServiceInsertRecordBody - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class RecordServiceInsertRecordBody { - public static final String SERIALIZED_NAME_RECORDS = "records"; - @SerializedName(SERIALIZED_NAME_RECORDS) - private List records = new ArrayList<>(); - - public static final String SERIALIZED_NAME_TOKENIZATION = "tokenization"; - @SerializedName(SERIALIZED_NAME_TOKENIZATION) - private Boolean tokenization; - - public static final String SERIALIZED_NAME_UPSERT = "upsert"; - @SerializedName(SERIALIZED_NAME_UPSERT) - private String upsert; - - public static final String SERIALIZED_NAME_HOMOGENEOUS = "homogeneous"; - @SerializedName(SERIALIZED_NAME_HOMOGENEOUS) - private Boolean homogeneous = false; - - public static final String SERIALIZED_NAME_BYOT = "byot"; - @SerializedName(SERIALIZED_NAME_BYOT) - private V1BYOT byot = V1BYOT.DISABLE; - - public RecordServiceInsertRecordBody() { - } - - public RecordServiceInsertRecordBody records(List records) { - this.records = records; - return this; - } - - public RecordServiceInsertRecordBody addRecordsItem(V1FieldRecords recordsItem) { - if (this.records == null) { - this.records = new ArrayList<>(); - } - this.records.add(recordsItem); - return this; - } - - /** - * Record values and tokens. - * @return records - */ - @javax.annotation.Nullable - public List getRecords() { - return records; - } - - public void setRecords(List records) { - this.records = records; - } - - - public RecordServiceInsertRecordBody tokenization(Boolean tokenization) { - this.tokenization = tokenization; - return this; - } - - /** - * If `true`, this operation returns tokens for fields with tokenization enabled. - * @return tokenization - */ - @javax.annotation.Nullable - public Boolean getTokenization() { - return tokenization; - } - - public void setTokenization(Boolean tokenization) { - this.tokenization = tokenization; - } - - - public RecordServiceInsertRecordBody upsert(String upsert) { - this.upsert = upsert; - return this; - } - - /** - * Name of a unique column in the table. Uses upsert operations to check if a record exists based on the unique column's value. If a matching record exists, the record updates with the values you provide. If a matching record doesn't exist, the upsert operation inserts a new record.<br /><br />When you upsert a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed. - * @return upsert - */ - @javax.annotation.Nullable - public String getUpsert() { - return upsert; - } - - public void setUpsert(String upsert) { - this.upsert = upsert; - } - - - public RecordServiceInsertRecordBody homogeneous(Boolean homogeneous) { - this.homogeneous = homogeneous; - return this; - } - - /** - * If `true`, this operation mandates that all the records have the same fields. This parameter does not work with upsert. - * @return homogeneous - */ - @javax.annotation.Nullable - public Boolean getHomogeneous() { - return homogeneous; - } - - public void setHomogeneous(Boolean homogeneous) { - this.homogeneous = homogeneous; - } - - - public RecordServiceInsertRecordBody byot(V1BYOT byot) { - this.byot = byot; - return this; - } - - /** - * Get byot - * @return byot - */ - @javax.annotation.Nullable - public V1BYOT getByot() { - return byot; - } - - public void setByot(V1BYOT byot) { - this.byot = byot; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - RecordServiceInsertRecordBody recordServiceInsertRecordBody = (RecordServiceInsertRecordBody) o; - return Objects.equals(this.records, recordServiceInsertRecordBody.records) && - Objects.equals(this.tokenization, recordServiceInsertRecordBody.tokenization) && - Objects.equals(this.upsert, recordServiceInsertRecordBody.upsert) && - Objects.equals(this.homogeneous, recordServiceInsertRecordBody.homogeneous) && - Objects.equals(this.byot, recordServiceInsertRecordBody.byot); - } - - @Override - public int hashCode() { - return Objects.hash(records, tokenization, upsert, homogeneous, byot); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class RecordServiceInsertRecordBody {\n"); - sb.append(" records: ").append(toIndentedString(records)).append("\n"); - sb.append(" tokenization: ").append(toIndentedString(tokenization)).append("\n"); - sb.append(" upsert: ").append(toIndentedString(upsert)).append("\n"); - sb.append(" homogeneous: ").append(toIndentedString(homogeneous)).append("\n"); - sb.append(" byot: ").append(toIndentedString(byot)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("records"); - openapiFields.add("tokenization"); - openapiFields.add("upsert"); - openapiFields.add("homogeneous"); - openapiFields.add("byot"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to RecordServiceInsertRecordBody - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!RecordServiceInsertRecordBody.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in RecordServiceInsertRecordBody is not found in the empty JSON string", RecordServiceInsertRecordBody.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!RecordServiceInsertRecordBody.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `RecordServiceInsertRecordBody` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { - JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); - if (jsonArrayrecords != null) { - // ensure the json data is an array - if (!jsonObj.get("records").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); - } - - // validate the optional field `records` (array) - for (int i = 0; i < jsonArrayrecords.size(); i++) { - V1FieldRecords.validateJsonElement(jsonArrayrecords.get(i)); - }; - } - } - if ((jsonObj.get("upsert") != null && !jsonObj.get("upsert").isJsonNull()) && !jsonObj.get("upsert").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `upsert` to be a primitive type in the JSON string but got `%s`", jsonObj.get("upsert").toString())); - } - // validate the optional field `byot` - if (jsonObj.get("byot") != null && !jsonObj.get("byot").isJsonNull()) { - V1BYOT.validateJsonElement(jsonObj.get("byot")); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!RecordServiceInsertRecordBody.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'RecordServiceInsertRecordBody' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(RecordServiceInsertRecordBody.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, RecordServiceInsertRecordBody value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public RecordServiceInsertRecordBody read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of RecordServiceInsertRecordBody given an JSON string - * - * @param jsonString JSON string - * @return An instance of RecordServiceInsertRecordBody - * @throws IOException if the JSON string is invalid with respect to RecordServiceInsertRecordBody - */ - public static RecordServiceInsertRecordBody fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, RecordServiceInsertRecordBody.class); - } - - /** - * Convert an instance of RecordServiceInsertRecordBody to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java b/src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java deleted file mode 100644 index 27e8f48a..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1BYOT; -import com.skyflow.generated.rest.models.V1FieldRecords; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * RecordServiceUpdateRecordBody - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class RecordServiceUpdateRecordBody { - public static final String SERIALIZED_NAME_RECORD = "record"; - @SerializedName(SERIALIZED_NAME_RECORD) - private V1FieldRecords record; - - public static final String SERIALIZED_NAME_TOKENIZATION = "tokenization"; - @SerializedName(SERIALIZED_NAME_TOKENIZATION) - private Boolean tokenization; - - public static final String SERIALIZED_NAME_BYOT = "byot"; - @SerializedName(SERIALIZED_NAME_BYOT) - private V1BYOT byot = V1BYOT.DISABLE; - - public RecordServiceUpdateRecordBody() { - } - - public RecordServiceUpdateRecordBody record(V1FieldRecords record) { - this.record = record; - return this; - } - - /** - * Get record - * @return record - */ - @javax.annotation.Nullable - public V1FieldRecords getRecord() { - return record; - } - - public void setRecord(V1FieldRecords record) { - this.record = record; - } - - - public RecordServiceUpdateRecordBody tokenization(Boolean tokenization) { - this.tokenization = tokenization; - return this; - } - - /** - * If `true`, this operation returns tokens for fields with tokenization enabled. - * @return tokenization - */ - @javax.annotation.Nullable - public Boolean getTokenization() { - return tokenization; - } - - public void setTokenization(Boolean tokenization) { - this.tokenization = tokenization; - } - - - public RecordServiceUpdateRecordBody byot(V1BYOT byot) { - this.byot = byot; - return this; - } - - /** - * Get byot - * @return byot - */ - @javax.annotation.Nullable - public V1BYOT getByot() { - return byot; - } - - public void setByot(V1BYOT byot) { - this.byot = byot; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - RecordServiceUpdateRecordBody recordServiceUpdateRecordBody = (RecordServiceUpdateRecordBody) o; - return Objects.equals(this.record, recordServiceUpdateRecordBody.record) && - Objects.equals(this.tokenization, recordServiceUpdateRecordBody.tokenization) && - Objects.equals(this.byot, recordServiceUpdateRecordBody.byot); - } - - @Override - public int hashCode() { - return Objects.hash(record, tokenization, byot); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class RecordServiceUpdateRecordBody {\n"); - sb.append(" record: ").append(toIndentedString(record)).append("\n"); - sb.append(" tokenization: ").append(toIndentedString(tokenization)).append("\n"); - sb.append(" byot: ").append(toIndentedString(byot)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("record"); - openapiFields.add("tokenization"); - openapiFields.add("byot"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to RecordServiceUpdateRecordBody - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!RecordServiceUpdateRecordBody.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in RecordServiceUpdateRecordBody is not found in the empty JSON string", RecordServiceUpdateRecordBody.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!RecordServiceUpdateRecordBody.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `RecordServiceUpdateRecordBody` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the optional field `record` - if (jsonObj.get("record") != null && !jsonObj.get("record").isJsonNull()) { - V1FieldRecords.validateJsonElement(jsonObj.get("record")); - } - // validate the optional field `byot` - if (jsonObj.get("byot") != null && !jsonObj.get("byot").isJsonNull()) { - V1BYOT.validateJsonElement(jsonObj.get("byot")); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!RecordServiceUpdateRecordBody.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'RecordServiceUpdateRecordBody' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(RecordServiceUpdateRecordBody.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, RecordServiceUpdateRecordBody value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public RecordServiceUpdateRecordBody read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of RecordServiceUpdateRecordBody given an JSON string - * - * @param jsonString JSON string - * @return An instance of RecordServiceUpdateRecordBody - * @throws IOException if the JSON string is invalid with respect to RecordServiceUpdateRecordBody - */ - public static RecordServiceUpdateRecordBody fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, RecordServiceUpdateRecordBody.class); - } - - /** - * Convert an instance of RecordServiceUpdateRecordBody to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java b/src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java deleted file mode 100644 index e0c8ea98..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Redaction type. Subject to policies assigned to the API caller. When used for detokenization, only supported for vaults that support [column groups](/tokenization-column-groups/). - */ -@JsonAdapter(RedactionEnumREDACTION.Adapter.class) -public enum RedactionEnumREDACTION { - - DEFAULT("DEFAULT"), - - REDACTED("REDACTED"), - - MASKED("MASKED"), - - PLAIN_TEXT("PLAIN_TEXT"); - - private String value; - - RedactionEnumREDACTION(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static RedactionEnumREDACTION fromValue(String value) { - for (RedactionEnumREDACTION b : RedactionEnumREDACTION.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final RedactionEnumREDACTION enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public RedactionEnumREDACTION read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return RedactionEnumREDACTION.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - RedactionEnumREDACTION.fromValue(value); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/RequestActionType.java b/src/main/java/com/skyflow/generated/rest/models/RequestActionType.java deleted file mode 100644 index d5e979d8..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/RequestActionType.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Gets or Sets RequestActionType - */ -@JsonAdapter(RequestActionType.Adapter.class) -public enum RequestActionType { - - NONE("NONE"), - - ASSIGN("ASSIGN"), - - CREATE("CREATE"), - - DELETE("DELETE"), - - EXECUTE("EXECUTE"), - - LIST("LIST"), - - READ("READ"), - - UNASSIGN("UNASSIGN"), - - UPDATE("UPDATE"), - - VALIDATE("VALIDATE"), - - LOGIN("LOGIN"), - - ROTATE("ROTATE"), - - SCHEDULEROTATION("SCHEDULEROTATION"), - - SCHEDULEROTATIONALERT("SCHEDULEROTATIONALERT"), - - IMPORT("IMPORT"), - - GETIMPORTPARAMETERS("GETIMPORTPARAMETERS"), - - PING("PING"), - - GETCLOUDPROVIDER("GETCLOUDPROVIDER"); - - private String value; - - RequestActionType(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static RequestActionType fromValue(String value) { - for (RequestActionType b : RequestActionType.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final RequestActionType enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public RequestActionType read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return RequestActionType.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - RequestActionType.fromValue(value); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java deleted file mode 100644 index faf2c5b3..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1AuditAfterOptions - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1AuditAfterOptions { - public static final String SERIALIZED_NAME_TIMESTAMP = "timestamp"; - @SerializedName(SERIALIZED_NAME_TIMESTAMP) - private String timestamp; - - public static final String SERIALIZED_NAME_CHANGE_I_D = "changeID"; - @SerializedName(SERIALIZED_NAME_CHANGE_I_D) - private String changeID; - - public V1AuditAfterOptions() { - } - - public V1AuditAfterOptions timestamp(String timestamp) { - this.timestamp = timestamp; - return this; - } - - /** - * Timestamp provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. - * @return timestamp - */ - @javax.annotation.Nullable - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - - public V1AuditAfterOptions changeID(String changeID) { - this.changeID = changeID; - return this; - } - - /** - * Change ID provided in the previous audit response's `nextOps` attribute. An alternate way to manage response pagination. Can't be used with `sortOps` or `offset`. For the first request in a series of audit requests, leave blank. - * @return changeID - */ - @javax.annotation.Nullable - public String getChangeID() { - return changeID; - } - - public void setChangeID(String changeID) { - this.changeID = changeID; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1AuditAfterOptions v1AuditAfterOptions = (V1AuditAfterOptions) o; - return Objects.equals(this.timestamp, v1AuditAfterOptions.timestamp) && - Objects.equals(this.changeID, v1AuditAfterOptions.changeID); - } - - @Override - public int hashCode() { - return Objects.hash(timestamp, changeID); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1AuditAfterOptions {\n"); - sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); - sb.append(" changeID: ").append(toIndentedString(changeID)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("timestamp"); - openapiFields.add("changeID"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1AuditAfterOptions - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1AuditAfterOptions.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1AuditAfterOptions is not found in the empty JSON string", V1AuditAfterOptions.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1AuditAfterOptions.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1AuditAfterOptions` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("timestamp") != null && !jsonObj.get("timestamp").isJsonNull()) && !jsonObj.get("timestamp").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `timestamp` to be a primitive type in the JSON string but got `%s`", jsonObj.get("timestamp").toString())); - } - if ((jsonObj.get("changeID") != null && !jsonObj.get("changeID").isJsonNull()) && !jsonObj.get("changeID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `changeID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("changeID").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1AuditAfterOptions.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1AuditAfterOptions' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1AuditAfterOptions.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1AuditAfterOptions value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1AuditAfterOptions read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1AuditAfterOptions given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1AuditAfterOptions - * @throws IOException if the JSON string is invalid with respect to V1AuditAfterOptions - */ - public static V1AuditAfterOptions fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1AuditAfterOptions.class); - } - - /** - * Convert an instance of V1AuditAfterOptions to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java deleted file mode 100644 index 97134351..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.AuditEventData; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * Contains fields for defining Response Properties. - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1AuditEventResponse { - public static final String SERIALIZED_NAME_CODE = "code"; - @SerializedName(SERIALIZED_NAME_CODE) - private Integer code; - - public static final String SERIALIZED_NAME_MESSAGE = "message"; - @SerializedName(SERIALIZED_NAME_MESSAGE) - private String message; - - public static final String SERIALIZED_NAME_DATA = "data"; - @SerializedName(SERIALIZED_NAME_DATA) - private AuditEventData data; - - public static final String SERIALIZED_NAME_TIMESTAMP = "timestamp"; - @SerializedName(SERIALIZED_NAME_TIMESTAMP) - private String timestamp; - - public V1AuditEventResponse() { - } - - public V1AuditEventResponse code(Integer code) { - this.code = code; - return this; - } - - /** - * The status of the overall operation. - * @return code - */ - @javax.annotation.Nullable - public Integer getCode() { - return code; - } - - public void setCode(Integer code) { - this.code = code; - } - - - public V1AuditEventResponse message(String message) { - this.message = message; - return this; - } - - /** - * The status message for the overall operation. - * @return message - */ - @javax.annotation.Nullable - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - - public V1AuditEventResponse data(AuditEventData data) { - this.data = data; - return this; - } - - /** - * Get data - * @return data - */ - @javax.annotation.Nullable - public AuditEventData getData() { - return data; - } - - public void setData(AuditEventData data) { - this.data = data; - } - - - public V1AuditEventResponse timestamp(String timestamp) { - this.timestamp = timestamp; - return this; - } - - /** - * time when this response is generated, use extention method to set it. - * @return timestamp - */ - @javax.annotation.Nullable - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1AuditEventResponse v1AuditEventResponse = (V1AuditEventResponse) o; - return Objects.equals(this.code, v1AuditEventResponse.code) && - Objects.equals(this.message, v1AuditEventResponse.message) && - Objects.equals(this.data, v1AuditEventResponse.data) && - Objects.equals(this.timestamp, v1AuditEventResponse.timestamp); - } - - @Override - public int hashCode() { - return Objects.hash(code, message, data, timestamp); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1AuditEventResponse {\n"); - sb.append(" code: ").append(toIndentedString(code)).append("\n"); - sb.append(" message: ").append(toIndentedString(message)).append("\n"); - sb.append(" data: ").append(toIndentedString(data)).append("\n"); - sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("code"); - openapiFields.add("message"); - openapiFields.add("data"); - openapiFields.add("timestamp"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1AuditEventResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1AuditEventResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1AuditEventResponse is not found in the empty JSON string", V1AuditEventResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1AuditEventResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1AuditEventResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("message") != null && !jsonObj.get("message").isJsonNull()) && !jsonObj.get("message").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString())); - } - // validate the optional field `data` - if (jsonObj.get("data") != null && !jsonObj.get("data").isJsonNull()) { - AuditEventData.validateJsonElement(jsonObj.get("data")); - } - if ((jsonObj.get("timestamp") != null && !jsonObj.get("timestamp").isJsonNull()) && !jsonObj.get("timestamp").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `timestamp` to be a primitive type in the JSON string but got `%s`", jsonObj.get("timestamp").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1AuditEventResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1AuditEventResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1AuditEventResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1AuditEventResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1AuditEventResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1AuditEventResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1AuditEventResponse - * @throws IOException if the JSON string is invalid with respect to V1AuditEventResponse - */ - public static V1AuditEventResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1AuditEventResponse.class); - } - - /** - * Convert an instance of V1AuditEventResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java deleted file mode 100644 index 1d0268b4..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1AuditAfterOptions; -import com.skyflow.generated.rest.models.V1AuditResponseEvent; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1AuditResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1AuditResponse { - public static final String SERIALIZED_NAME_EVENT = "event"; - @SerializedName(SERIALIZED_NAME_EVENT) - private List event = new ArrayList<>(); - - public static final String SERIALIZED_NAME_NEXT_OPS = "nextOps"; - @SerializedName(SERIALIZED_NAME_NEXT_OPS) - private V1AuditAfterOptions nextOps; - - public V1AuditResponse() { - } - - public V1AuditResponse event(List event) { - this.event = event; - return this; - } - - public V1AuditResponse addEventItem(V1AuditResponseEvent eventItem) { - if (this.event == null) { - this.event = new ArrayList<>(); - } - this.event.add(eventItem); - return this; - } - - /** - * Events matching the query. - * @return event - */ - @javax.annotation.Nullable - public List getEvent() { - return event; - } - - public void setEvent(List event) { - this.event = event; - } - - - public V1AuditResponse nextOps(V1AuditAfterOptions nextOps) { - this.nextOps = nextOps; - return this; - } - - /** - * Get nextOps - * @return nextOps - */ - @javax.annotation.Nullable - public V1AuditAfterOptions getNextOps() { - return nextOps; - } - - public void setNextOps(V1AuditAfterOptions nextOps) { - this.nextOps = nextOps; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1AuditResponse v1AuditResponse = (V1AuditResponse) o; - return Objects.equals(this.event, v1AuditResponse.event) && - Objects.equals(this.nextOps, v1AuditResponse.nextOps); - } - - @Override - public int hashCode() { - return Objects.hash(event, nextOps); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1AuditResponse {\n"); - sb.append(" event: ").append(toIndentedString(event)).append("\n"); - sb.append(" nextOps: ").append(toIndentedString(nextOps)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("event"); - openapiFields.add("nextOps"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1AuditResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1AuditResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1AuditResponse is not found in the empty JSON string", V1AuditResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1AuditResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1AuditResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("event") != null && !jsonObj.get("event").isJsonNull()) { - JsonArray jsonArrayevent = jsonObj.getAsJsonArray("event"); - if (jsonArrayevent != null) { - // ensure the json data is an array - if (!jsonObj.get("event").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `event` to be an array in the JSON string but got `%s`", jsonObj.get("event").toString())); - } - - // validate the optional field `event` (array) - for (int i = 0; i < jsonArrayevent.size(); i++) { - V1AuditResponseEvent.validateJsonElement(jsonArrayevent.get(i)); - }; - } - } - // validate the optional field `nextOps` - if (jsonObj.get("nextOps") != null && !jsonObj.get("nextOps").isJsonNull()) { - V1AuditAfterOptions.validateJsonElement(jsonObj.get("nextOps")); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1AuditResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1AuditResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1AuditResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1AuditResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1AuditResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1AuditResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1AuditResponse - * @throws IOException if the JSON string is invalid with respect to V1AuditResponse - */ - public static V1AuditResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1AuditResponse.class); - } - - /** - * Convert an instance of V1AuditResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java deleted file mode 100644 index 0e2070ae..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java +++ /dev/null @@ -1,367 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.AuditEventContext; -import com.skyflow.generated.rest.models.V1AuditEventResponse; -import com.skyflow.generated.rest.models.V1AuditResponseEventRequest; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * Audit event details. - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1AuditResponseEvent { - public static final String SERIALIZED_NAME_CONTEXT = "context"; - @SerializedName(SERIALIZED_NAME_CONTEXT) - private AuditEventContext context; - - public static final String SERIALIZED_NAME_REQUEST = "request"; - @SerializedName(SERIALIZED_NAME_REQUEST) - private V1AuditResponseEventRequest request; - - public static final String SERIALIZED_NAME_RESPONSE = "response"; - @SerializedName(SERIALIZED_NAME_RESPONSE) - private V1AuditEventResponse response; - - public static final String SERIALIZED_NAME_PARENT_ACCOUNT_I_D = "parentAccountID"; - @SerializedName(SERIALIZED_NAME_PARENT_ACCOUNT_I_D) - private String parentAccountID; - - public static final String SERIALIZED_NAME_ACCOUNT_I_D = "accountID"; - @SerializedName(SERIALIZED_NAME_ACCOUNT_I_D) - private String accountID; - - public static final String SERIALIZED_NAME_RESOURCE_I_DS = "resourceIDs"; - @SerializedName(SERIALIZED_NAME_RESOURCE_I_DS) - private List resourceIDs = new ArrayList<>(); - - public V1AuditResponseEvent() { - } - - public V1AuditResponseEvent context(AuditEventContext context) { - this.context = context; - return this; - } - - /** - * Get context - * @return context - */ - @javax.annotation.Nullable - public AuditEventContext getContext() { - return context; - } - - public void setContext(AuditEventContext context) { - this.context = context; - } - - - public V1AuditResponseEvent request(V1AuditResponseEventRequest request) { - this.request = request; - return this; - } - - /** - * Get request - * @return request - */ - @javax.annotation.Nullable - public V1AuditResponseEventRequest getRequest() { - return request; - } - - public void setRequest(V1AuditResponseEventRequest request) { - this.request = request; - } - - - public V1AuditResponseEvent response(V1AuditEventResponse response) { - this.response = response; - return this; - } - - /** - * Get response - * @return response - */ - @javax.annotation.Nullable - public V1AuditEventResponse getResponse() { - return response; - } - - public void setResponse(V1AuditEventResponse response) { - this.response = response; - } - - - public V1AuditResponseEvent parentAccountID(String parentAccountID) { - this.parentAccountID = parentAccountID; - return this; - } - - /** - * Parent account ID of the account that made the request, if any. - * @return parentAccountID - */ - @javax.annotation.Nullable - public String getParentAccountID() { - return parentAccountID; - } - - public void setParentAccountID(String parentAccountID) { - this.parentAccountID = parentAccountID; - } - - - public V1AuditResponseEvent accountID(String accountID) { - this.accountID = accountID; - return this; - } - - /** - * ID of the account that made the request. - * @return accountID - */ - @javax.annotation.Nullable - public String getAccountID() { - return accountID; - } - - public void setAccountID(String accountID) { - this.accountID = accountID; - } - - - public V1AuditResponseEvent resourceIDs(List resourceIDs) { - this.resourceIDs = resourceIDs; - return this; - } - - public V1AuditResponseEvent addResourceIDsItem(String resourceIDsItem) { - if (this.resourceIDs == null) { - this.resourceIDs = new ArrayList<>(); - } - this.resourceIDs.add(resourceIDsItem); - return this; - } - - /** - * IDs for resources involved in the event. Presented in `{resourceType}/{resourceID}` format. For example, `VAULT/cd1d815aa09b4cbfbb803bd20349f202`. - * @return resourceIDs - */ - @javax.annotation.Nullable - public List getResourceIDs() { - return resourceIDs; - } - - public void setResourceIDs(List resourceIDs) { - this.resourceIDs = resourceIDs; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1AuditResponseEvent v1AuditResponseEvent = (V1AuditResponseEvent) o; - return Objects.equals(this.context, v1AuditResponseEvent.context) && - Objects.equals(this.request, v1AuditResponseEvent.request) && - Objects.equals(this.response, v1AuditResponseEvent.response) && - Objects.equals(this.parentAccountID, v1AuditResponseEvent.parentAccountID) && - Objects.equals(this.accountID, v1AuditResponseEvent.accountID) && - Objects.equals(this.resourceIDs, v1AuditResponseEvent.resourceIDs); - } - - @Override - public int hashCode() { - return Objects.hash(context, request, response, parentAccountID, accountID, resourceIDs); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1AuditResponseEvent {\n"); - sb.append(" context: ").append(toIndentedString(context)).append("\n"); - sb.append(" request: ").append(toIndentedString(request)).append("\n"); - sb.append(" response: ").append(toIndentedString(response)).append("\n"); - sb.append(" parentAccountID: ").append(toIndentedString(parentAccountID)).append("\n"); - sb.append(" accountID: ").append(toIndentedString(accountID)).append("\n"); - sb.append(" resourceIDs: ").append(toIndentedString(resourceIDs)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("context"); - openapiFields.add("request"); - openapiFields.add("response"); - openapiFields.add("parentAccountID"); - openapiFields.add("accountID"); - openapiFields.add("resourceIDs"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1AuditResponseEvent - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1AuditResponseEvent.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1AuditResponseEvent is not found in the empty JSON string", V1AuditResponseEvent.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1AuditResponseEvent.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1AuditResponseEvent` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the optional field `context` - if (jsonObj.get("context") != null && !jsonObj.get("context").isJsonNull()) { - AuditEventContext.validateJsonElement(jsonObj.get("context")); - } - // validate the optional field `request` - if (jsonObj.get("request") != null && !jsonObj.get("request").isJsonNull()) { - V1AuditResponseEventRequest.validateJsonElement(jsonObj.get("request")); - } - // validate the optional field `response` - if (jsonObj.get("response") != null && !jsonObj.get("response").isJsonNull()) { - V1AuditEventResponse.validateJsonElement(jsonObj.get("response")); - } - if ((jsonObj.get("parentAccountID") != null && !jsonObj.get("parentAccountID").isJsonNull()) && !jsonObj.get("parentAccountID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `parentAccountID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("parentAccountID").toString())); - } - if ((jsonObj.get("accountID") != null && !jsonObj.get("accountID").isJsonNull()) && !jsonObj.get("accountID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `accountID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("accountID").toString())); - } - // ensure the optional json data is an array if present - if (jsonObj.get("resourceIDs") != null && !jsonObj.get("resourceIDs").isJsonNull() && !jsonObj.get("resourceIDs").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `resourceIDs` to be an array in the JSON string but got `%s`", jsonObj.get("resourceIDs").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1AuditResponseEvent.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1AuditResponseEvent' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1AuditResponseEvent.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1AuditResponseEvent value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1AuditResponseEvent read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1AuditResponseEvent given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1AuditResponseEvent - * @throws IOException if the JSON string is invalid with respect to V1AuditResponseEvent - */ - public static V1AuditResponseEvent fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1AuditResponseEvent.class); - } - - /** - * Convert an instance of V1AuditResponseEvent to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java deleted file mode 100644 index d4b69f55..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java +++ /dev/null @@ -1,456 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.AuditEventAuditResourceType; -import com.skyflow.generated.rest.models.AuditEventData; -import com.skyflow.generated.rest.models.AuditEventHTTPInfo; -import com.skyflow.generated.rest.models.RequestActionType; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * Contains fields for defining Request Properties. - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1AuditResponseEventRequest { - public static final String SERIALIZED_NAME_DATA = "data"; - @SerializedName(SERIALIZED_NAME_DATA) - private AuditEventData data; - - public static final String SERIALIZED_NAME_API_NAME = "apiName"; - @SerializedName(SERIALIZED_NAME_API_NAME) - private String apiName; - - public static final String SERIALIZED_NAME_WORKSPACE_I_D = "workspaceID"; - @SerializedName(SERIALIZED_NAME_WORKSPACE_I_D) - private String workspaceID; - - public static final String SERIALIZED_NAME_VAULT_I_D = "vaultID"; - @SerializedName(SERIALIZED_NAME_VAULT_I_D) - private String vaultID; - - public static final String SERIALIZED_NAME_TAGS = "tags"; - @SerializedName(SERIALIZED_NAME_TAGS) - private List tags = new ArrayList<>(); - - public static final String SERIALIZED_NAME_TIMESTAMP = "timestamp"; - @SerializedName(SERIALIZED_NAME_TIMESTAMP) - private String timestamp; - - public static final String SERIALIZED_NAME_ACTION_TYPE = "actionType"; - @SerializedName(SERIALIZED_NAME_ACTION_TYPE) - private RequestActionType actionType = RequestActionType.NONE; - - public static final String SERIALIZED_NAME_RESOURCE_TYPE = "resourceType"; - @SerializedName(SERIALIZED_NAME_RESOURCE_TYPE) - private AuditEventAuditResourceType resourceType = AuditEventAuditResourceType.NONE_API; - - public static final String SERIALIZED_NAME_HTTP_INFO = "httpInfo"; - @SerializedName(SERIALIZED_NAME_HTTP_INFO) - private AuditEventHTTPInfo httpInfo; - - public V1AuditResponseEventRequest() { - } - - public V1AuditResponseEventRequest data(AuditEventData data) { - this.data = data; - return this; - } - - /** - * Get data - * @return data - */ - @javax.annotation.Nullable - public AuditEventData getData() { - return data; - } - - public void setData(AuditEventData data) { - this.data = data; - } - - - public V1AuditResponseEventRequest apiName(String apiName) { - this.apiName = apiName; - return this; - } - - /** - * API name. - * @return apiName - */ - @javax.annotation.Nullable - public String getApiName() { - return apiName; - } - - public void setApiName(String apiName) { - this.apiName = apiName; - } - - - public V1AuditResponseEventRequest workspaceID(String workspaceID) { - this.workspaceID = workspaceID; - return this; - } - - /** - * The workspaceID (if any) of the request. - * @return workspaceID - */ - @javax.annotation.Nullable - public String getWorkspaceID() { - return workspaceID; - } - - public void setWorkspaceID(String workspaceID) { - this.workspaceID = workspaceID; - } - - - public V1AuditResponseEventRequest vaultID(String vaultID) { - this.vaultID = vaultID; - return this; - } - - /** - * The vaultID (if any) of the request. - * @return vaultID - */ - @javax.annotation.Nullable - public String getVaultID() { - return vaultID; - } - - public void setVaultID(String vaultID) { - this.vaultID = vaultID; - } - - - public V1AuditResponseEventRequest tags(List tags) { - this.tags = tags; - return this; - } - - public V1AuditResponseEventRequest addTagsItem(String tagsItem) { - if (this.tags == null) { - this.tags = new ArrayList<>(); - } - this.tags.add(tagsItem); - return this; - } - - /** - * Tags associated with the event. To provide better search capabilities. Like login. - * @return tags - */ - @javax.annotation.Nullable - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - - public V1AuditResponseEventRequest timestamp(String timestamp) { - this.timestamp = timestamp; - return this; - } - - /** - * time when this request is generated, use extention method to set it. - * @return timestamp - */ - @javax.annotation.Nullable - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - - public V1AuditResponseEventRequest actionType(RequestActionType actionType) { - this.actionType = actionType; - return this; - } - - /** - * Get actionType - * @return actionType - */ - @javax.annotation.Nullable - public RequestActionType getActionType() { - return actionType; - } - - public void setActionType(RequestActionType actionType) { - this.actionType = actionType; - } - - - public V1AuditResponseEventRequest resourceType(AuditEventAuditResourceType resourceType) { - this.resourceType = resourceType; - return this; - } - - /** - * Get resourceType - * @return resourceType - */ - @javax.annotation.Nullable - public AuditEventAuditResourceType getResourceType() { - return resourceType; - } - - public void setResourceType(AuditEventAuditResourceType resourceType) { - this.resourceType = resourceType; - } - - - public V1AuditResponseEventRequest httpInfo(AuditEventHTTPInfo httpInfo) { - this.httpInfo = httpInfo; - return this; - } - - /** - * Get httpInfo - * @return httpInfo - */ - @javax.annotation.Nullable - public AuditEventHTTPInfo getHttpInfo() { - return httpInfo; - } - - public void setHttpInfo(AuditEventHTTPInfo httpInfo) { - this.httpInfo = httpInfo; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1AuditResponseEventRequest v1AuditResponseEventRequest = (V1AuditResponseEventRequest) o; - return Objects.equals(this.data, v1AuditResponseEventRequest.data) && - Objects.equals(this.apiName, v1AuditResponseEventRequest.apiName) && - Objects.equals(this.workspaceID, v1AuditResponseEventRequest.workspaceID) && - Objects.equals(this.vaultID, v1AuditResponseEventRequest.vaultID) && - Objects.equals(this.tags, v1AuditResponseEventRequest.tags) && - Objects.equals(this.timestamp, v1AuditResponseEventRequest.timestamp) && - Objects.equals(this.actionType, v1AuditResponseEventRequest.actionType) && - Objects.equals(this.resourceType, v1AuditResponseEventRequest.resourceType) && - Objects.equals(this.httpInfo, v1AuditResponseEventRequest.httpInfo); - } - - @Override - public int hashCode() { - return Objects.hash(data, apiName, workspaceID, vaultID, tags, timestamp, actionType, resourceType, httpInfo); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1AuditResponseEventRequest {\n"); - sb.append(" data: ").append(toIndentedString(data)).append("\n"); - sb.append(" apiName: ").append(toIndentedString(apiName)).append("\n"); - sb.append(" workspaceID: ").append(toIndentedString(workspaceID)).append("\n"); - sb.append(" vaultID: ").append(toIndentedString(vaultID)).append("\n"); - sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); - sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); - sb.append(" actionType: ").append(toIndentedString(actionType)).append("\n"); - sb.append(" resourceType: ").append(toIndentedString(resourceType)).append("\n"); - sb.append(" httpInfo: ").append(toIndentedString(httpInfo)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("data"); - openapiFields.add("apiName"); - openapiFields.add("workspaceID"); - openapiFields.add("vaultID"); - openapiFields.add("tags"); - openapiFields.add("timestamp"); - openapiFields.add("actionType"); - openapiFields.add("resourceType"); - openapiFields.add("httpInfo"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1AuditResponseEventRequest - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1AuditResponseEventRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1AuditResponseEventRequest is not found in the empty JSON string", V1AuditResponseEventRequest.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1AuditResponseEventRequest.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1AuditResponseEventRequest` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the optional field `data` - if (jsonObj.get("data") != null && !jsonObj.get("data").isJsonNull()) { - AuditEventData.validateJsonElement(jsonObj.get("data")); - } - if ((jsonObj.get("apiName") != null && !jsonObj.get("apiName").isJsonNull()) && !jsonObj.get("apiName").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `apiName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("apiName").toString())); - } - if ((jsonObj.get("workspaceID") != null && !jsonObj.get("workspaceID").isJsonNull()) && !jsonObj.get("workspaceID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `workspaceID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("workspaceID").toString())); - } - if ((jsonObj.get("vaultID") != null && !jsonObj.get("vaultID").isJsonNull()) && !jsonObj.get("vaultID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `vaultID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("vaultID").toString())); - } - // ensure the optional json data is an array if present - if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull() && !jsonObj.get("tags").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); - } - if ((jsonObj.get("timestamp") != null && !jsonObj.get("timestamp").isJsonNull()) && !jsonObj.get("timestamp").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `timestamp` to be a primitive type in the JSON string but got `%s`", jsonObj.get("timestamp").toString())); - } - // validate the optional field `actionType` - if (jsonObj.get("actionType") != null && !jsonObj.get("actionType").isJsonNull()) { - RequestActionType.validateJsonElement(jsonObj.get("actionType")); - } - // validate the optional field `resourceType` - if (jsonObj.get("resourceType") != null && !jsonObj.get("resourceType").isJsonNull()) { - AuditEventAuditResourceType.validateJsonElement(jsonObj.get("resourceType")); - } - // validate the optional field `httpInfo` - if (jsonObj.get("httpInfo") != null && !jsonObj.get("httpInfo").isJsonNull()) { - AuditEventHTTPInfo.validateJsonElement(jsonObj.get("httpInfo")); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1AuditResponseEventRequest.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1AuditResponseEventRequest' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1AuditResponseEventRequest.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1AuditResponseEventRequest value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1AuditResponseEventRequest read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1AuditResponseEventRequest given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1AuditResponseEventRequest - * @throws IOException if the JSON string is invalid with respect to V1AuditResponseEventRequest - */ - public static V1AuditResponseEventRequest fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1AuditResponseEventRequest.class); - } - - /** - * Convert an instance of V1AuditResponseEventRequest to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java deleted file mode 100644 index 292bd674..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java +++ /dev/null @@ -1,305 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1VaultSchemaConfig; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * Request to return specific card metadata. - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1BINListRequest { - public static final String SERIALIZED_NAME_FIELDS = "fields"; - @SerializedName(SERIALIZED_NAME_FIELDS) - private List fields = new ArrayList<>(); - - public static final String SERIALIZED_NAME_B_I_N = "BIN"; - @SerializedName(SERIALIZED_NAME_B_I_N) - private String BIN; - - public static final String SERIALIZED_NAME_VAULT_SCHEMA_CONFIG = "vault_schema_config"; - @SerializedName(SERIALIZED_NAME_VAULT_SCHEMA_CONFIG) - private V1VaultSchemaConfig vaultSchemaConfig; - - public static final String SERIALIZED_NAME_SKYFLOW_ID = "skyflow_id"; - @SerializedName(SERIALIZED_NAME_SKYFLOW_ID) - private String skyflowId; - - public V1BINListRequest() { - } - - public V1BINListRequest fields(List fields) { - this.fields = fields; - return this; - } - - public V1BINListRequest addFieldsItem(String fieldsItem) { - if (this.fields == null) { - this.fields = new ArrayList<>(); - } - this.fields.add(fieldsItem); - return this; - } - - /** - * Fields to return. If not specified, all fields are returned. - * @return fields - */ - @javax.annotation.Nullable - public List getFields() { - return fields; - } - - public void setFields(List fields) { - this.fields = fields; - } - - - public V1BINListRequest BIN(String BIN) { - this.BIN = BIN; - return this; - } - - /** - * BIN of the card. - * @return BIN - */ - @javax.annotation.Nullable - public String getBIN() { - return BIN; - } - - public void setBIN(String BIN) { - this.BIN = BIN; - } - - - public V1BINListRequest vaultSchemaConfig(V1VaultSchemaConfig vaultSchemaConfig) { - this.vaultSchemaConfig = vaultSchemaConfig; - return this; - } - - /** - * Get vaultSchemaConfig - * @return vaultSchemaConfig - */ - @javax.annotation.Nullable - public V1VaultSchemaConfig getVaultSchemaConfig() { - return vaultSchemaConfig; - } - - public void setVaultSchemaConfig(V1VaultSchemaConfig vaultSchemaConfig) { - this.vaultSchemaConfig = vaultSchemaConfig; - } - - - public V1BINListRequest skyflowId(String skyflowId) { - this.skyflowId = skyflowId; - return this; - } - - /** - * <code>skyflow_id</code> of the record. - * @return skyflowId - */ - @javax.annotation.Nullable - public String getSkyflowId() { - return skyflowId; - } - - public void setSkyflowId(String skyflowId) { - this.skyflowId = skyflowId; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1BINListRequest v1BINListRequest = (V1BINListRequest) o; - return Objects.equals(this.fields, v1BINListRequest.fields) && - Objects.equals(this.BIN, v1BINListRequest.BIN) && - Objects.equals(this.vaultSchemaConfig, v1BINListRequest.vaultSchemaConfig) && - Objects.equals(this.skyflowId, v1BINListRequest.skyflowId); - } - - @Override - public int hashCode() { - return Objects.hash(fields, BIN, vaultSchemaConfig, skyflowId); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1BINListRequest {\n"); - sb.append(" fields: ").append(toIndentedString(fields)).append("\n"); - sb.append(" BIN: ").append(toIndentedString(BIN)).append("\n"); - sb.append(" vaultSchemaConfig: ").append(toIndentedString(vaultSchemaConfig)).append("\n"); - sb.append(" skyflowId: ").append(toIndentedString(skyflowId)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("fields"); - openapiFields.add("BIN"); - openapiFields.add("vault_schema_config"); - openapiFields.add("skyflow_id"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1BINListRequest - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1BINListRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1BINListRequest is not found in the empty JSON string", V1BINListRequest.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1BINListRequest.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1BINListRequest` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the optional json data is an array if present - if (jsonObj.get("fields") != null && !jsonObj.get("fields").isJsonNull() && !jsonObj.get("fields").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `fields` to be an array in the JSON string but got `%s`", jsonObj.get("fields").toString())); - } - if ((jsonObj.get("BIN") != null && !jsonObj.get("BIN").isJsonNull()) && !jsonObj.get("BIN").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `BIN` to be a primitive type in the JSON string but got `%s`", jsonObj.get("BIN").toString())); - } - // validate the optional field `vault_schema_config` - if (jsonObj.get("vault_schema_config") != null && !jsonObj.get("vault_schema_config").isJsonNull()) { - V1VaultSchemaConfig.validateJsonElement(jsonObj.get("vault_schema_config")); - } - if ((jsonObj.get("skyflow_id") != null && !jsonObj.get("skyflow_id").isJsonNull()) && !jsonObj.get("skyflow_id").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `skyflow_id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("skyflow_id").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1BINListRequest.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1BINListRequest' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1BINListRequest.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1BINListRequest value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1BINListRequest read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1BINListRequest given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1BINListRequest - * @throws IOException if the JSON string is invalid with respect to V1BINListRequest - */ - public static V1BINListRequest fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1BINListRequest.class); - } - - /** - * Convert an instance of V1BINListRequest to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java deleted file mode 100644 index 47f30610..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1Card; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * Response to the Get BIN request. - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1BINListResponse { - public static final String SERIALIZED_NAME_CARDS_DATA = "cards_data"; - @SerializedName(SERIALIZED_NAME_CARDS_DATA) - private List cardsData = new ArrayList<>(); - - public V1BINListResponse() { - } - - public V1BINListResponse cardsData(List cardsData) { - this.cardsData = cardsData; - return this; - } - - public V1BINListResponse addCardsDataItem(V1Card cardsDataItem) { - if (this.cardsData == null) { - this.cardsData = new ArrayList<>(); - } - this.cardsData.add(cardsDataItem); - return this; - } - - /** - * Card metadata associated with the specified BIN. - * @return cardsData - */ - @javax.annotation.Nullable - public List getCardsData() { - return cardsData; - } - - public void setCardsData(List cardsData) { - this.cardsData = cardsData; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1BINListResponse v1BINListResponse = (V1BINListResponse) o; - return Objects.equals(this.cardsData, v1BINListResponse.cardsData); - } - - @Override - public int hashCode() { - return Objects.hash(cardsData); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1BINListResponse {\n"); - sb.append(" cardsData: ").append(toIndentedString(cardsData)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("cards_data"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1BINListResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1BINListResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1BINListResponse is not found in the empty JSON string", V1BINListResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1BINListResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1BINListResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("cards_data") != null && !jsonObj.get("cards_data").isJsonNull()) { - JsonArray jsonArraycardsData = jsonObj.getAsJsonArray("cards_data"); - if (jsonArraycardsData != null) { - // ensure the json data is an array - if (!jsonObj.get("cards_data").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `cards_data` to be an array in the JSON string but got `%s`", jsonObj.get("cards_data").toString())); - } - - // validate the optional field `cards_data` (array) - for (int i = 0; i < jsonArraycardsData.size(); i++) { - V1Card.validateJsonElement(jsonArraycardsData.get(i)); - }; - } - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1BINListResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1BINListResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1BINListResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1BINListResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1BINListResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1BINListResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1BINListResponse - * @throws IOException if the JSON string is invalid with respect to V1BINListResponse - */ - public static V1BINListResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1BINListResponse.class); - } - - /** - * Convert an instance of V1BINListResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1BYOT.java b/src/main/java/com/skyflow/generated/rest/models/V1BYOT.java deleted file mode 100644 index 28bd87e9..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1BYOT.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Token insertion behavior. - DISABLE: Tokens aren't allowed for any fields. If tokens are specified, the request fails. - ENABLE: Tokens are allowed—but not required—for all fields. If tokens are specified, they're inserted. - ENABLE_STRICT: Tokens are required for all fields. If tokens are specified, they're inserted. If not, the request fails. - */ -@JsonAdapter(V1BYOT.Adapter.class) -public enum V1BYOT { - - DISABLE("DISABLE"), - - ENABLE("ENABLE"), - - ENABLE_STRICT("ENABLE_STRICT"); - - private String value; - - V1BYOT(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static V1BYOT fromValue(String value) { - for (V1BYOT b : V1BYOT.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final V1BYOT enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public V1BYOT read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return V1BYOT.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - V1BYOT.fromValue(value); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java deleted file mode 100644 index 2d98e66e..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1BatchOperationResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1BatchOperationResponse { - public static final String SERIALIZED_NAME_VAULT_I_D = "vaultID"; - @SerializedName(SERIALIZED_NAME_VAULT_I_D) - private String vaultID; - - public static final String SERIALIZED_NAME_RESPONSES = "responses"; - @SerializedName(SERIALIZED_NAME_RESPONSES) - private List responses = new ArrayList<>(); - - public V1BatchOperationResponse() { - } - - public V1BatchOperationResponse vaultID(String vaultID) { - this.vaultID = vaultID; - return this; - } - - /** - * ID of the vault. - * @return vaultID - */ - @javax.annotation.Nullable - public String getVaultID() { - return vaultID; - } - - public void setVaultID(String vaultID) { - this.vaultID = vaultID; - } - - - public V1BatchOperationResponse responses(List responses) { - this.responses = responses; - return this; - } - - public V1BatchOperationResponse addResponsesItem(Object responsesItem) { - if (this.responses == null) { - this.responses = new ArrayList<>(); - } - this.responses.add(responsesItem); - return this; - } - - /** - * Responses in the same order as in the request. Responses have the same payload structure as their corresponding APIs: <br/><ul><li>`POST` returns an Insert Records response.</li><li>`PUT` returns an Update Record response.</li><li>`GET` returns a Get Record response.</li><li>`DELETE` returns a Delete Record response.</li></ul> - * @return responses - */ - @javax.annotation.Nullable - public List getResponses() { - return responses; - } - - public void setResponses(List responses) { - this.responses = responses; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1BatchOperationResponse v1BatchOperationResponse = (V1BatchOperationResponse) o; - return Objects.equals(this.vaultID, v1BatchOperationResponse.vaultID) && - Objects.equals(this.responses, v1BatchOperationResponse.responses); - } - - @Override - public int hashCode() { - return Objects.hash(vaultID, responses); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1BatchOperationResponse {\n"); - sb.append(" vaultID: ").append(toIndentedString(vaultID)).append("\n"); - sb.append(" responses: ").append(toIndentedString(responses)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("vaultID"); - openapiFields.add("responses"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1BatchOperationResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1BatchOperationResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1BatchOperationResponse is not found in the empty JSON string", V1BatchOperationResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1BatchOperationResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1BatchOperationResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("vaultID") != null && !jsonObj.get("vaultID").isJsonNull()) && !jsonObj.get("vaultID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `vaultID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("vaultID").toString())); - } - // ensure the optional json data is an array if present - if (jsonObj.get("responses") != null && !jsonObj.get("responses").isJsonNull() && !jsonObj.get("responses").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `responses` to be an array in the JSON string but got `%s`", jsonObj.get("responses").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1BatchOperationResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1BatchOperationResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1BatchOperationResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1BatchOperationResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1BatchOperationResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1BatchOperationResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1BatchOperationResponse - * @throws IOException if the JSON string is invalid with respect to V1BatchOperationResponse - */ - public static V1BatchOperationResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1BatchOperationResponse.class); - } - - /** - * Convert an instance of V1BatchOperationResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java b/src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java deleted file mode 100644 index 21ab2cf9..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java +++ /dev/null @@ -1,458 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.BatchRecordMethod; -import com.skyflow.generated.rest.models.RedactionEnumREDACTION; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1BatchRecord - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1BatchRecord { - public static final String SERIALIZED_NAME_FIELDS = "fields"; - @SerializedName(SERIALIZED_NAME_FIELDS) - private Object fields; - - public static final String SERIALIZED_NAME_TABLE_NAME = "tableName"; - @SerializedName(SERIALIZED_NAME_TABLE_NAME) - private String tableName; - - public static final String SERIALIZED_NAME_METHOD = "method"; - @SerializedName(SERIALIZED_NAME_METHOD) - private BatchRecordMethod method = BatchRecordMethod.NONE; - - public static final String SERIALIZED_NAME_BATCH_I_D = "batchID"; - @SerializedName(SERIALIZED_NAME_BATCH_I_D) - private String batchID; - - public static final String SERIALIZED_NAME_REDACTION = "redaction"; - @SerializedName(SERIALIZED_NAME_REDACTION) - private RedactionEnumREDACTION redaction = RedactionEnumREDACTION.DEFAULT; - - public static final String SERIALIZED_NAME_TOKENIZATION = "tokenization"; - @SerializedName(SERIALIZED_NAME_TOKENIZATION) - private Boolean tokenization; - - public static final String SERIALIZED_NAME_I_D = "ID"; - @SerializedName(SERIALIZED_NAME_I_D) - private String ID; - - public static final String SERIALIZED_NAME_DOWNLOAD_U_R_L = "downloadURL"; - @SerializedName(SERIALIZED_NAME_DOWNLOAD_U_R_L) - private Boolean downloadURL; - - public static final String SERIALIZED_NAME_UPSERT = "upsert"; - @SerializedName(SERIALIZED_NAME_UPSERT) - private String upsert; - - public static final String SERIALIZED_NAME_TOKENS = "tokens"; - @SerializedName(SERIALIZED_NAME_TOKENS) - private Object tokens; - - public V1BatchRecord() { - } - - public V1BatchRecord fields(Object fields) { - this.fields = fields; - return this; - } - - /** - * Field and value key pairs. For example, `{'field_1':'value_1', 'field_2':'value_2'}`. Only valid when `method` is `POST` or `PUT`. - * @return fields - */ - @javax.annotation.Nullable - public Object getFields() { - return fields; - } - - public void setFields(Object fields) { - this.fields = fields; - } - - - public V1BatchRecord tableName(String tableName) { - this.tableName = tableName; - return this; - } - - /** - * Name of the table to perform the operation on. - * @return tableName - */ - @javax.annotation.Nullable - public String getTableName() { - return tableName; - } - - public void setTableName(String tableName) { - this.tableName = tableName; - } - - - public V1BatchRecord method(BatchRecordMethod method) { - this.method = method; - return this; - } - - /** - * Get method - * @return method - */ - @javax.annotation.Nullable - public BatchRecordMethod getMethod() { - return method; - } - - public void setMethod(BatchRecordMethod method) { - this.method = method; - } - - - public V1BatchRecord batchID(String batchID) { - this.batchID = batchID; - return this; - } - - /** - * ID to group operations by. Operations in the same group are executed sequentially. - * @return batchID - */ - @javax.annotation.Nullable - public String getBatchID() { - return batchID; - } - - public void setBatchID(String batchID) { - this.batchID = batchID; - } - - - public V1BatchRecord redaction(RedactionEnumREDACTION redaction) { - this.redaction = redaction; - return this; - } - - /** - * Get redaction - * @return redaction - */ - @javax.annotation.Nullable - public RedactionEnumREDACTION getRedaction() { - return redaction; - } - - public void setRedaction(RedactionEnumREDACTION redaction) { - this.redaction = redaction; - } - - - public V1BatchRecord tokenization(Boolean tokenization) { - this.tokenization = tokenization; - return this; - } - - /** - * If `true`, this operation returns tokens for fields with tokenization enabled. Only applicable if `skyflow_id` values are specified. - * @return tokenization - */ - @javax.annotation.Nullable - public Boolean getTokenization() { - return tokenization; - } - - public void setTokenization(Boolean tokenization) { - this.tokenization = tokenization; - } - - - public V1BatchRecord ID(String ID) { - this.ID = ID; - return this; - } - - /** - * `skyflow_id` for the record. Only valid when `method` is `GET`, `DELETE`, or `PUT`. - * @return ID - */ - @javax.annotation.Nullable - public String getID() { - return ID; - } - - public void setID(String ID) { - this.ID = ID; - } - - - public V1BatchRecord downloadURL(Boolean downloadURL) { - this.downloadURL = downloadURL; - return this; - } - - /** - * If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. - * @return downloadURL - */ - @javax.annotation.Nullable - public Boolean getDownloadURL() { - return downloadURL; - } - - public void setDownloadURL(Boolean downloadURL) { - this.downloadURL = downloadURL; - } - - - public V1BatchRecord upsert(String upsert) { - this.upsert = upsert; - return this; - } - - /** - * Column that stores primary keys for upsert operations. The column must be marked as unique in the vault schema. Only valid when `method` is `POST`. - * @return upsert - */ - @javax.annotation.Nullable - public String getUpsert() { - return upsert; - } - - public void setUpsert(String upsert) { - this.upsert = upsert; - } - - - public V1BatchRecord tokens(Object tokens) { - this.tokens = tokens; - return this; - } - - /** - * Fields and tokens for the record. For example, `{'field_1':'token_1', 'field_2':'token_2'}`. - * @return tokens - */ - @javax.annotation.Nullable - public Object getTokens() { - return tokens; - } - - public void setTokens(Object tokens) { - this.tokens = tokens; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1BatchRecord v1BatchRecord = (V1BatchRecord) o; - return Objects.equals(this.fields, v1BatchRecord.fields) && - Objects.equals(this.tableName, v1BatchRecord.tableName) && - Objects.equals(this.method, v1BatchRecord.method) && - Objects.equals(this.batchID, v1BatchRecord.batchID) && - Objects.equals(this.redaction, v1BatchRecord.redaction) && - Objects.equals(this.tokenization, v1BatchRecord.tokenization) && - Objects.equals(this.ID, v1BatchRecord.ID) && - Objects.equals(this.downloadURL, v1BatchRecord.downloadURL) && - Objects.equals(this.upsert, v1BatchRecord.upsert) && - Objects.equals(this.tokens, v1BatchRecord.tokens); - } - - @Override - public int hashCode() { - return Objects.hash(fields, tableName, method, batchID, redaction, tokenization, ID, downloadURL, upsert, tokens); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1BatchRecord {\n"); - sb.append(" fields: ").append(toIndentedString(fields)).append("\n"); - sb.append(" tableName: ").append(toIndentedString(tableName)).append("\n"); - sb.append(" method: ").append(toIndentedString(method)).append("\n"); - sb.append(" batchID: ").append(toIndentedString(batchID)).append("\n"); - sb.append(" redaction: ").append(toIndentedString(redaction)).append("\n"); - sb.append(" tokenization: ").append(toIndentedString(tokenization)).append("\n"); - sb.append(" ID: ").append(toIndentedString(ID)).append("\n"); - sb.append(" downloadURL: ").append(toIndentedString(downloadURL)).append("\n"); - sb.append(" upsert: ").append(toIndentedString(upsert)).append("\n"); - sb.append(" tokens: ").append(toIndentedString(tokens)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("fields"); - openapiFields.add("tableName"); - openapiFields.add("method"); - openapiFields.add("batchID"); - openapiFields.add("redaction"); - openapiFields.add("tokenization"); - openapiFields.add("ID"); - openapiFields.add("downloadURL"); - openapiFields.add("upsert"); - openapiFields.add("tokens"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1BatchRecord - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1BatchRecord.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1BatchRecord is not found in the empty JSON string", V1BatchRecord.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1BatchRecord.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1BatchRecord` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("tableName") != null && !jsonObj.get("tableName").isJsonNull()) && !jsonObj.get("tableName").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `tableName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("tableName").toString())); - } - // validate the optional field `method` - if (jsonObj.get("method") != null && !jsonObj.get("method").isJsonNull()) { - BatchRecordMethod.validateJsonElement(jsonObj.get("method")); - } - if ((jsonObj.get("batchID") != null && !jsonObj.get("batchID").isJsonNull()) && !jsonObj.get("batchID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `batchID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("batchID").toString())); - } - // validate the optional field `redaction` - if (jsonObj.get("redaction") != null && !jsonObj.get("redaction").isJsonNull()) { - RedactionEnumREDACTION.validateJsonElement(jsonObj.get("redaction")); - } - if ((jsonObj.get("ID") != null && !jsonObj.get("ID").isJsonNull()) && !jsonObj.get("ID").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `ID` to be a primitive type in the JSON string but got `%s`", jsonObj.get("ID").toString())); - } - if ((jsonObj.get("upsert") != null && !jsonObj.get("upsert").isJsonNull()) && !jsonObj.get("upsert").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `upsert` to be a primitive type in the JSON string but got `%s`", jsonObj.get("upsert").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1BatchRecord.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1BatchRecord' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1BatchRecord.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1BatchRecord value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1BatchRecord read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1BatchRecord given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1BatchRecord - * @throws IOException if the JSON string is invalid with respect to V1BatchRecord - */ - public static V1BatchRecord fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1BatchRecord.class); - } - - /** - * Convert an instance of V1BatchRecord to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java deleted file mode 100644 index 6a89ed40..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1BulkDeleteRecordResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1BulkDeleteRecordResponse { - public static final String SERIALIZED_NAME_RECORD_I_D_RESPONSE = "RecordIDResponse"; - @SerializedName(SERIALIZED_NAME_RECORD_I_D_RESPONSE) - private List recordIDResponse = new ArrayList<>(); - - public V1BulkDeleteRecordResponse() { - } - - public V1BulkDeleteRecordResponse recordIDResponse(List recordIDResponse) { - this.recordIDResponse = recordIDResponse; - return this; - } - - public V1BulkDeleteRecordResponse addRecordIDResponseItem(String recordIDResponseItem) { - if (this.recordIDResponse == null) { - this.recordIDResponse = new ArrayList<>(); - } - this.recordIDResponse.add(recordIDResponseItem); - return this; - } - - /** - * IDs for the deleted records, or `*` if all records were deleted. - * @return recordIDResponse - */ - @javax.annotation.Nullable - public List getRecordIDResponse() { - return recordIDResponse; - } - - public void setRecordIDResponse(List recordIDResponse) { - this.recordIDResponse = recordIDResponse; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1BulkDeleteRecordResponse v1BulkDeleteRecordResponse = (V1BulkDeleteRecordResponse) o; - return Objects.equals(this.recordIDResponse, v1BulkDeleteRecordResponse.recordIDResponse); - } - - @Override - public int hashCode() { - return Objects.hash(recordIDResponse); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1BulkDeleteRecordResponse {\n"); - sb.append(" recordIDResponse: ").append(toIndentedString(recordIDResponse)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("RecordIDResponse"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1BulkDeleteRecordResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1BulkDeleteRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1BulkDeleteRecordResponse is not found in the empty JSON string", V1BulkDeleteRecordResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1BulkDeleteRecordResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1BulkDeleteRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the optional json data is an array if present - if (jsonObj.get("RecordIDResponse") != null && !jsonObj.get("RecordIDResponse").isJsonNull() && !jsonObj.get("RecordIDResponse").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `RecordIDResponse` to be an array in the JSON string but got `%s`", jsonObj.get("RecordIDResponse").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1BulkDeleteRecordResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1BulkDeleteRecordResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1BulkDeleteRecordResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1BulkDeleteRecordResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1BulkDeleteRecordResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1BulkDeleteRecordResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1BulkDeleteRecordResponse - * @throws IOException if the JSON string is invalid with respect to V1BulkDeleteRecordResponse - */ - public static V1BulkDeleteRecordResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1BulkDeleteRecordResponse.class); - } - - /** - * Convert an instance of V1BulkDeleteRecordResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java deleted file mode 100644 index 2a935fe9..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1FieldRecords; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1BulkGetRecordResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1BulkGetRecordResponse { - public static final String SERIALIZED_NAME_RECORDS = "records"; - @SerializedName(SERIALIZED_NAME_RECORDS) - private List records = new ArrayList<>(); - - public V1BulkGetRecordResponse() { - } - - public V1BulkGetRecordResponse records(List records) { - this.records = records; - return this; - } - - public V1BulkGetRecordResponse addRecordsItem(V1FieldRecords recordsItem) { - if (this.records == null) { - this.records = new ArrayList<>(); - } - this.records.add(recordsItem); - return this; - } - - /** - * The specified records. - * @return records - */ - @javax.annotation.Nullable - public List getRecords() { - return records; - } - - public void setRecords(List records) { - this.records = records; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1BulkGetRecordResponse v1BulkGetRecordResponse = (V1BulkGetRecordResponse) o; - return Objects.equals(this.records, v1BulkGetRecordResponse.records); - } - - @Override - public int hashCode() { - return Objects.hash(records); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1BulkGetRecordResponse {\n"); - sb.append(" records: ").append(toIndentedString(records)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("records"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1BulkGetRecordResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1BulkGetRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1BulkGetRecordResponse is not found in the empty JSON string", V1BulkGetRecordResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1BulkGetRecordResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1BulkGetRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { - JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); - if (jsonArrayrecords != null) { - // ensure the json data is an array - if (!jsonObj.get("records").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); - } - - // validate the optional field `records` (array) - for (int i = 0; i < jsonArrayrecords.size(); i++) { - V1FieldRecords.validateJsonElement(jsonArrayrecords.get(i)); - }; - } - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1BulkGetRecordResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1BulkGetRecordResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1BulkGetRecordResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1BulkGetRecordResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1BulkGetRecordResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1BulkGetRecordResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1BulkGetRecordResponse - * @throws IOException if the JSON string is invalid with respect to V1BulkGetRecordResponse - */ - public static V1BulkGetRecordResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1BulkGetRecordResponse.class); - } - - /** - * Convert an instance of V1BulkGetRecordResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1Card.java b/src/main/java/com/skyflow/generated/rest/models/V1Card.java deleted file mode 100644 index 5c8fb3cc..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1Card.java +++ /dev/null @@ -1,437 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * Card metadata of the requested BIN. - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1Card { - public static final String SERIALIZED_NAME_B_I_N = "BIN"; - @SerializedName(SERIALIZED_NAME_B_I_N) - private String BIN; - - public static final String SERIALIZED_NAME_ISSUER_NAME = "issuer_name"; - @SerializedName(SERIALIZED_NAME_ISSUER_NAME) - private String issuerName; - - public static final String SERIALIZED_NAME_COUNTRY_CODE = "country_code"; - @SerializedName(SERIALIZED_NAME_COUNTRY_CODE) - private String countryCode; - - public static final String SERIALIZED_NAME_CURRENCY = "currency"; - @SerializedName(SERIALIZED_NAME_CURRENCY) - private String currency; - - public static final String SERIALIZED_NAME_CARD_TYPE = "card_type"; - @SerializedName(SERIALIZED_NAME_CARD_TYPE) - private String cardType; - - public static final String SERIALIZED_NAME_CARD_CATEGORY = "card_category"; - @SerializedName(SERIALIZED_NAME_CARD_CATEGORY) - private String cardCategory; - - public static final String SERIALIZED_NAME_CARD_SCHEME = "card_scheme"; - @SerializedName(SERIALIZED_NAME_CARD_SCHEME) - private String cardScheme; - - public static final String SERIALIZED_NAME_CARD_LAST_FOUR_DIGITS = "card_last_four_digits"; - @SerializedName(SERIALIZED_NAME_CARD_LAST_FOUR_DIGITS) - private String cardLastFourDigits; - - public static final String SERIALIZED_NAME_CARD_EXPIRY = "card_expiry"; - @SerializedName(SERIALIZED_NAME_CARD_EXPIRY) - private String cardExpiry; - - public V1Card() { - } - - public V1Card BIN(String BIN) { - this.BIN = BIN; - return this; - } - - /** - * BIN of the card. - * @return BIN - */ - @javax.annotation.Nullable - public String getBIN() { - return BIN; - } - - public void setBIN(String BIN) { - this.BIN = BIN; - } - - - public V1Card issuerName(String issuerName) { - this.issuerName = issuerName; - return this; - } - - /** - * Name of the card issuer bank. - * @return issuerName - */ - @javax.annotation.Nullable - public String getIssuerName() { - return issuerName; - } - - public void setIssuerName(String issuerName) { - this.issuerName = issuerName; - } - - - public V1Card countryCode(String countryCode) { - this.countryCode = countryCode; - return this; - } - - /** - * Country code of the card. - * @return countryCode - */ - @javax.annotation.Nullable - public String getCountryCode() { - return countryCode; - } - - public void setCountryCode(String countryCode) { - this.countryCode = countryCode; - } - - - public V1Card currency(String currency) { - this.currency = currency; - return this; - } - - /** - * Currency of the card. - * @return currency - */ - @javax.annotation.Nullable - public String getCurrency() { - return currency; - } - - public void setCurrency(String currency) { - this.currency = currency; - } - - - public V1Card cardType(String cardType) { - this.cardType = cardType; - return this; - } - - /** - * Type of the card. - * @return cardType - */ - @javax.annotation.Nullable - public String getCardType() { - return cardType; - } - - public void setCardType(String cardType) { - this.cardType = cardType; - } - - - public V1Card cardCategory(String cardCategory) { - this.cardCategory = cardCategory; - return this; - } - - /** - * Category of the card. - * @return cardCategory - */ - @javax.annotation.Nullable - public String getCardCategory() { - return cardCategory; - } - - public void setCardCategory(String cardCategory) { - this.cardCategory = cardCategory; - } - - - public V1Card cardScheme(String cardScheme) { - this.cardScheme = cardScheme; - return this; - } - - /** - * Scheme of the card. - * @return cardScheme - */ - @javax.annotation.Nullable - public String getCardScheme() { - return cardScheme; - } - - public void setCardScheme(String cardScheme) { - this.cardScheme = cardScheme; - } - - - public V1Card cardLastFourDigits(String cardLastFourDigits) { - this.cardLastFourDigits = cardLastFourDigits; - return this; - } - - /** - * Last four digits of the card number. - * @return cardLastFourDigits - */ - @javax.annotation.Nullable - public String getCardLastFourDigits() { - return cardLastFourDigits; - } - - public void setCardLastFourDigits(String cardLastFourDigits) { - this.cardLastFourDigits = cardLastFourDigits; - } - - - public V1Card cardExpiry(String cardExpiry) { - this.cardExpiry = cardExpiry; - return this; - } - - /** - * Expiry date of the card. - * @return cardExpiry - */ - @javax.annotation.Nullable - public String getCardExpiry() { - return cardExpiry; - } - - public void setCardExpiry(String cardExpiry) { - this.cardExpiry = cardExpiry; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1Card v1Card = (V1Card) o; - return Objects.equals(this.BIN, v1Card.BIN) && - Objects.equals(this.issuerName, v1Card.issuerName) && - Objects.equals(this.countryCode, v1Card.countryCode) && - Objects.equals(this.currency, v1Card.currency) && - Objects.equals(this.cardType, v1Card.cardType) && - Objects.equals(this.cardCategory, v1Card.cardCategory) && - Objects.equals(this.cardScheme, v1Card.cardScheme) && - Objects.equals(this.cardLastFourDigits, v1Card.cardLastFourDigits) && - Objects.equals(this.cardExpiry, v1Card.cardExpiry); - } - - @Override - public int hashCode() { - return Objects.hash(BIN, issuerName, countryCode, currency, cardType, cardCategory, cardScheme, cardLastFourDigits, cardExpiry); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1Card {\n"); - sb.append(" BIN: ").append(toIndentedString(BIN)).append("\n"); - sb.append(" issuerName: ").append(toIndentedString(issuerName)).append("\n"); - sb.append(" countryCode: ").append(toIndentedString(countryCode)).append("\n"); - sb.append(" currency: ").append(toIndentedString(currency)).append("\n"); - sb.append(" cardType: ").append(toIndentedString(cardType)).append("\n"); - sb.append(" cardCategory: ").append(toIndentedString(cardCategory)).append("\n"); - sb.append(" cardScheme: ").append(toIndentedString(cardScheme)).append("\n"); - sb.append(" cardLastFourDigits: ").append(toIndentedString(cardLastFourDigits)).append("\n"); - sb.append(" cardExpiry: ").append(toIndentedString(cardExpiry)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("BIN"); - openapiFields.add("issuer_name"); - openapiFields.add("country_code"); - openapiFields.add("currency"); - openapiFields.add("card_type"); - openapiFields.add("card_category"); - openapiFields.add("card_scheme"); - openapiFields.add("card_last_four_digits"); - openapiFields.add("card_expiry"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1Card - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1Card.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1Card is not found in the empty JSON string", V1Card.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1Card.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1Card` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("BIN") != null && !jsonObj.get("BIN").isJsonNull()) && !jsonObj.get("BIN").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `BIN` to be a primitive type in the JSON string but got `%s`", jsonObj.get("BIN").toString())); - } - if ((jsonObj.get("issuer_name") != null && !jsonObj.get("issuer_name").isJsonNull()) && !jsonObj.get("issuer_name").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `issuer_name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("issuer_name").toString())); - } - if ((jsonObj.get("country_code") != null && !jsonObj.get("country_code").isJsonNull()) && !jsonObj.get("country_code").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `country_code` to be a primitive type in the JSON string but got `%s`", jsonObj.get("country_code").toString())); - } - if ((jsonObj.get("currency") != null && !jsonObj.get("currency").isJsonNull()) && !jsonObj.get("currency").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `currency` to be a primitive type in the JSON string but got `%s`", jsonObj.get("currency").toString())); - } - if ((jsonObj.get("card_type") != null && !jsonObj.get("card_type").isJsonNull()) && !jsonObj.get("card_type").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `card_type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_type").toString())); - } - if ((jsonObj.get("card_category") != null && !jsonObj.get("card_category").isJsonNull()) && !jsonObj.get("card_category").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `card_category` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_category").toString())); - } - if ((jsonObj.get("card_scheme") != null && !jsonObj.get("card_scheme").isJsonNull()) && !jsonObj.get("card_scheme").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `card_scheme` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_scheme").toString())); - } - if ((jsonObj.get("card_last_four_digits") != null && !jsonObj.get("card_last_four_digits").isJsonNull()) && !jsonObj.get("card_last_four_digits").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `card_last_four_digits` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_last_four_digits").toString())); - } - if ((jsonObj.get("card_expiry") != null && !jsonObj.get("card_expiry").isJsonNull()) && !jsonObj.get("card_expiry").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `card_expiry` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_expiry").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1Card.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1Card' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1Card.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1Card value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1Card read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1Card given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1Card - * @throws IOException if the JSON string is invalid with respect to V1Card - */ - public static V1Card fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1Card.class); - } - - /** - * Convert an instance of V1Card to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java deleted file mode 100644 index 9a3c2cb4..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1DeleteFileResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1DeleteFileResponse { - public static final String SERIALIZED_NAME_SKYFLOW_ID = "skyflow_id"; - @SerializedName(SERIALIZED_NAME_SKYFLOW_ID) - private String skyflowId; - - public static final String SERIALIZED_NAME_DELETED = "deleted"; - @SerializedName(SERIALIZED_NAME_DELETED) - private Boolean deleted; - - public V1DeleteFileResponse() { - } - - public V1DeleteFileResponse skyflowId(String skyflowId) { - this.skyflowId = skyflowId; - return this; - } - - /** - * ID of the record. - * @return skyflowId - */ - @javax.annotation.Nullable - public String getSkyflowId() { - return skyflowId; - } - - public void setSkyflowId(String skyflowId) { - this.skyflowId = skyflowId; - } - - - public V1DeleteFileResponse deleted(Boolean deleted) { - this.deleted = deleted; - return this; - } - - /** - * If `true`, the file was deleted. - * @return deleted - */ - @javax.annotation.Nullable - public Boolean getDeleted() { - return deleted; - } - - public void setDeleted(Boolean deleted) { - this.deleted = deleted; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1DeleteFileResponse v1DeleteFileResponse = (V1DeleteFileResponse) o; - return Objects.equals(this.skyflowId, v1DeleteFileResponse.skyflowId) && - Objects.equals(this.deleted, v1DeleteFileResponse.deleted); - } - - @Override - public int hashCode() { - return Objects.hash(skyflowId, deleted); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1DeleteFileResponse {\n"); - sb.append(" skyflowId: ").append(toIndentedString(skyflowId)).append("\n"); - sb.append(" deleted: ").append(toIndentedString(deleted)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("skyflow_id"); - openapiFields.add("deleted"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1DeleteFileResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1DeleteFileResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1DeleteFileResponse is not found in the empty JSON string", V1DeleteFileResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1DeleteFileResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1DeleteFileResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("skyflow_id") != null && !jsonObj.get("skyflow_id").isJsonNull()) && !jsonObj.get("skyflow_id").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `skyflow_id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("skyflow_id").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1DeleteFileResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1DeleteFileResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1DeleteFileResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1DeleteFileResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1DeleteFileResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1DeleteFileResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1DeleteFileResponse - * @throws IOException if the JSON string is invalid with respect to V1DeleteFileResponse - */ - public static V1DeleteFileResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1DeleteFileResponse.class); - } - - /** - * Convert an instance of V1DeleteFileResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java deleted file mode 100644 index 8ebf5c35..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1DeleteRecordResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1DeleteRecordResponse { - public static final String SERIALIZED_NAME_SKYFLOW_ID = "skyflow_id"; - @SerializedName(SERIALIZED_NAME_SKYFLOW_ID) - private String skyflowId; - - public static final String SERIALIZED_NAME_DELETED = "deleted"; - @SerializedName(SERIALIZED_NAME_DELETED) - private Boolean deleted; - - public V1DeleteRecordResponse() { - } - - public V1DeleteRecordResponse skyflowId(String skyflowId) { - this.skyflowId = skyflowId; - return this; - } - - /** - * ID of the deleted record. - * @return skyflowId - */ - @javax.annotation.Nullable - public String getSkyflowId() { - return skyflowId; - } - - public void setSkyflowId(String skyflowId) { - this.skyflowId = skyflowId; - } - - - public V1DeleteRecordResponse deleted(Boolean deleted) { - this.deleted = deleted; - return this; - } - - /** - * If `true`, the record was deleted. - * @return deleted - */ - @javax.annotation.Nullable - public Boolean getDeleted() { - return deleted; - } - - public void setDeleted(Boolean deleted) { - this.deleted = deleted; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1DeleteRecordResponse v1DeleteRecordResponse = (V1DeleteRecordResponse) o; - return Objects.equals(this.skyflowId, v1DeleteRecordResponse.skyflowId) && - Objects.equals(this.deleted, v1DeleteRecordResponse.deleted); - } - - @Override - public int hashCode() { - return Objects.hash(skyflowId, deleted); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1DeleteRecordResponse {\n"); - sb.append(" skyflowId: ").append(toIndentedString(skyflowId)).append("\n"); - sb.append(" deleted: ").append(toIndentedString(deleted)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("skyflow_id"); - openapiFields.add("deleted"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1DeleteRecordResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1DeleteRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1DeleteRecordResponse is not found in the empty JSON string", V1DeleteRecordResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1DeleteRecordResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1DeleteRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("skyflow_id") != null && !jsonObj.get("skyflow_id").isJsonNull()) && !jsonObj.get("skyflow_id").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `skyflow_id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("skyflow_id").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1DeleteRecordResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1DeleteRecordResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1DeleteRecordResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1DeleteRecordResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1DeleteRecordResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1DeleteRecordResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1DeleteRecordResponse - * @throws IOException if the JSON string is invalid with respect to V1DeleteRecordResponse - */ - public static V1DeleteRecordResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1DeleteRecordResponse.class); - } - - /** - * Convert an instance of V1DeleteRecordResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java b/src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java deleted file mode 100644 index fdc5c52e..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1DetokenizeRecordRequest; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1DetokenizePayload - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1DetokenizePayload { - public static final String SERIALIZED_NAME_DETOKENIZATION_PARAMETERS = "detokenizationParameters"; - @SerializedName(SERIALIZED_NAME_DETOKENIZATION_PARAMETERS) - private List detokenizationParameters = new ArrayList<>(); - - public static final String SERIALIZED_NAME_DOWNLOAD_U_R_L = "downloadURL"; - @SerializedName(SERIALIZED_NAME_DOWNLOAD_U_R_L) - private Boolean downloadURL; - - public static final String SERIALIZED_NAME_CONTINUE_ON_ERROR = "continueOnError"; - @SerializedName(SERIALIZED_NAME_CONTINUE_ON_ERROR) - private Boolean continueOnError = false; - - public V1DetokenizePayload() { - } - - public V1DetokenizePayload detokenizationParameters(List detokenizationParameters) { - this.detokenizationParameters = detokenizationParameters; - return this; - } - - public V1DetokenizePayload addDetokenizationParametersItem(V1DetokenizeRecordRequest detokenizationParametersItem) { - if (this.detokenizationParameters == null) { - this.detokenizationParameters = new ArrayList<>(); - } - this.detokenizationParameters.add(detokenizationParametersItem); - return this; - } - - /** - * Detokenization details. - * @return detokenizationParameters - */ - @javax.annotation.Nullable - public List getDetokenizationParameters() { - return detokenizationParameters; - } - - public void setDetokenizationParameters(List detokenizationParameters) { - this.detokenizationParameters = detokenizationParameters; - } - - - public V1DetokenizePayload downloadURL(Boolean downloadURL) { - this.downloadURL = downloadURL; - return this; - } - - /** - * If `true`, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. - * @return downloadURL - */ - @javax.annotation.Nullable - public Boolean getDownloadURL() { - return downloadURL; - } - - public void setDownloadURL(Boolean downloadURL) { - this.downloadURL = downloadURL; - } - - - public V1DetokenizePayload continueOnError(Boolean continueOnError) { - this.continueOnError = continueOnError; - return this; - } - - /** - * If `true`, the detokenization request continues even if an error occurs. - * @return continueOnError - */ - @javax.annotation.Nullable - public Boolean getContinueOnError() { - return continueOnError; - } - - public void setContinueOnError(Boolean continueOnError) { - this.continueOnError = continueOnError; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1DetokenizePayload v1DetokenizePayload = (V1DetokenizePayload) o; - return Objects.equals(this.detokenizationParameters, v1DetokenizePayload.detokenizationParameters) && - Objects.equals(this.downloadURL, v1DetokenizePayload.downloadURL) && - Objects.equals(this.continueOnError, v1DetokenizePayload.continueOnError); - } - - @Override - public int hashCode() { - return Objects.hash(detokenizationParameters, downloadURL, continueOnError); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1DetokenizePayload {\n"); - sb.append(" detokenizationParameters: ").append(toIndentedString(detokenizationParameters)).append("\n"); - sb.append(" downloadURL: ").append(toIndentedString(downloadURL)).append("\n"); - sb.append(" continueOnError: ").append(toIndentedString(continueOnError)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("detokenizationParameters"); - openapiFields.add("downloadURL"); - openapiFields.add("continueOnError"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1DetokenizePayload - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1DetokenizePayload.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1DetokenizePayload is not found in the empty JSON string", V1DetokenizePayload.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1DetokenizePayload.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1DetokenizePayload` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("detokenizationParameters") != null && !jsonObj.get("detokenizationParameters").isJsonNull()) { - JsonArray jsonArraydetokenizationParameters = jsonObj.getAsJsonArray("detokenizationParameters"); - if (jsonArraydetokenizationParameters != null) { - // ensure the json data is an array - if (!jsonObj.get("detokenizationParameters").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `detokenizationParameters` to be an array in the JSON string but got `%s`", jsonObj.get("detokenizationParameters").toString())); - } - - // validate the optional field `detokenizationParameters` (array) - for (int i = 0; i < jsonArraydetokenizationParameters.size(); i++) { - V1DetokenizeRecordRequest.validateJsonElement(jsonArraydetokenizationParameters.get(i)); - }; - } - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1DetokenizePayload.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1DetokenizePayload' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1DetokenizePayload.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1DetokenizePayload value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1DetokenizePayload read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1DetokenizePayload given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1DetokenizePayload - * @throws IOException if the JSON string is invalid with respect to V1DetokenizePayload - */ - public static V1DetokenizePayload fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1DetokenizePayload.class); - } - - /** - * Convert an instance of V1DetokenizePayload to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java deleted file mode 100644 index 391fa2fc..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.RedactionEnumREDACTION; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1DetokenizeRecordRequest - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1DetokenizeRecordRequest { - public static final String SERIALIZED_NAME_TOKEN = "token"; - @SerializedName(SERIALIZED_NAME_TOKEN) - private String token; - - public static final String SERIALIZED_NAME_REDACTION = "redaction"; - @SerializedName(SERIALIZED_NAME_REDACTION) - private RedactionEnumREDACTION redaction = RedactionEnumREDACTION.DEFAULT; - - public V1DetokenizeRecordRequest() { - } - - public V1DetokenizeRecordRequest token(String token) { - this.token = token; - return this; - } - - /** - * Token that identifies the record to detokenize. - * @return token - */ - @javax.annotation.Nullable - public String getToken() { - return token; - } - - public void setToken(String token) { - this.token = token; - } - - - public V1DetokenizeRecordRequest redaction(RedactionEnumREDACTION redaction) { - this.redaction = redaction; - return this; - } - - /** - * Get redaction - * @return redaction - */ - @javax.annotation.Nullable - public RedactionEnumREDACTION getRedaction() { - return redaction; - } - - public void setRedaction(RedactionEnumREDACTION redaction) { - this.redaction = redaction; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1DetokenizeRecordRequest v1DetokenizeRecordRequest = (V1DetokenizeRecordRequest) o; - return Objects.equals(this.token, v1DetokenizeRecordRequest.token) && - Objects.equals(this.redaction, v1DetokenizeRecordRequest.redaction); - } - - @Override - public int hashCode() { - return Objects.hash(token, redaction); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1DetokenizeRecordRequest {\n"); - sb.append(" token: ").append(toIndentedString(token)).append("\n"); - sb.append(" redaction: ").append(toIndentedString(redaction)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("token"); - openapiFields.add("redaction"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1DetokenizeRecordRequest - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1DetokenizeRecordRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1DetokenizeRecordRequest is not found in the empty JSON string", V1DetokenizeRecordRequest.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1DetokenizeRecordRequest.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1DetokenizeRecordRequest` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("token") != null && !jsonObj.get("token").isJsonNull()) && !jsonObj.get("token").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `token` to be a primitive type in the JSON string but got `%s`", jsonObj.get("token").toString())); - } - // validate the optional field `redaction` - if (jsonObj.get("redaction") != null && !jsonObj.get("redaction").isJsonNull()) { - RedactionEnumREDACTION.validateJsonElement(jsonObj.get("redaction")); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1DetokenizeRecordRequest.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1DetokenizeRecordRequest' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1DetokenizeRecordRequest.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1DetokenizeRecordRequest value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1DetokenizeRecordRequest read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1DetokenizeRecordRequest given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1DetokenizeRecordRequest - * @throws IOException if the JSON string is invalid with respect to V1DetokenizeRecordRequest - */ - public static V1DetokenizeRecordRequest fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1DetokenizeRecordRequest.class); - } - - /** - * Convert an instance of V1DetokenizeRecordRequest to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java deleted file mode 100644 index 5c223793..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.DetokenizeRecordResponseValueType; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1DetokenizeRecordResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1DetokenizeRecordResponse { - public static final String SERIALIZED_NAME_TOKEN = "token"; - @SerializedName(SERIALIZED_NAME_TOKEN) - private String token; - - public static final String SERIALIZED_NAME_VALUE_TYPE = "valueType"; - @SerializedName(SERIALIZED_NAME_VALUE_TYPE) - private DetokenizeRecordResponseValueType valueType = DetokenizeRecordResponseValueType.NONE; - - public static final String SERIALIZED_NAME_VALUE = "value"; - @SerializedName(SERIALIZED_NAME_VALUE) - private String value; - - public static final String SERIALIZED_NAME_ERROR = "error"; - @SerializedName(SERIALIZED_NAME_ERROR) - private String error; - - public V1DetokenizeRecordResponse() { - } - - public V1DetokenizeRecordResponse token(String token) { - this.token = token; - return this; - } - - /** - * Token of the record. - * @return token - */ - @javax.annotation.Nullable - public String getToken() { - return token; - } - - public void setToken(String token) { - this.token = token; - } - - - public V1DetokenizeRecordResponse valueType(DetokenizeRecordResponseValueType valueType) { - this.valueType = valueType; - return this; - } - - /** - * Get valueType - * @return valueType - */ - @javax.annotation.Nullable - public DetokenizeRecordResponseValueType getValueType() { - return valueType; - } - - public void setValueType(DetokenizeRecordResponseValueType valueType) { - this.valueType = valueType; - } - - - public V1DetokenizeRecordResponse value(String value) { - this.value = value; - return this; - } - - /** - * Data corresponding to the token. - * @return value - */ - @javax.annotation.Nullable - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - - public V1DetokenizeRecordResponse error(String error) { - this.error = error; - return this; - } - - /** - * Error if token isn't found. - * @return error - */ - @javax.annotation.Nullable - public String getError() { - return error; - } - - public void setError(String error) { - this.error = error; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1DetokenizeRecordResponse v1DetokenizeRecordResponse = (V1DetokenizeRecordResponse) o; - return Objects.equals(this.token, v1DetokenizeRecordResponse.token) && - Objects.equals(this.valueType, v1DetokenizeRecordResponse.valueType) && - Objects.equals(this.value, v1DetokenizeRecordResponse.value) && - Objects.equals(this.error, v1DetokenizeRecordResponse.error); - } - - @Override - public int hashCode() { - return Objects.hash(token, valueType, value, error); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1DetokenizeRecordResponse {\n"); - sb.append(" token: ").append(toIndentedString(token)).append("\n"); - sb.append(" valueType: ").append(toIndentedString(valueType)).append("\n"); - sb.append(" value: ").append(toIndentedString(value)).append("\n"); - sb.append(" error: ").append(toIndentedString(error)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("token"); - openapiFields.add("valueType"); - openapiFields.add("value"); - openapiFields.add("error"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1DetokenizeRecordResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1DetokenizeRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1DetokenizeRecordResponse is not found in the empty JSON string", V1DetokenizeRecordResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1DetokenizeRecordResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1DetokenizeRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("token") != null && !jsonObj.get("token").isJsonNull()) && !jsonObj.get("token").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `token` to be a primitive type in the JSON string but got `%s`", jsonObj.get("token").toString())); - } - // validate the optional field `valueType` - if (jsonObj.get("valueType") != null && !jsonObj.get("valueType").isJsonNull()) { - DetokenizeRecordResponseValueType.validateJsonElement(jsonObj.get("valueType")); - } - if ((jsonObj.get("value") != null && !jsonObj.get("value").isJsonNull()) && !jsonObj.get("value").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `value` to be a primitive type in the JSON string but got `%s`", jsonObj.get("value").toString())); - } - if ((jsonObj.get("error") != null && !jsonObj.get("error").isJsonNull()) && !jsonObj.get("error").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `error` to be a primitive type in the JSON string but got `%s`", jsonObj.get("error").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1DetokenizeRecordResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1DetokenizeRecordResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1DetokenizeRecordResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1DetokenizeRecordResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1DetokenizeRecordResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1DetokenizeRecordResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1DetokenizeRecordResponse - * @throws IOException if the JSON string is invalid with respect to V1DetokenizeRecordResponse - */ - public static V1DetokenizeRecordResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1DetokenizeRecordResponse.class); - } - - /** - * Convert an instance of V1DetokenizeRecordResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java deleted file mode 100644 index ed996183..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1DetokenizeRecordResponse; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1DetokenizeResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1DetokenizeResponse { - public static final String SERIALIZED_NAME_RECORDS = "records"; - @SerializedName(SERIALIZED_NAME_RECORDS) - private List records = new ArrayList<>(); - - public V1DetokenizeResponse() { - } - - public V1DetokenizeResponse records(List records) { - this.records = records; - return this; - } - - public V1DetokenizeResponse addRecordsItem(V1DetokenizeRecordResponse recordsItem) { - if (this.records == null) { - this.records = new ArrayList<>(); - } - this.records.add(recordsItem); - return this; - } - - /** - * Records corresponding to the specified tokens. - * @return records - */ - @javax.annotation.Nullable - public List getRecords() { - return records; - } - - public void setRecords(List records) { - this.records = records; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1DetokenizeResponse v1DetokenizeResponse = (V1DetokenizeResponse) o; - return Objects.equals(this.records, v1DetokenizeResponse.records); - } - - @Override - public int hashCode() { - return Objects.hash(records); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1DetokenizeResponse {\n"); - sb.append(" records: ").append(toIndentedString(records)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("records"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1DetokenizeResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1DetokenizeResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1DetokenizeResponse is not found in the empty JSON string", V1DetokenizeResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1DetokenizeResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1DetokenizeResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { - JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); - if (jsonArrayrecords != null) { - // ensure the json data is an array - if (!jsonObj.get("records").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); - } - - // validate the optional field `records` (array) - for (int i = 0; i < jsonArrayrecords.size(); i++) { - V1DetokenizeRecordResponse.validateJsonElement(jsonArrayrecords.get(i)); - }; - } - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1DetokenizeResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1DetokenizeResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1DetokenizeResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1DetokenizeResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1DetokenizeResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1DetokenizeResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1DetokenizeResponse - * @throws IOException if the JSON string is invalid with respect to V1DetokenizeResponse - */ - public static V1DetokenizeResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1DetokenizeResponse.class); - } - - /** - * Convert an instance of V1DetokenizeResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java b/src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java deleted file mode 100644 index 9efada66..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * Record values and tokens. - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1FieldRecords { - public static final String SERIALIZED_NAME_FIELDS = "fields"; - @SerializedName(SERIALIZED_NAME_FIELDS) - private Object fields; - - public static final String SERIALIZED_NAME_TOKENS = "tokens"; - @SerializedName(SERIALIZED_NAME_TOKENS) - private Object tokens; - - public V1FieldRecords() { - } - - public V1FieldRecords fields(Object fields) { - this.fields = fields; - return this; - } - - /** - * Fields and values for the record. For example, `{'field_1':'value_1', 'field_2':'value_2'}`. - * @return fields - */ - @javax.annotation.Nullable - public Object getFields() { - return fields; - } - - public void setFields(Object fields) { - this.fields = fields; - } - - - public V1FieldRecords tokens(Object tokens) { - this.tokens = tokens; - return this; - } - - /** - * Fields and tokens for the record. For example, `{'field_1':'token_1', 'field_2':'token_2'}`. - * @return tokens - */ - @javax.annotation.Nullable - public Object getTokens() { - return tokens; - } - - public void setTokens(Object tokens) { - this.tokens = tokens; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1FieldRecords v1FieldRecords = (V1FieldRecords) o; - return Objects.equals(this.fields, v1FieldRecords.fields) && - Objects.equals(this.tokens, v1FieldRecords.tokens); - } - - @Override - public int hashCode() { - return Objects.hash(fields, tokens); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1FieldRecords {\n"); - sb.append(" fields: ").append(toIndentedString(fields)).append("\n"); - sb.append(" tokens: ").append(toIndentedString(tokens)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("fields"); - openapiFields.add("tokens"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1FieldRecords - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1FieldRecords.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1FieldRecords is not found in the empty JSON string", V1FieldRecords.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1FieldRecords.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1FieldRecords` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1FieldRecords.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1FieldRecords' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1FieldRecords.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1FieldRecords value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1FieldRecords read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1FieldRecords given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1FieldRecords - * @throws IOException if the JSON string is invalid with respect to V1FieldRecords - */ - public static V1FieldRecords fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1FieldRecords.class); - } - - /** - * Convert an instance of V1FieldRecords to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java b/src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java deleted file mode 100644 index af3f490f..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Anti-virus scan status of the file. - */ -@JsonAdapter(V1FileAVScanStatus.Adapter.class) -public enum V1FileAVScanStatus { - - NONE("SCAN_NONE"), - - CLEAN("SCAN_CLEAN"), - - INFECTED("SCAN_INFECTED"), - - DELETED("SCAN_DELETED"), - - ERROR("SCAN_ERROR"), - - PENDING("SCAN_PENDING"), - - UNSCANNABLE("SCAN_UNSCANNABLE"), - - FILE_NOT_FOUND("SCAN_FILE_NOT_FOUND"), - - INVALID("SCAN_INVALID"); - - private String value; - - V1FileAVScanStatus(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static V1FileAVScanStatus fromValue(String value) { - for (V1FileAVScanStatus b : V1FileAVScanStatus.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final V1FileAVScanStatus enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public V1FileAVScanStatus read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return V1FileAVScanStatus.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - V1FileAVScanStatus.fromValue(value); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java deleted file mode 100644 index c2d6bf1d..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Skyflow Management API - * # Management API This API controls aspects of your account and schema, including workspaces, vaults, keys, users, permissions, and more. The Management API is available from two base URIs:
  • Sandbox: https://manage.skyflowapis-preview.com
  • Production: https://manage.skyflowapis.com
When you make an API call, you need to add two headers:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
X-SKYFLOW-ACCOUNT-IDYour Skyflow account ID.X-SKYFLOW-ACCOUNT-ID: h451b763713e4424a7jke1bbkbbc84ef
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1GetAuthTokenRequest - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-10-03T10:28:16.037563+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1GetAuthTokenRequest { - public static final String SERIALIZED_NAME_GRANT_TYPE = "grant_type"; - @SerializedName(SERIALIZED_NAME_GRANT_TYPE) - private String grantType; - - public static final String SERIALIZED_NAME_ASSERTION = "assertion"; - @SerializedName(SERIALIZED_NAME_ASSERTION) - private String assertion; - - public static final String SERIALIZED_NAME_SUBJECT_TOKEN = "subject_token"; - @SerializedName(SERIALIZED_NAME_SUBJECT_TOKEN) - private String subjectToken; - - public static final String SERIALIZED_NAME_SUBJECT_TOKEN_TYPE = "subject_token_type"; - @SerializedName(SERIALIZED_NAME_SUBJECT_TOKEN_TYPE) - private String subjectTokenType; - - public static final String SERIALIZED_NAME_REQUESTED_TOKEN_USE = "requested_token_use"; - @SerializedName(SERIALIZED_NAME_REQUESTED_TOKEN_USE) - private String requestedTokenUse; - - public static final String SERIALIZED_NAME_SCOPE = "scope"; - @SerializedName(SERIALIZED_NAME_SCOPE) - private String scope; - - public V1GetAuthTokenRequest() { - } - - public V1GetAuthTokenRequest grantType(String grantType) { - this.grantType = grantType; - return this; - } - - /** - * Grant type of the request. Set this to `urn:ietf:params:oauth:grant-type:jwt-bearer`. - * @return grantType - */ - @javax.annotation.Nonnull - public String getGrantType() { - return grantType; - } - - public void setGrantType(String grantType) { - this.grantType = grantType; - } - - - public V1GetAuthTokenRequest assertion(String assertion) { - this.assertion = assertion; - return this; - } - - /** - * User-signed JWT token that contains the following fields: <br/> <ul><li><code>iss</code>: Issuer of the JWT.</li><li><code>key</code>: Unique identifier for the key.</li><li><code>aud</code>: Recipient the JWT is intended for.</li><li><code>exp</code>: Time the JWT expires.</li><li><code>sub</code>: Subject of the JWT.</li><li><code>ctx</code>: (Optional) Value for <a href='/context-aware-overview/'>Context-aware authorization</a>.</li></ul> - * @return assertion - */ - @javax.annotation.Nonnull - public String getAssertion() { - return assertion; - } - - public void setAssertion(String assertion) { - this.assertion = assertion; - } - - - public V1GetAuthTokenRequest subjectToken(String subjectToken) { - this.subjectToken = subjectToken; - return this; - } - - /** - * Subject token. - * @return subjectToken - */ - @javax.annotation.Nullable - public String getSubjectToken() { - return subjectToken; - } - - public void setSubjectToken(String subjectToken) { - this.subjectToken = subjectToken; - } - - - public V1GetAuthTokenRequest subjectTokenType(String subjectTokenType) { - this.subjectTokenType = subjectTokenType; - return this; - } - - /** - * Subject token type. - * @return subjectTokenType - */ - @javax.annotation.Nullable - public String getSubjectTokenType() { - return subjectTokenType; - } - - public void setSubjectTokenType(String subjectTokenType) { - this.subjectTokenType = subjectTokenType; - } - - - public V1GetAuthTokenRequest requestedTokenUse(String requestedTokenUse) { - this.requestedTokenUse = requestedTokenUse; - return this; - } - - /** - * Token use type. Either `delegation` or `impersonation`. - * @return requestedTokenUse - */ - @javax.annotation.Nullable - public String getRequestedTokenUse() { - return requestedTokenUse; - } - - public void setRequestedTokenUse(String requestedTokenUse) { - this.requestedTokenUse = requestedTokenUse; - } - - - public V1GetAuthTokenRequest scope(String scope) { - this.scope = scope; - return this; - } - - /** - * Subset of available <a href='#Roles'>roles</a> to associate with the requested token. Uses the format \"role:\\<roleID1\\> role:\\<roleID2\\>\". - * @return scope - */ - @javax.annotation.Nullable - public String getScope() { - return scope; - } - - public void setScope(String scope) { - this.scope = scope; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1GetAuthTokenRequest v1GetAuthTokenRequest = (V1GetAuthTokenRequest) o; - return Objects.equals(this.grantType, v1GetAuthTokenRequest.grantType) && - Objects.equals(this.assertion, v1GetAuthTokenRequest.assertion) && - Objects.equals(this.subjectToken, v1GetAuthTokenRequest.subjectToken) && - Objects.equals(this.subjectTokenType, v1GetAuthTokenRequest.subjectTokenType) && - Objects.equals(this.requestedTokenUse, v1GetAuthTokenRequest.requestedTokenUse) && - Objects.equals(this.scope, v1GetAuthTokenRequest.scope); - } - - @Override - public int hashCode() { - return Objects.hash(grantType, assertion, subjectToken, subjectTokenType, requestedTokenUse, scope); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1GetAuthTokenRequest {\n"); - sb.append(" grantType: ").append(toIndentedString(grantType)).append("\n"); - sb.append(" assertion: ").append(toIndentedString(assertion)).append("\n"); - sb.append(" subjectToken: ").append(toIndentedString(subjectToken)).append("\n"); - sb.append(" subjectTokenType: ").append(toIndentedString(subjectTokenType)).append("\n"); - sb.append(" requestedTokenUse: ").append(toIndentedString(requestedTokenUse)).append("\n"); - sb.append(" scope: ").append(toIndentedString(scope)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("grant_type"); - openapiFields.add("assertion"); - openapiFields.add("subject_token"); - openapiFields.add("subject_token_type"); - openapiFields.add("requested_token_use"); - openapiFields.add("scope"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("grant_type"); - openapiRequiredFields.add("assertion"); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1GetAuthTokenRequest - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1GetAuthTokenRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1GetAuthTokenRequest is not found in the empty JSON string", V1GetAuthTokenRequest.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1GetAuthTokenRequest.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1GetAuthTokenRequest` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : V1GetAuthTokenRequest.openapiRequiredFields) { - if (jsonElement.getAsJsonObject().get(requiredField) == null) { - throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (!jsonObj.get("grant_type").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `grant_type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("grant_type").toString())); - } - if (!jsonObj.get("assertion").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `assertion` to be a primitive type in the JSON string but got `%s`", jsonObj.get("assertion").toString())); - } - if ((jsonObj.get("subject_token") != null && !jsonObj.get("subject_token").isJsonNull()) && !jsonObj.get("subject_token").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `subject_token` to be a primitive type in the JSON string but got `%s`", jsonObj.get("subject_token").toString())); - } - if ((jsonObj.get("subject_token_type") != null && !jsonObj.get("subject_token_type").isJsonNull()) && !jsonObj.get("subject_token_type").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `subject_token_type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("subject_token_type").toString())); - } - if ((jsonObj.get("requested_token_use") != null && !jsonObj.get("requested_token_use").isJsonNull()) && !jsonObj.get("requested_token_use").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `requested_token_use` to be a primitive type in the JSON string but got `%s`", jsonObj.get("requested_token_use").toString())); - } - if ((jsonObj.get("scope") != null && !jsonObj.get("scope").isJsonNull()) && !jsonObj.get("scope").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `scope` to be a primitive type in the JSON string but got `%s`", jsonObj.get("scope").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1GetAuthTokenRequest.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1GetAuthTokenRequest' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1GetAuthTokenRequest.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1GetAuthTokenRequest value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1GetAuthTokenRequest read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1GetAuthTokenRequest given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1GetAuthTokenRequest - * @throws IOException if the JSON string is invalid with respect to V1GetAuthTokenRequest - */ - public static V1GetAuthTokenRequest fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1GetAuthTokenRequest.class); - } - - /** - * Convert an instance of V1GetAuthTokenRequest to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java deleted file mode 100644 index d6c0f61f..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Skyflow Management API - * # Management API This API controls aspects of your account and schema, including workspaces, vaults, keys, users, permissions, and more. The Management API is available from two base URIs:
  • Sandbox: https://manage.skyflowapis-preview.com
  • Production: https://manage.skyflowapis.com
When you make an API call, you need to add two headers:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
X-SKYFLOW-ACCOUNT-IDYour Skyflow account ID.X-SKYFLOW-ACCOUNT-ID: h451b763713e4424a7jke1bbkbbc84ef
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1GetAuthTokenResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-10-03T10:28:16.037563+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1GetAuthTokenResponse { - public static final String SERIALIZED_NAME_ACCESS_TOKEN = "accessToken"; - @SerializedName(SERIALIZED_NAME_ACCESS_TOKEN) - private String accessToken; - - public static final String SERIALIZED_NAME_TOKEN_TYPE = "tokenType"; - @SerializedName(SERIALIZED_NAME_TOKEN_TYPE) - private String tokenType; - - public V1GetAuthTokenResponse() { - } - - public V1GetAuthTokenResponse accessToken(String accessToken) { - this.accessToken = accessToken; - return this; - } - - /** - * AccessToken. - * @return accessToken - */ - @javax.annotation.Nullable - public String getAccessToken() { - return accessToken; - } - - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - - public V1GetAuthTokenResponse tokenType(String tokenType) { - this.tokenType = tokenType; - return this; - } - - /** - * TokenType : Bearer. - * @return tokenType - */ - @javax.annotation.Nullable - public String getTokenType() { - return tokenType; - } - - public void setTokenType(String tokenType) { - this.tokenType = tokenType; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1GetAuthTokenResponse v1GetAuthTokenResponse = (V1GetAuthTokenResponse) o; - return Objects.equals(this.accessToken, v1GetAuthTokenResponse.accessToken) && - Objects.equals(this.tokenType, v1GetAuthTokenResponse.tokenType); - } - - @Override - public int hashCode() { - return Objects.hash(accessToken, tokenType); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1GetAuthTokenResponse {\n"); - sb.append(" accessToken: ").append(toIndentedString(accessToken)).append("\n"); - sb.append(" tokenType: ").append(toIndentedString(tokenType)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("accessToken"); - openapiFields.add("tokenType"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1GetAuthTokenResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1GetAuthTokenResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1GetAuthTokenResponse is not found in the empty JSON string", V1GetAuthTokenResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1GetAuthTokenResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1GetAuthTokenResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("accessToken") != null && !jsonObj.get("accessToken").isJsonNull()) && !jsonObj.get("accessToken").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `accessToken` to be a primitive type in the JSON string but got `%s`", jsonObj.get("accessToken").toString())); - } - if ((jsonObj.get("tokenType") != null && !jsonObj.get("tokenType").isJsonNull()) && !jsonObj.get("tokenType").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `tokenType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("tokenType").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1GetAuthTokenResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1GetAuthTokenResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1GetAuthTokenResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1GetAuthTokenResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1GetAuthTokenResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1GetAuthTokenResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1GetAuthTokenResponse - * @throws IOException if the JSON string is invalid with respect to V1GetAuthTokenResponse - */ - public static V1GetAuthTokenResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1GetAuthTokenResponse.class); - } - - /** - * Convert an instance of V1GetAuthTokenResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java deleted file mode 100644 index 4bce5d74..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1FileAVScanStatus; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1GetFileScanStatusResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1GetFileScanStatusResponse { - public static final String SERIALIZED_NAME_AV_SCAN_STATUS = "av_scan_status"; - @SerializedName(SERIALIZED_NAME_AV_SCAN_STATUS) - private V1FileAVScanStatus avScanStatus = V1FileAVScanStatus.NONE; - - public V1GetFileScanStatusResponse() { - } - - public V1GetFileScanStatusResponse avScanStatus(V1FileAVScanStatus avScanStatus) { - this.avScanStatus = avScanStatus; - return this; - } - - /** - * Get avScanStatus - * @return avScanStatus - */ - @javax.annotation.Nullable - public V1FileAVScanStatus getAvScanStatus() { - return avScanStatus; - } - - public void setAvScanStatus(V1FileAVScanStatus avScanStatus) { - this.avScanStatus = avScanStatus; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1GetFileScanStatusResponse v1GetFileScanStatusResponse = (V1GetFileScanStatusResponse) o; - return Objects.equals(this.avScanStatus, v1GetFileScanStatusResponse.avScanStatus); - } - - @Override - public int hashCode() { - return Objects.hash(avScanStatus); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1GetFileScanStatusResponse {\n"); - sb.append(" avScanStatus: ").append(toIndentedString(avScanStatus)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("av_scan_status"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1GetFileScanStatusResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1GetFileScanStatusResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1GetFileScanStatusResponse is not found in the empty JSON string", V1GetFileScanStatusResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1GetFileScanStatusResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1GetFileScanStatusResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - // validate the optional field `av_scan_status` - if (jsonObj.get("av_scan_status") != null && !jsonObj.get("av_scan_status").isJsonNull()) { - V1FileAVScanStatus.validateJsonElement(jsonObj.get("av_scan_status")); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1GetFileScanStatusResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1GetFileScanStatusResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1GetFileScanStatusResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1GetFileScanStatusResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1GetFileScanStatusResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1GetFileScanStatusResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1GetFileScanStatusResponse - * @throws IOException if the JSON string is invalid with respect to V1GetFileScanStatusResponse - */ - public static V1GetFileScanStatusResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1GetFileScanStatusResponse.class); - } - - /** - * Convert an instance of V1GetFileScanStatusResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java deleted file mode 100644 index 2ff57e57..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1FieldRecords; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1GetQueryResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1GetQueryResponse { - public static final String SERIALIZED_NAME_RECORDS = "records"; - @SerializedName(SERIALIZED_NAME_RECORDS) - private List records = new ArrayList<>(); - - public V1GetQueryResponse() { - } - - public V1GetQueryResponse records(List records) { - this.records = records; - return this; - } - - public V1GetQueryResponse addRecordsItem(V1FieldRecords recordsItem) { - if (this.records == null) { - this.records = new ArrayList<>(); - } - this.records.add(recordsItem); - return this; - } - - /** - * Records returned by the query. - * @return records - */ - @javax.annotation.Nullable - public List getRecords() { - return records; - } - - public void setRecords(List records) { - this.records = records; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1GetQueryResponse v1GetQueryResponse = (V1GetQueryResponse) o; - return Objects.equals(this.records, v1GetQueryResponse.records); - } - - @Override - public int hashCode() { - return Objects.hash(records); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1GetQueryResponse {\n"); - sb.append(" records: ").append(toIndentedString(records)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("records"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1GetQueryResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1GetQueryResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1GetQueryResponse is not found in the empty JSON string", V1GetQueryResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1GetQueryResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1GetQueryResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { - JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); - if (jsonArrayrecords != null) { - // ensure the json data is an array - if (!jsonObj.get("records").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); - } - - // validate the optional field `records` (array) - for (int i = 0; i < jsonArrayrecords.size(); i++) { - V1FieldRecords.validateJsonElement(jsonArrayrecords.get(i)); - }; - } - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1GetQueryResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1GetQueryResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1GetQueryResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1GetQueryResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1GetQueryResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1GetQueryResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1GetQueryResponse - * @throws IOException if the JSON string is invalid with respect to V1GetQueryResponse - */ - public static V1GetQueryResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1GetQueryResponse.class); - } - - /** - * Convert an instance of V1GetQueryResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java deleted file mode 100644 index f4f432b3..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1RecordMetaProperties; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1InsertRecordResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1InsertRecordResponse { - public static final String SERIALIZED_NAME_RECORDS = "records"; - @SerializedName(SERIALIZED_NAME_RECORDS) - private List records = new ArrayList<>(); - - public V1InsertRecordResponse() { - } - - public V1InsertRecordResponse records(List records) { - this.records = records; - return this; - } - - public V1InsertRecordResponse addRecordsItem(V1RecordMetaProperties recordsItem) { - if (this.records == null) { - this.records = new ArrayList<>(); - } - this.records.add(recordsItem); - return this; - } - - /** - * Identifiers for the inserted records. - * @return records - */ - @javax.annotation.Nullable - public List getRecords() { - return records; - } - - public void setRecords(List records) { - this.records = records; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1InsertRecordResponse v1InsertRecordResponse = (V1InsertRecordResponse) o; - return Objects.equals(this.records, v1InsertRecordResponse.records); - } - - @Override - public int hashCode() { - return Objects.hash(records); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1InsertRecordResponse {\n"); - sb.append(" records: ").append(toIndentedString(records)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("records"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1InsertRecordResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1InsertRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1InsertRecordResponse is not found in the empty JSON string", V1InsertRecordResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1InsertRecordResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1InsertRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { - JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); - if (jsonArrayrecords != null) { - // ensure the json data is an array - if (!jsonObj.get("records").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); - } - - // validate the optional field `records` (array) - for (int i = 0; i < jsonArrayrecords.size(); i++) { - V1RecordMetaProperties.validateJsonElement(jsonArrayrecords.get(i)); - }; - } - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1InsertRecordResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1InsertRecordResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1InsertRecordResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1InsertRecordResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1InsertRecordResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1InsertRecordResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1InsertRecordResponse - * @throws IOException if the JSON string is invalid with respect to V1InsertRecordResponse - */ - public static V1InsertRecordResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1InsertRecordResponse.class); - } - - /** - * Convert an instance of V1InsertRecordResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1MemberType.java b/src/main/java/com/skyflow/generated/rest/models/V1MemberType.java deleted file mode 100644 index 5cb1ce8b..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1MemberType.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.annotations.SerializedName; - -import java.io.IOException; -import com.google.gson.TypeAdapter; -import com.google.gson.JsonElement; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -/** - * Type of the member. - */ -@JsonAdapter(V1MemberType.Adapter.class) -public enum V1MemberType { - - NONE("NONE"), - - USER("USER"), - - SERVICE_ACCOUNT("SERVICE_ACCOUNT"); - - private String value; - - V1MemberType(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - public static V1MemberType fromValue(String value) { - for (V1MemberType b : V1MemberType.values()) { - if (b.value.equals(value)) { - return b; - } - } - throw new IllegalArgumentException("Unexpected value '" + value + "'"); - } - - public static class Adapter extends TypeAdapter { - @Override - public void write(final JsonWriter jsonWriter, final V1MemberType enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); - } - - @Override - public V1MemberType read(final JsonReader jsonReader) throws IOException { - String value = jsonReader.nextString(); - return V1MemberType.fromValue(value); - } - } - - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - String value = jsonElement.getAsString(); - V1MemberType.fromValue(value); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java b/src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java deleted file mode 100644 index e0aaf47e..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1RecordMetaProperties - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1RecordMetaProperties { - public static final String SERIALIZED_NAME_SKYFLOW_ID = "skyflow_id"; - @SerializedName(SERIALIZED_NAME_SKYFLOW_ID) - private String skyflowId; - - public static final String SERIALIZED_NAME_TOKENS = "tokens"; - @SerializedName(SERIALIZED_NAME_TOKENS) - private Object tokens; - - public V1RecordMetaProperties() { - } - - public V1RecordMetaProperties skyflowId(String skyflowId) { - this.skyflowId = skyflowId; - return this; - } - - /** - * ID of the inserted record. - * @return skyflowId - */ - @javax.annotation.Nullable - public String getSkyflowId() { - return skyflowId; - } - - public void setSkyflowId(String skyflowId) { - this.skyflowId = skyflowId; - } - - - public V1RecordMetaProperties tokens(Object tokens) { - this.tokens = tokens; - return this; - } - - /** - * Tokens for the record. - * @return tokens - */ - @javax.annotation.Nullable - public Object getTokens() { - return tokens; - } - - public void setTokens(Object tokens) { - this.tokens = tokens; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1RecordMetaProperties v1RecordMetaProperties = (V1RecordMetaProperties) o; - return Objects.equals(this.skyflowId, v1RecordMetaProperties.skyflowId) && - Objects.equals(this.tokens, v1RecordMetaProperties.tokens); - } - - @Override - public int hashCode() { - return Objects.hash(skyflowId, tokens); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1RecordMetaProperties {\n"); - sb.append(" skyflowId: ").append(toIndentedString(skyflowId)).append("\n"); - sb.append(" tokens: ").append(toIndentedString(tokens)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("skyflow_id"); - openapiFields.add("tokens"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1RecordMetaProperties - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1RecordMetaProperties.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1RecordMetaProperties is not found in the empty JSON string", V1RecordMetaProperties.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1RecordMetaProperties.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1RecordMetaProperties` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("skyflow_id") != null && !jsonObj.get("skyflow_id").isJsonNull()) && !jsonObj.get("skyflow_id").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `skyflow_id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("skyflow_id").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1RecordMetaProperties.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1RecordMetaProperties' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1RecordMetaProperties.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1RecordMetaProperties value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1RecordMetaProperties read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1RecordMetaProperties given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1RecordMetaProperties - * @throws IOException if the JSON string is invalid with respect to V1RecordMetaProperties - */ - public static V1RecordMetaProperties fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1RecordMetaProperties.class); - } - - /** - * Convert an instance of V1RecordMetaProperties to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java b/src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java deleted file mode 100644 index 74936451..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1TokenizeRecordRequest; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1TokenizePayload - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1TokenizePayload { - public static final String SERIALIZED_NAME_TOKENIZATION_PARAMETERS = "tokenizationParameters"; - @SerializedName(SERIALIZED_NAME_TOKENIZATION_PARAMETERS) - private List tokenizationParameters = new ArrayList<>(); - - public V1TokenizePayload() { - } - - public V1TokenizePayload tokenizationParameters(List tokenizationParameters) { - this.tokenizationParameters = tokenizationParameters; - return this; - } - - public V1TokenizePayload addTokenizationParametersItem(V1TokenizeRecordRequest tokenizationParametersItem) { - if (this.tokenizationParameters == null) { - this.tokenizationParameters = new ArrayList<>(); - } - this.tokenizationParameters.add(tokenizationParametersItem); - return this; - } - - /** - * Tokenization details. - * @return tokenizationParameters - */ - @javax.annotation.Nullable - public List getTokenizationParameters() { - return tokenizationParameters; - } - - public void setTokenizationParameters(List tokenizationParameters) { - this.tokenizationParameters = tokenizationParameters; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1TokenizePayload v1TokenizePayload = (V1TokenizePayload) o; - return Objects.equals(this.tokenizationParameters, v1TokenizePayload.tokenizationParameters); - } - - @Override - public int hashCode() { - return Objects.hash(tokenizationParameters); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1TokenizePayload {\n"); - sb.append(" tokenizationParameters: ").append(toIndentedString(tokenizationParameters)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("tokenizationParameters"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1TokenizePayload - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1TokenizePayload.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1TokenizePayload is not found in the empty JSON string", V1TokenizePayload.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1TokenizePayload.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1TokenizePayload` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("tokenizationParameters") != null && !jsonObj.get("tokenizationParameters").isJsonNull()) { - JsonArray jsonArraytokenizationParameters = jsonObj.getAsJsonArray("tokenizationParameters"); - if (jsonArraytokenizationParameters != null) { - // ensure the json data is an array - if (!jsonObj.get("tokenizationParameters").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `tokenizationParameters` to be an array in the JSON string but got `%s`", jsonObj.get("tokenizationParameters").toString())); - } - - // validate the optional field `tokenizationParameters` (array) - for (int i = 0; i < jsonArraytokenizationParameters.size(); i++) { - V1TokenizeRecordRequest.validateJsonElement(jsonArraytokenizationParameters.get(i)); - }; - } - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1TokenizePayload.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1TokenizePayload' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1TokenizePayload.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1TokenizePayload value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1TokenizePayload read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1TokenizePayload given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1TokenizePayload - * @throws IOException if the JSON string is invalid with respect to V1TokenizePayload - */ - public static V1TokenizePayload fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1TokenizePayload.class); - } - - /** - * Convert an instance of V1TokenizePayload to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java deleted file mode 100644 index 1de790c5..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1TokenizeRecordRequest - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1TokenizeRecordRequest { - public static final String SERIALIZED_NAME_VALUE = "value"; - @SerializedName(SERIALIZED_NAME_VALUE) - private String value; - - public static final String SERIALIZED_NAME_COLUMN_GROUP = "columnGroup"; - @SerializedName(SERIALIZED_NAME_COLUMN_GROUP) - private String columnGroup; - - public V1TokenizeRecordRequest() { - } - - public V1TokenizeRecordRequest value(String value) { - this.value = value; - return this; - } - - /** - * Existing value to return a token for. - * @return value - */ - @javax.annotation.Nullable - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - - public V1TokenizeRecordRequest columnGroup(String columnGroup) { - this.columnGroup = columnGroup; - return this; - } - - /** - * Name of the column group that the value belongs to. - * @return columnGroup - */ - @javax.annotation.Nullable - public String getColumnGroup() { - return columnGroup; - } - - public void setColumnGroup(String columnGroup) { - this.columnGroup = columnGroup; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1TokenizeRecordRequest v1TokenizeRecordRequest = (V1TokenizeRecordRequest) o; - return Objects.equals(this.value, v1TokenizeRecordRequest.value) && - Objects.equals(this.columnGroup, v1TokenizeRecordRequest.columnGroup); - } - - @Override - public int hashCode() { - return Objects.hash(value, columnGroup); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1TokenizeRecordRequest {\n"); - sb.append(" value: ").append(toIndentedString(value)).append("\n"); - sb.append(" columnGroup: ").append(toIndentedString(columnGroup)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("value"); - openapiFields.add("columnGroup"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1TokenizeRecordRequest - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1TokenizeRecordRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1TokenizeRecordRequest is not found in the empty JSON string", V1TokenizeRecordRequest.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1TokenizeRecordRequest.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1TokenizeRecordRequest` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("value") != null && !jsonObj.get("value").isJsonNull()) && !jsonObj.get("value").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `value` to be a primitive type in the JSON string but got `%s`", jsonObj.get("value").toString())); - } - if ((jsonObj.get("columnGroup") != null && !jsonObj.get("columnGroup").isJsonNull()) && !jsonObj.get("columnGroup").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `columnGroup` to be a primitive type in the JSON string but got `%s`", jsonObj.get("columnGroup").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1TokenizeRecordRequest.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1TokenizeRecordRequest' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1TokenizeRecordRequest.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1TokenizeRecordRequest value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1TokenizeRecordRequest read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1TokenizeRecordRequest given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1TokenizeRecordRequest - * @throws IOException if the JSON string is invalid with respect to V1TokenizeRecordRequest - */ - public static V1TokenizeRecordRequest fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1TokenizeRecordRequest.class); - } - - /** - * Convert an instance of V1TokenizeRecordRequest to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java deleted file mode 100644 index 290d7403..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1TokenizeRecordResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1TokenizeRecordResponse { - public static final String SERIALIZED_NAME_TOKEN = "token"; - @SerializedName(SERIALIZED_NAME_TOKEN) - private String token; - - public V1TokenizeRecordResponse() { - } - - public V1TokenizeRecordResponse token(String token) { - this.token = token; - return this; - } - - /** - * Token corresponding to a value. - * @return token - */ - @javax.annotation.Nullable - public String getToken() { - return token; - } - - public void setToken(String token) { - this.token = token; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1TokenizeRecordResponse v1TokenizeRecordResponse = (V1TokenizeRecordResponse) o; - return Objects.equals(this.token, v1TokenizeRecordResponse.token); - } - - @Override - public int hashCode() { - return Objects.hash(token); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1TokenizeRecordResponse {\n"); - sb.append(" token: ").append(toIndentedString(token)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("token"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1TokenizeRecordResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1TokenizeRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1TokenizeRecordResponse is not found in the empty JSON string", V1TokenizeRecordResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1TokenizeRecordResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1TokenizeRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("token") != null && !jsonObj.get("token").isJsonNull()) && !jsonObj.get("token").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `token` to be a primitive type in the JSON string but got `%s`", jsonObj.get("token").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1TokenizeRecordResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1TokenizeRecordResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1TokenizeRecordResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1TokenizeRecordResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1TokenizeRecordResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1TokenizeRecordResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1TokenizeRecordResponse - * @throws IOException if the JSON string is invalid with respect to V1TokenizeRecordResponse - */ - public static V1TokenizeRecordResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1TokenizeRecordResponse.class); - } - - /** - * Convert an instance of V1TokenizeRecordResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java deleted file mode 100644 index 3885c9a5..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1TokenizeRecordResponse; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1TokenizeResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1TokenizeResponse { - public static final String SERIALIZED_NAME_RECORDS = "records"; - @SerializedName(SERIALIZED_NAME_RECORDS) - private List records = new ArrayList<>(); - - public V1TokenizeResponse() { - } - - public V1TokenizeResponse records(List records) { - this.records = records; - return this; - } - - public V1TokenizeResponse addRecordsItem(V1TokenizeRecordResponse recordsItem) { - if (this.records == null) { - this.records = new ArrayList<>(); - } - this.records.add(recordsItem); - return this; - } - - /** - * Tokens corresponding to the specified values. - * @return records - */ - @javax.annotation.Nullable - public List getRecords() { - return records; - } - - public void setRecords(List records) { - this.records = records; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1TokenizeResponse v1TokenizeResponse = (V1TokenizeResponse) o; - return Objects.equals(this.records, v1TokenizeResponse.records); - } - - @Override - public int hashCode() { - return Objects.hash(records); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1TokenizeResponse {\n"); - sb.append(" records: ").append(toIndentedString(records)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("records"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1TokenizeResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1TokenizeResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1TokenizeResponse is not found in the empty JSON string", V1TokenizeResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1TokenizeResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1TokenizeResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if (jsonObj.get("records") != null && !jsonObj.get("records").isJsonNull()) { - JsonArray jsonArrayrecords = jsonObj.getAsJsonArray("records"); - if (jsonArrayrecords != null) { - // ensure the json data is an array - if (!jsonObj.get("records").isJsonArray()) { - throw new IllegalArgumentException(String.format("Expected the field `records` to be an array in the JSON string but got `%s`", jsonObj.get("records").toString())); - } - - // validate the optional field `records` (array) - for (int i = 0; i < jsonArrayrecords.size(); i++) { - V1TokenizeRecordResponse.validateJsonElement(jsonArrayrecords.get(i)); - }; - } - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1TokenizeResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1TokenizeResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1TokenizeResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1TokenizeResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1TokenizeResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1TokenizeResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1TokenizeResponse - * @throws IOException if the JSON string is invalid with respect to V1TokenizeResponse - */ - public static V1TokenizeResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1TokenizeResponse.class); - } - - /** - * Convert an instance of V1TokenizeResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java deleted file mode 100644 index b731dd12..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * V1UpdateRecordResponse - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1UpdateRecordResponse { - public static final String SERIALIZED_NAME_SKYFLOW_ID = "skyflow_id"; - @SerializedName(SERIALIZED_NAME_SKYFLOW_ID) - private String skyflowId; - - public static final String SERIALIZED_NAME_TOKENS = "tokens"; - @SerializedName(SERIALIZED_NAME_TOKENS) - private Object tokens; - - public V1UpdateRecordResponse() { - } - - public V1UpdateRecordResponse skyflowId(String skyflowId) { - this.skyflowId = skyflowId; - return this; - } - - /** - * ID of the updated record. - * @return skyflowId - */ - @javax.annotation.Nullable - public String getSkyflowId() { - return skyflowId; - } - - public void setSkyflowId(String skyflowId) { - this.skyflowId = skyflowId; - } - - - public V1UpdateRecordResponse tokens(Object tokens) { - this.tokens = tokens; - return this; - } - - /** - * Tokens for the record. - * @return tokens - */ - @javax.annotation.Nullable - public Object getTokens() { - return tokens; - } - - public void setTokens(Object tokens) { - this.tokens = tokens; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1UpdateRecordResponse v1UpdateRecordResponse = (V1UpdateRecordResponse) o; - return Objects.equals(this.skyflowId, v1UpdateRecordResponse.skyflowId) && - Objects.equals(this.tokens, v1UpdateRecordResponse.tokens); - } - - @Override - public int hashCode() { - return Objects.hash(skyflowId, tokens); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1UpdateRecordResponse {\n"); - sb.append(" skyflowId: ").append(toIndentedString(skyflowId)).append("\n"); - sb.append(" tokens: ").append(toIndentedString(tokens)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("skyflow_id"); - openapiFields.add("tokens"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1UpdateRecordResponse - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1UpdateRecordResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1UpdateRecordResponse is not found in the empty JSON string", V1UpdateRecordResponse.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1UpdateRecordResponse.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1UpdateRecordResponse` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("skyflow_id") != null && !jsonObj.get("skyflow_id").isJsonNull()) && !jsonObj.get("skyflow_id").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `skyflow_id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("skyflow_id").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1UpdateRecordResponse.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1UpdateRecordResponse' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1UpdateRecordResponse.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1UpdateRecordResponse value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1UpdateRecordResponse read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1UpdateRecordResponse given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1UpdateRecordResponse - * @throws IOException if the JSON string is invalid with respect to V1UpdateRecordResponse - */ - public static V1UpdateRecordResponse fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1UpdateRecordResponse.class); - } - - /** - * Convert an instance of V1UpdateRecordResponse to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java b/src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java deleted file mode 100644 index 582a53fd..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * Mapping of the fields in the vault to the fields to use for the lookup. - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1VaultFieldMapping { - public static final String SERIALIZED_NAME_CARD_NUMBER = "card_number"; - @SerializedName(SERIALIZED_NAME_CARD_NUMBER) - private String cardNumber; - - public static final String SERIALIZED_NAME_CARD_LAST_FOUR_DIGITS = "card_last_four_digits"; - @SerializedName(SERIALIZED_NAME_CARD_LAST_FOUR_DIGITS) - private String cardLastFourDigits; - - public static final String SERIALIZED_NAME_CARD_EXPIRY = "card_expiry"; - @SerializedName(SERIALIZED_NAME_CARD_EXPIRY) - private String cardExpiry; - - public V1VaultFieldMapping() { - } - - public V1VaultFieldMapping cardNumber(String cardNumber) { - this.cardNumber = cardNumber; - return this; - } - - /** - * Name of the column that stores the card number. - * @return cardNumber - */ - @javax.annotation.Nullable - public String getCardNumber() { - return cardNumber; - } - - public void setCardNumber(String cardNumber) { - this.cardNumber = cardNumber; - } - - - public V1VaultFieldMapping cardLastFourDigits(String cardLastFourDigits) { - this.cardLastFourDigits = cardLastFourDigits; - return this; - } - - /** - * Name of the column that stores the card number suffix. - * @return cardLastFourDigits - */ - @javax.annotation.Nullable - public String getCardLastFourDigits() { - return cardLastFourDigits; - } - - public void setCardLastFourDigits(String cardLastFourDigits) { - this.cardLastFourDigits = cardLastFourDigits; - } - - - public V1VaultFieldMapping cardExpiry(String cardExpiry) { - this.cardExpiry = cardExpiry; - return this; - } - - /** - * Name of the column that stores the expiry date. - * @return cardExpiry - */ - @javax.annotation.Nullable - public String getCardExpiry() { - return cardExpiry; - } - - public void setCardExpiry(String cardExpiry) { - this.cardExpiry = cardExpiry; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1VaultFieldMapping v1VaultFieldMapping = (V1VaultFieldMapping) o; - return Objects.equals(this.cardNumber, v1VaultFieldMapping.cardNumber) && - Objects.equals(this.cardLastFourDigits, v1VaultFieldMapping.cardLastFourDigits) && - Objects.equals(this.cardExpiry, v1VaultFieldMapping.cardExpiry); - } - - @Override - public int hashCode() { - return Objects.hash(cardNumber, cardLastFourDigits, cardExpiry); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1VaultFieldMapping {\n"); - sb.append(" cardNumber: ").append(toIndentedString(cardNumber)).append("\n"); - sb.append(" cardLastFourDigits: ").append(toIndentedString(cardLastFourDigits)).append("\n"); - sb.append(" cardExpiry: ").append(toIndentedString(cardExpiry)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("card_number"); - openapiFields.add("card_last_four_digits"); - openapiFields.add("card_expiry"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1VaultFieldMapping - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1VaultFieldMapping.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1VaultFieldMapping is not found in the empty JSON string", V1VaultFieldMapping.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1VaultFieldMapping.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1VaultFieldMapping` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("card_number") != null && !jsonObj.get("card_number").isJsonNull()) && !jsonObj.get("card_number").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `card_number` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_number").toString())); - } - if ((jsonObj.get("card_last_four_digits") != null && !jsonObj.get("card_last_four_digits").isJsonNull()) && !jsonObj.get("card_last_four_digits").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `card_last_four_digits` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_last_four_digits").toString())); - } - if ((jsonObj.get("card_expiry") != null && !jsonObj.get("card_expiry").isJsonNull()) && !jsonObj.get("card_expiry").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `card_expiry` to be a primitive type in the JSON string but got `%s`", jsonObj.get("card_expiry").toString())); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1VaultFieldMapping.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1VaultFieldMapping' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1VaultFieldMapping.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1VaultFieldMapping value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1VaultFieldMapping read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1VaultFieldMapping given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1VaultFieldMapping - * @throws IOException if the JSON string is invalid with respect to V1VaultFieldMapping - */ - public static V1VaultFieldMapping fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1VaultFieldMapping.class); - } - - /** - * Convert an instance of V1VaultFieldMapping to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java b/src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java deleted file mode 100644 index 58ac97ef..00000000 --- a/src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Skyflow Data API - * # Data API This API inserts, retrieves, and otherwise manages data in a vault. The Data API is available from two base URIs. *identifier* is the identifier in your vault's URL.
  • Sandbox: https://_*identifier*.vault.skyflowapis-preview.com
  • Production: https://_*identifier*.vault.skyflowapis.com
When you make an API call, you need to add a header:
HeaderValueExample
AuthorizationA Bearer Token. See API Authentication.Authorization: Bearer eyJhbGciOiJSUzI...1NiIsJdfPA
- * - * The version of the OpenAPI document: v1 - * Contact: support@skyflow.com - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - - -package com.skyflow.generated.rest.models; - -import java.util.Objects; -import com.google.gson.TypeAdapter; -import com.google.gson.annotations.JsonAdapter; -import com.google.gson.annotations.SerializedName; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.skyflow.generated.rest.models.V1VaultFieldMapping; -import java.io.IOException; -import java.util.Arrays; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.skyflow.generated.rest.JSON; - -/** - * Details of the vault that stores additional card details. - */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2024-09-25T11:34:22.684345+05:30[Asia/Kolkata]", comments = "Generator version: 7.8.0") -public class V1VaultSchemaConfig { - public static final String SERIALIZED_NAME_ID = "id"; - @SerializedName(SERIALIZED_NAME_ID) - private String id; - - public static final String SERIALIZED_NAME_TABLE_NAME = "table_name"; - @SerializedName(SERIALIZED_NAME_TABLE_NAME) - private String tableName; - - public static final String SERIALIZED_NAME_MAPPING = "mapping"; - @SerializedName(SERIALIZED_NAME_MAPPING) - private V1VaultFieldMapping mapping; - - public V1VaultSchemaConfig() { - } - - public V1VaultSchemaConfig id(String id) { - this.id = id; - return this; - } - - /** - * ID of the vault that stores card details. - * @return id - */ - @javax.annotation.Nullable - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - - public V1VaultSchemaConfig tableName(String tableName) { - this.tableName = tableName; - return this; - } - - /** - * Name of the table that stores card details. - * @return tableName - */ - @javax.annotation.Nullable - public String getTableName() { - return tableName; - } - - public void setTableName(String tableName) { - this.tableName = tableName; - } - - - public V1VaultSchemaConfig mapping(V1VaultFieldMapping mapping) { - this.mapping = mapping; - return this; - } - - /** - * Get mapping - * @return mapping - */ - @javax.annotation.Nullable - public V1VaultFieldMapping getMapping() { - return mapping; - } - - public void setMapping(V1VaultFieldMapping mapping) { - this.mapping = mapping; - } - - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - V1VaultSchemaConfig v1VaultSchemaConfig = (V1VaultSchemaConfig) o; - return Objects.equals(this.id, v1VaultSchemaConfig.id) && - Objects.equals(this.tableName, v1VaultSchemaConfig.tableName) && - Objects.equals(this.mapping, v1VaultSchemaConfig.mapping); - } - - @Override - public int hashCode() { - return Objects.hash(id, tableName, mapping); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class V1VaultSchemaConfig {\n"); - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" tableName: ").append(toIndentedString(tableName)).append("\n"); - sb.append(" mapping: ").append(toIndentedString(mapping)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } - - - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("id"); - openapiFields.add("table_name"); - openapiFields.add("mapping"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - } - - /** - * Validates the JSON Element and throws an exception if issues found - * - * @param jsonElement JSON Element - * @throws IOException if the JSON Element is invalid with respect to V1VaultSchemaConfig - */ - public static void validateJsonElement(JsonElement jsonElement) throws IOException { - if (jsonElement == null) { - if (!V1VaultSchemaConfig.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null - throw new IllegalArgumentException(String.format("The required field(s) %s in V1VaultSchemaConfig is not found in the empty JSON string", V1VaultSchemaConfig.openapiRequiredFields.toString())); - } - } - - Set> entries = jsonElement.getAsJsonObject().entrySet(); - // check to see if the JSON string contains additional fields - for (Map.Entry entry : entries) { - if (!V1VaultSchemaConfig.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `V1VaultSchemaConfig` properties. JSON: %s", entry.getKey(), jsonElement.toString())); - } - } - JsonObject jsonObj = jsonElement.getAsJsonObject(); - if ((jsonObj.get("id") != null && !jsonObj.get("id").isJsonNull()) && !jsonObj.get("id").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("id").toString())); - } - if ((jsonObj.get("table_name") != null && !jsonObj.get("table_name").isJsonNull()) && !jsonObj.get("table_name").isJsonPrimitive()) { - throw new IllegalArgumentException(String.format("Expected the field `table_name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("table_name").toString())); - } - // validate the optional field `mapping` - if (jsonObj.get("mapping") != null && !jsonObj.get("mapping").isJsonNull()) { - V1VaultFieldMapping.validateJsonElement(jsonObj.get("mapping")); - } - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!V1VaultSchemaConfig.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'V1VaultSchemaConfig' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(V1VaultSchemaConfig.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, V1VaultSchemaConfig value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public V1VaultSchemaConfig read(JsonReader in) throws IOException { - JsonElement jsonElement = elementAdapter.read(in); - validateJsonElement(jsonElement); - return thisAdapter.fromJsonTree(jsonElement); - } - - }.nullSafe(); - } - } - - /** - * Create an instance of V1VaultSchemaConfig given an JSON string - * - * @param jsonString JSON string - * @return An instance of V1VaultSchemaConfig - * @throws IOException if the JSON string is invalid with respect to V1VaultSchemaConfig - */ - public static V1VaultSchemaConfig fromJson(String jsonString) throws IOException { - return JSON.getGson().fromJson(jsonString, V1VaultSchemaConfig.class); - } - - /** - * Convert an instance of V1VaultSchemaConfig to an JSON string - * - * @return JSON string - */ - public String toJson() { - return JSON.getGson().toJson(this); - } -} - diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncAuditClient.java b/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncAuditClient.java new file mode 100644 index 00000000..0064558d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncAuditClient.java @@ -0,0 +1,45 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.audit.requests.AuditServiceListAuditEventsRequest; +import com.skyflow.generated.rest.types.V1AuditResponse; +import java.util.concurrent.CompletableFuture; + +public class AsyncAuditClient { + protected final ClientOptions clientOptions; + + private final AsyncRawAuditClient rawClient; + + public AsyncAuditClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawAuditClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawAuditClient withRawResponse() { + return this.rawClient; + } + + /** + * Lists audit events that match query parameters. + */ + public CompletableFuture auditServiceListAuditEvents(AuditServiceListAuditEventsRequest request) { + return this.rawClient.auditServiceListAuditEvents(request).thenApply(response -> response.body()); + } + + /** + * Lists audit events that match query parameters. + */ + public CompletableFuture auditServiceListAuditEvents( + AuditServiceListAuditEventsRequest request, RequestOptions requestOptions) { + return this.rawClient + .auditServiceListAuditEvents(request, requestOptions) + .thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncRawAuditClient.java b/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncRawAuditClient.java new file mode 100644 index 00000000..875ca259 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncRawAuditClient.java @@ -0,0 +1,296 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.audit.requests.AuditServiceListAuditEventsRequest; +import com.skyflow.generated.rest.types.V1AuditResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawAuditClient { + protected final ClientOptions clientOptions; + + public AsyncRawAuditClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Lists audit events that match query parameters. + */ + public CompletableFuture> auditServiceListAuditEvents( + AuditServiceListAuditEventsRequest request) { + return auditServiceListAuditEvents(request, null); + } + + /** + * Lists audit events that match query parameters. + */ + public CompletableFuture> auditServiceListAuditEvents( + AuditServiceListAuditEventsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/audit/events"); + if (request.getFilterOpsContextChangeId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.changeID", + request.getFilterOpsContextChangeId().get(), + false); + } + if (request.getFilterOpsContextRequestId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.requestID", + request.getFilterOpsContextRequestId().get(), + false); + } + if (request.getFilterOpsContextTraceId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.traceID", + request.getFilterOpsContextTraceId().get(), + false); + } + if (request.getFilterOpsContextSessionId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.sessionID", + request.getFilterOpsContextSessionId().get(), + false); + } + if (request.getFilterOpsContextActor().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.actor", + request.getFilterOpsContextActor().get(), + false); + } + if (request.getFilterOpsContextActorType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.actorType", + request.getFilterOpsContextActorType().get(), + false); + } + if (request.getFilterOpsContextAccessType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.accessType", + request.getFilterOpsContextAccessType().get(), + false); + } + if (request.getFilterOpsContextIpAddress().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.ipAddress", + request.getFilterOpsContextIpAddress().get(), + false); + } + if (request.getFilterOpsContextOrigin().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.origin", + request.getFilterOpsContextOrigin().get(), + false); + } + if (request.getFilterOpsContextAuthMode().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.authMode", + request.getFilterOpsContextAuthMode().get(), + false); + } + if (request.getFilterOpsContextJwtId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.jwtID", + request.getFilterOpsContextJwtId().get(), + false); + } + if (request.getFilterOpsContextBearerTokenContextId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.bearerTokenContextID", + request.getFilterOpsContextBearerTokenContextId().get(), + false); + } + if (request.getFilterOpsParentAccountId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.parentAccountID", + request.getFilterOpsParentAccountId().get(), + false); + } + QueryStringMapper.addQueryParameter(httpUrl, "filterOps.accountID", request.getFilterOpsAccountId(), false); + if (request.getFilterOpsWorkspaceId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.workspaceID", + request.getFilterOpsWorkspaceId().get(), + false); + } + if (request.getFilterOpsVaultId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.vaultID", request.getFilterOpsVaultId().get(), false); + } + if (request.getFilterOpsResourceIDs().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.resourceIDs", + request.getFilterOpsResourceIDs().get(), + false); + } + if (request.getFilterOpsActionType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.actionType", + request.getFilterOpsActionType().get(), + false); + } + if (request.getFilterOpsResourceType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.resourceType", + request.getFilterOpsResourceType().get(), + false); + } + if (request.getFilterOpsTags().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.tags", request.getFilterOpsTags().get(), false); + } + if (request.getFilterOpsResponseCode().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.responseCode", + request.getFilterOpsResponseCode().get(), + false); + } + if (request.getFilterOpsStartTime().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.startTime", + request.getFilterOpsStartTime().get(), + false); + } + if (request.getFilterOpsEndTime().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.endTime", request.getFilterOpsEndTime().get(), false); + } + if (request.getFilterOpsApiName().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.apiName", request.getFilterOpsApiName().get(), false); + } + if (request.getFilterOpsResponseMessage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.responseMessage", + request.getFilterOpsResponseMessage().get(), + false); + } + if (request.getFilterOpsHttpMethod().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.httpMethod", + request.getFilterOpsHttpMethod().get(), + false); + } + if (request.getFilterOpsHttpUri().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.httpURI", request.getFilterOpsHttpUri().get(), false); + } + if (request.getSortOpsSortBy().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "sortOps.sortBy", request.getSortOpsSortBy().get(), false); + } + if (request.getSortOpsOrderBy().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "sortOps.orderBy", request.getSortOpsOrderBy().get(), false); + } + if (request.getAfterOpsTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "afterOps.timestamp", + request.getAfterOpsTimestamp().get(), + false); + } + if (request.getAfterOpsChangeId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "afterOps.changeID", request.getAfterOpsChangeId().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getOffset().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "offset", request.getOffset().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1AuditResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/AuditClient.java b/src/main/java/com/skyflow/generated/rest/resources/audit/AuditClient.java new file mode 100644 index 00000000..bac81431 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/AuditClient.java @@ -0,0 +1,44 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.audit.requests.AuditServiceListAuditEventsRequest; +import com.skyflow.generated.rest.types.V1AuditResponse; + +public class AuditClient { + protected final ClientOptions clientOptions; + + private final RawAuditClient rawClient; + + public AuditClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawAuditClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawAuditClient withRawResponse() { + return this.rawClient; + } + + /** + * Lists audit events that match query parameters. + */ + public V1AuditResponse auditServiceListAuditEvents(AuditServiceListAuditEventsRequest request) { + return this.rawClient.auditServiceListAuditEvents(request).body(); + } + + /** + * Lists audit events that match query parameters. + */ + public V1AuditResponse auditServiceListAuditEvents( + AuditServiceListAuditEventsRequest request, RequestOptions requestOptions) { + return this.rawClient + .auditServiceListAuditEvents(request, requestOptions) + .body(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/RawAuditClient.java b/src/main/java/com/skyflow/generated/rest/resources/audit/RawAuditClient.java new file mode 100644 index 00000000..bfec3bf2 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/RawAuditClient.java @@ -0,0 +1,277 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.audit.requests.AuditServiceListAuditEventsRequest; +import com.skyflow.generated.rest.types.V1AuditResponse; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawAuditClient { + protected final ClientOptions clientOptions; + + public RawAuditClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Lists audit events that match query parameters. + */ + public ApiClientHttpResponse auditServiceListAuditEvents( + AuditServiceListAuditEventsRequest request) { + return auditServiceListAuditEvents(request, null); + } + + /** + * Lists audit events that match query parameters. + */ + public ApiClientHttpResponse auditServiceListAuditEvents( + AuditServiceListAuditEventsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/audit/events"); + if (request.getFilterOpsContextChangeId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.changeID", + request.getFilterOpsContextChangeId().get(), + false); + } + if (request.getFilterOpsContextRequestId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.requestID", + request.getFilterOpsContextRequestId().get(), + false); + } + if (request.getFilterOpsContextTraceId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.traceID", + request.getFilterOpsContextTraceId().get(), + false); + } + if (request.getFilterOpsContextSessionId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.sessionID", + request.getFilterOpsContextSessionId().get(), + false); + } + if (request.getFilterOpsContextActor().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.actor", + request.getFilterOpsContextActor().get(), + false); + } + if (request.getFilterOpsContextActorType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.actorType", + request.getFilterOpsContextActorType().get(), + false); + } + if (request.getFilterOpsContextAccessType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.accessType", + request.getFilterOpsContextAccessType().get(), + false); + } + if (request.getFilterOpsContextIpAddress().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.ipAddress", + request.getFilterOpsContextIpAddress().get(), + false); + } + if (request.getFilterOpsContextOrigin().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.origin", + request.getFilterOpsContextOrigin().get(), + false); + } + if (request.getFilterOpsContextAuthMode().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.authMode", + request.getFilterOpsContextAuthMode().get(), + false); + } + if (request.getFilterOpsContextJwtId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.jwtID", + request.getFilterOpsContextJwtId().get(), + false); + } + if (request.getFilterOpsContextBearerTokenContextId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.bearerTokenContextID", + request.getFilterOpsContextBearerTokenContextId().get(), + false); + } + if (request.getFilterOpsParentAccountId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.parentAccountID", + request.getFilterOpsParentAccountId().get(), + false); + } + QueryStringMapper.addQueryParameter(httpUrl, "filterOps.accountID", request.getFilterOpsAccountId(), false); + if (request.getFilterOpsWorkspaceId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.workspaceID", + request.getFilterOpsWorkspaceId().get(), + false); + } + if (request.getFilterOpsVaultId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.vaultID", request.getFilterOpsVaultId().get(), false); + } + if (request.getFilterOpsResourceIDs().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.resourceIDs", + request.getFilterOpsResourceIDs().get(), + false); + } + if (request.getFilterOpsActionType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.actionType", + request.getFilterOpsActionType().get(), + false); + } + if (request.getFilterOpsResourceType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.resourceType", + request.getFilterOpsResourceType().get(), + false); + } + if (request.getFilterOpsTags().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.tags", request.getFilterOpsTags().get(), false); + } + if (request.getFilterOpsResponseCode().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.responseCode", + request.getFilterOpsResponseCode().get(), + false); + } + if (request.getFilterOpsStartTime().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.startTime", + request.getFilterOpsStartTime().get(), + false); + } + if (request.getFilterOpsEndTime().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.endTime", request.getFilterOpsEndTime().get(), false); + } + if (request.getFilterOpsApiName().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.apiName", request.getFilterOpsApiName().get(), false); + } + if (request.getFilterOpsResponseMessage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.responseMessage", + request.getFilterOpsResponseMessage().get(), + false); + } + if (request.getFilterOpsHttpMethod().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.httpMethod", + request.getFilterOpsHttpMethod().get(), + false); + } + if (request.getFilterOpsHttpUri().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.httpURI", request.getFilterOpsHttpUri().get(), false); + } + if (request.getSortOpsSortBy().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "sortOps.sortBy", request.getSortOpsSortBy().get(), false); + } + if (request.getSortOpsOrderBy().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "sortOps.orderBy", request.getSortOpsOrderBy().get(), false); + } + if (request.getAfterOpsTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "afterOps.timestamp", + request.getAfterOpsTimestamp().get(), + false); + } + if (request.getAfterOpsChangeId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "afterOps.changeID", request.getAfterOpsChangeId().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getOffset().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "offset", request.getOffset().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1AuditResponse.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/requests/AuditServiceListAuditEventsRequest.java b/src/main/java/com/skyflow/generated/rest/resources/audit/requests/AuditServiceListAuditEventsRequest.java new file mode 100644 index 00000000..3da04589 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/requests/AuditServiceListAuditEventsRequest.java @@ -0,0 +1,1589 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.audit.types.AuditServiceListAuditEventsRequestFilterOpsActionType; +import com.skyflow.generated.rest.resources.audit.types.AuditServiceListAuditEventsRequestFilterOpsContextAccessType; +import com.skyflow.generated.rest.resources.audit.types.AuditServiceListAuditEventsRequestFilterOpsContextActorType; +import com.skyflow.generated.rest.resources.audit.types.AuditServiceListAuditEventsRequestFilterOpsContextAuthMode; +import com.skyflow.generated.rest.resources.audit.types.AuditServiceListAuditEventsRequestFilterOpsResourceType; +import com.skyflow.generated.rest.resources.audit.types.AuditServiceListAuditEventsRequestSortOpsOrderBy; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = AuditServiceListAuditEventsRequest.Builder.class) +public final class AuditServiceListAuditEventsRequest { + private final Optional filterOpsContextChangeId; + + private final Optional filterOpsContextRequestId; + + private final Optional filterOpsContextTraceId; + + private final Optional filterOpsContextSessionId; + + private final Optional filterOpsContextActor; + + private final Optional filterOpsContextActorType; + + private final Optional filterOpsContextAccessType; + + private final Optional filterOpsContextIpAddress; + + private final Optional filterOpsContextOrigin; + + private final Optional filterOpsContextAuthMode; + + private final Optional filterOpsContextJwtId; + + private final Optional filterOpsContextBearerTokenContextId; + + private final Optional filterOpsParentAccountId; + + private final String filterOpsAccountId; + + private final Optional filterOpsWorkspaceId; + + private final Optional filterOpsVaultId; + + private final Optional filterOpsResourceIDs; + + private final Optional filterOpsActionType; + + private final Optional filterOpsResourceType; + + private final Optional filterOpsTags; + + private final Optional filterOpsResponseCode; + + private final Optional filterOpsStartTime; + + private final Optional filterOpsEndTime; + + private final Optional filterOpsApiName; + + private final Optional filterOpsResponseMessage; + + private final Optional filterOpsHttpMethod; + + private final Optional filterOpsHttpUri; + + private final Optional sortOpsSortBy; + + private final Optional sortOpsOrderBy; + + private final Optional afterOpsTimestamp; + + private final Optional afterOpsChangeId; + + private final Optional limit; + + private final Optional offset; + + private final Map additionalProperties; + + private AuditServiceListAuditEventsRequest( + Optional filterOpsContextChangeId, + Optional filterOpsContextRequestId, + Optional filterOpsContextTraceId, + Optional filterOpsContextSessionId, + Optional filterOpsContextActor, + Optional filterOpsContextActorType, + Optional filterOpsContextAccessType, + Optional filterOpsContextIpAddress, + Optional filterOpsContextOrigin, + Optional filterOpsContextAuthMode, + Optional filterOpsContextJwtId, + Optional filterOpsContextBearerTokenContextId, + Optional filterOpsParentAccountId, + String filterOpsAccountId, + Optional filterOpsWorkspaceId, + Optional filterOpsVaultId, + Optional filterOpsResourceIDs, + Optional filterOpsActionType, + Optional filterOpsResourceType, + Optional filterOpsTags, + Optional filterOpsResponseCode, + Optional filterOpsStartTime, + Optional filterOpsEndTime, + Optional filterOpsApiName, + Optional filterOpsResponseMessage, + Optional filterOpsHttpMethod, + Optional filterOpsHttpUri, + Optional sortOpsSortBy, + Optional sortOpsOrderBy, + Optional afterOpsTimestamp, + Optional afterOpsChangeId, + Optional limit, + Optional offset, + Map additionalProperties) { + this.filterOpsContextChangeId = filterOpsContextChangeId; + this.filterOpsContextRequestId = filterOpsContextRequestId; + this.filterOpsContextTraceId = filterOpsContextTraceId; + this.filterOpsContextSessionId = filterOpsContextSessionId; + this.filterOpsContextActor = filterOpsContextActor; + this.filterOpsContextActorType = filterOpsContextActorType; + this.filterOpsContextAccessType = filterOpsContextAccessType; + this.filterOpsContextIpAddress = filterOpsContextIpAddress; + this.filterOpsContextOrigin = filterOpsContextOrigin; + this.filterOpsContextAuthMode = filterOpsContextAuthMode; + this.filterOpsContextJwtId = filterOpsContextJwtId; + this.filterOpsContextBearerTokenContextId = filterOpsContextBearerTokenContextId; + this.filterOpsParentAccountId = filterOpsParentAccountId; + this.filterOpsAccountId = filterOpsAccountId; + this.filterOpsWorkspaceId = filterOpsWorkspaceId; + this.filterOpsVaultId = filterOpsVaultId; + this.filterOpsResourceIDs = filterOpsResourceIDs; + this.filterOpsActionType = filterOpsActionType; + this.filterOpsResourceType = filterOpsResourceType; + this.filterOpsTags = filterOpsTags; + this.filterOpsResponseCode = filterOpsResponseCode; + this.filterOpsStartTime = filterOpsStartTime; + this.filterOpsEndTime = filterOpsEndTime; + this.filterOpsApiName = filterOpsApiName; + this.filterOpsResponseMessage = filterOpsResponseMessage; + this.filterOpsHttpMethod = filterOpsHttpMethod; + this.filterOpsHttpUri = filterOpsHttpUri; + this.sortOpsSortBy = sortOpsSortBy; + this.sortOpsOrderBy = sortOpsOrderBy; + this.afterOpsTimestamp = afterOpsTimestamp; + this.afterOpsChangeId = afterOpsChangeId; + this.limit = limit; + this.offset = offset; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID for the audit event. + */ + @JsonProperty("filterOps.context.changeID") + public Optional getFilterOpsContextChangeId() { + return filterOpsContextChangeId; + } + + /** + * @return ID for the request that caused the event. + */ + @JsonProperty("filterOps.context.requestID") + public Optional getFilterOpsContextRequestId() { + return filterOpsContextRequestId; + } + + /** + * @return ID for the request set by the service that received the request. + */ + @JsonProperty("filterOps.context.traceID") + public Optional getFilterOpsContextTraceId() { + return filterOpsContextTraceId; + } + + /** + * @return ID for the session in which the request was sent. + */ + @JsonProperty("filterOps.context.sessionID") + public Optional getFilterOpsContextSessionId() { + return filterOpsContextSessionId; + } + + /** + * @return Member who sent the request. Depending on actorType, this may be a user ID or a service account ID. + */ + @JsonProperty("filterOps.context.actor") + public Optional getFilterOpsContextActor() { + return filterOpsContextActor; + } + + /** + * @return Type of member who sent the request. + */ + @JsonProperty("filterOps.context.actorType") + public Optional getFilterOpsContextActorType() { + return filterOpsContextActorType; + } + + /** + * @return Type of access for the request. + */ + @JsonProperty("filterOps.context.accessType") + public Optional getFilterOpsContextAccessType() { + return filterOpsContextAccessType; + } + + /** + * @return IP Address of the client that made the request. + */ + @JsonProperty("filterOps.context.ipAddress") + public Optional getFilterOpsContextIpAddress() { + return filterOpsContextIpAddress; + } + + /** + * @return HTTP Origin request header (including scheme, hostname, and port) of the request. + */ + @JsonProperty("filterOps.context.origin") + public Optional getFilterOpsContextOrigin() { + return filterOpsContextOrigin; + } + + /** + * @return Authentication mode the actor used. + */ + @JsonProperty("filterOps.context.authMode") + public Optional getFilterOpsContextAuthMode() { + return filterOpsContextAuthMode; + } + + /** + * @return ID of the JWT token. + */ + @JsonProperty("filterOps.context.jwtID") + public Optional getFilterOpsContextJwtId() { + return filterOpsContextJwtId; + } + + /** + * @return Embedded User Context. + */ + @JsonProperty("filterOps.context.bearerTokenContextID") + public Optional getFilterOpsContextBearerTokenContextId() { + return filterOpsContextBearerTokenContextId; + } + + /** + * @return Resources with the specified parent account ID. + */ + @JsonProperty("filterOps.parentAccountID") + public Optional getFilterOpsParentAccountId() { + return filterOpsParentAccountId; + } + + /** + * @return Resources with the specified account ID. + */ + @JsonProperty("filterOps.accountID") + public String getFilterOpsAccountId() { + return filterOpsAccountId; + } + + /** + * @return Resources with the specified workspace ID. + */ + @JsonProperty("filterOps.workspaceID") + public Optional getFilterOpsWorkspaceId() { + return filterOpsWorkspaceId; + } + + /** + * @return Resources with the specified vault ID. + */ + @JsonProperty("filterOps.vaultID") + public Optional getFilterOpsVaultId() { + return filterOpsVaultId; + } + + /** + * @return Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of "<resourceType>/<resourceID>". For example, "VAULT/12345, USER/67890". + */ + @JsonProperty("filterOps.resourceIDs") + public Optional getFilterOpsResourceIDs() { + return filterOpsResourceIDs; + } + + /** + * @return Events with the specified action type. + */ + @JsonProperty("filterOps.actionType") + public Optional getFilterOpsActionType() { + return filterOpsActionType; + } + + /** + * @return Resources with the specified type. + */ + @JsonProperty("filterOps.resourceType") + public Optional getFilterOpsResourceType() { + return filterOpsResourceType; + } + + /** + * @return Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, "login, get". + */ + @JsonProperty("filterOps.tags") + public Optional getFilterOpsTags() { + return filterOpsTags; + } + + /** + * @return HTTP response code of the request. + */ + @JsonProperty("filterOps.responseCode") + public Optional getFilterOpsResponseCode() { + return filterOpsResponseCode; + } + + /** + * @return Start timestamp for the query, in SQL format. + */ + @JsonProperty("filterOps.startTime") + public Optional getFilterOpsStartTime() { + return filterOpsStartTime; + } + + /** + * @return End timestamp for the query, in SQL format. + */ + @JsonProperty("filterOps.endTime") + public Optional getFilterOpsEndTime() { + return filterOpsEndTime; + } + + /** + * @return Name of the API called in the request. + */ + @JsonProperty("filterOps.apiName") + public Optional getFilterOpsApiName() { + return filterOpsApiName; + } + + /** + * @return Response message of the request. + */ + @JsonProperty("filterOps.responseMessage") + public Optional getFilterOpsResponseMessage() { + return filterOpsResponseMessage; + } + + /** + * @return HTTP method of the request. + */ + @JsonProperty("filterOps.httpMethod") + public Optional getFilterOpsHttpMethod() { + return filterOpsHttpMethod; + } + + /** + * @return HTTP URI of the request. + */ + @JsonProperty("filterOps.httpURI") + public Optional getFilterOpsHttpUri() { + return filterOpsHttpUri; + } + + /** + * @return Fully-qualified field by which to sort results. Field names should be in camel case (for example, "capitalization.camelCase"). + */ + @JsonProperty("sortOps.sortBy") + public Optional getSortOpsSortBy() { + return sortOpsSortBy; + } + + /** + * @return Ascending or descending ordering of results. + */ + @JsonProperty("sortOps.orderBy") + public Optional getSortOpsOrderBy() { + return sortOpsOrderBy; + } + + /** + * @return Timestamp provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank. + */ + @JsonProperty("afterOps.timestamp") + public Optional getAfterOpsTimestamp() { + return afterOpsTimestamp; + } + + /** + * @return Change ID provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank. + */ + @JsonProperty("afterOps.changeID") + public Optional getAfterOpsChangeId() { + return afterOpsChangeId; + } + + /** + * @return Number of results to return. + */ + @JsonProperty("limit") + public Optional getLimit() { + return limit; + } + + /** + * @return Record position at which to start returning results. + */ + @JsonProperty("offset") + public Optional getOffset() { + return offset; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof AuditServiceListAuditEventsRequest + && equalTo((AuditServiceListAuditEventsRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(AuditServiceListAuditEventsRequest other) { + return filterOpsContextChangeId.equals(other.filterOpsContextChangeId) + && filterOpsContextRequestId.equals(other.filterOpsContextRequestId) + && filterOpsContextTraceId.equals(other.filterOpsContextTraceId) + && filterOpsContextSessionId.equals(other.filterOpsContextSessionId) + && filterOpsContextActor.equals(other.filterOpsContextActor) + && filterOpsContextActorType.equals(other.filterOpsContextActorType) + && filterOpsContextAccessType.equals(other.filterOpsContextAccessType) + && filterOpsContextIpAddress.equals(other.filterOpsContextIpAddress) + && filterOpsContextOrigin.equals(other.filterOpsContextOrigin) + && filterOpsContextAuthMode.equals(other.filterOpsContextAuthMode) + && filterOpsContextJwtId.equals(other.filterOpsContextJwtId) + && filterOpsContextBearerTokenContextId.equals(other.filterOpsContextBearerTokenContextId) + && filterOpsParentAccountId.equals(other.filterOpsParentAccountId) + && filterOpsAccountId.equals(other.filterOpsAccountId) + && filterOpsWorkspaceId.equals(other.filterOpsWorkspaceId) + && filterOpsVaultId.equals(other.filterOpsVaultId) + && filterOpsResourceIDs.equals(other.filterOpsResourceIDs) + && filterOpsActionType.equals(other.filterOpsActionType) + && filterOpsResourceType.equals(other.filterOpsResourceType) + && filterOpsTags.equals(other.filterOpsTags) + && filterOpsResponseCode.equals(other.filterOpsResponseCode) + && filterOpsStartTime.equals(other.filterOpsStartTime) + && filterOpsEndTime.equals(other.filterOpsEndTime) + && filterOpsApiName.equals(other.filterOpsApiName) + && filterOpsResponseMessage.equals(other.filterOpsResponseMessage) + && filterOpsHttpMethod.equals(other.filterOpsHttpMethod) + && filterOpsHttpUri.equals(other.filterOpsHttpUri) + && sortOpsSortBy.equals(other.sortOpsSortBy) + && sortOpsOrderBy.equals(other.sortOpsOrderBy) + && afterOpsTimestamp.equals(other.afterOpsTimestamp) + && afterOpsChangeId.equals(other.afterOpsChangeId) + && limit.equals(other.limit) + && offset.equals(other.offset); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.filterOpsContextChangeId, + this.filterOpsContextRequestId, + this.filterOpsContextTraceId, + this.filterOpsContextSessionId, + this.filterOpsContextActor, + this.filterOpsContextActorType, + this.filterOpsContextAccessType, + this.filterOpsContextIpAddress, + this.filterOpsContextOrigin, + this.filterOpsContextAuthMode, + this.filterOpsContextJwtId, + this.filterOpsContextBearerTokenContextId, + this.filterOpsParentAccountId, + this.filterOpsAccountId, + this.filterOpsWorkspaceId, + this.filterOpsVaultId, + this.filterOpsResourceIDs, + this.filterOpsActionType, + this.filterOpsResourceType, + this.filterOpsTags, + this.filterOpsResponseCode, + this.filterOpsStartTime, + this.filterOpsEndTime, + this.filterOpsApiName, + this.filterOpsResponseMessage, + this.filterOpsHttpMethod, + this.filterOpsHttpUri, + this.sortOpsSortBy, + this.sortOpsOrderBy, + this.afterOpsTimestamp, + this.afterOpsChangeId, + this.limit, + this.offset); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static FilterOpsAccountIdStage builder() { + return new Builder(); + } + + public interface FilterOpsAccountIdStage { + /** + * Resources with the specified account ID. + */ + _FinalStage filterOpsAccountId(@NotNull String filterOpsAccountId); + + Builder from(AuditServiceListAuditEventsRequest other); + } + + public interface _FinalStage { + AuditServiceListAuditEventsRequest build(); + + /** + *

ID for the audit event.

+ */ + _FinalStage filterOpsContextChangeId(Optional filterOpsContextChangeId); + + _FinalStage filterOpsContextChangeId(String filterOpsContextChangeId); + + /** + *

ID for the request that caused the event.

+ */ + _FinalStage filterOpsContextRequestId(Optional filterOpsContextRequestId); + + _FinalStage filterOpsContextRequestId(String filterOpsContextRequestId); + + /** + *

ID for the request set by the service that received the request.

+ */ + _FinalStage filterOpsContextTraceId(Optional filterOpsContextTraceId); + + _FinalStage filterOpsContextTraceId(String filterOpsContextTraceId); + + /** + *

ID for the session in which the request was sent.

+ */ + _FinalStage filterOpsContextSessionId(Optional filterOpsContextSessionId); + + _FinalStage filterOpsContextSessionId(String filterOpsContextSessionId); + + /** + *

Member who sent the request. Depending on actorType, this may be a user ID or a service account ID.

+ */ + _FinalStage filterOpsContextActor(Optional filterOpsContextActor); + + _FinalStage filterOpsContextActor(String filterOpsContextActor); + + /** + *

Type of member who sent the request.

+ */ + _FinalStage filterOpsContextActorType( + Optional filterOpsContextActorType); + + _FinalStage filterOpsContextActorType( + AuditServiceListAuditEventsRequestFilterOpsContextActorType filterOpsContextActorType); + + /** + *

Type of access for the request.

+ */ + _FinalStage filterOpsContextAccessType( + Optional filterOpsContextAccessType); + + _FinalStage filterOpsContextAccessType( + AuditServiceListAuditEventsRequestFilterOpsContextAccessType filterOpsContextAccessType); + + /** + *

IP Address of the client that made the request.

+ */ + _FinalStage filterOpsContextIpAddress(Optional filterOpsContextIpAddress); + + _FinalStage filterOpsContextIpAddress(String filterOpsContextIpAddress); + + /** + *

HTTP Origin request header (including scheme, hostname, and port) of the request.

+ */ + _FinalStage filterOpsContextOrigin(Optional filterOpsContextOrigin); + + _FinalStage filterOpsContextOrigin(String filterOpsContextOrigin); + + /** + *

Authentication mode the actor used.

+ */ + _FinalStage filterOpsContextAuthMode( + Optional filterOpsContextAuthMode); + + _FinalStage filterOpsContextAuthMode( + AuditServiceListAuditEventsRequestFilterOpsContextAuthMode filterOpsContextAuthMode); + + /** + *

ID of the JWT token.

+ */ + _FinalStage filterOpsContextJwtId(Optional filterOpsContextJwtId); + + _FinalStage filterOpsContextJwtId(String filterOpsContextJwtId); + + /** + *

Embedded User Context.

+ */ + _FinalStage filterOpsContextBearerTokenContextId(Optional filterOpsContextBearerTokenContextId); + + _FinalStage filterOpsContextBearerTokenContextId(String filterOpsContextBearerTokenContextId); + + /** + *

Resources with the specified parent account ID.

+ */ + _FinalStage filterOpsParentAccountId(Optional filterOpsParentAccountId); + + _FinalStage filterOpsParentAccountId(String filterOpsParentAccountId); + + /** + *

Resources with the specified workspace ID.

+ */ + _FinalStage filterOpsWorkspaceId(Optional filterOpsWorkspaceId); + + _FinalStage filterOpsWorkspaceId(String filterOpsWorkspaceId); + + /** + *

Resources with the specified vault ID.

+ */ + _FinalStage filterOpsVaultId(Optional filterOpsVaultId); + + _FinalStage filterOpsVaultId(String filterOpsVaultId); + + /** + *

Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of "<resourceType>/<resourceID>". For example, "VAULT/12345, USER/67890".

+ */ + _FinalStage filterOpsResourceIDs(Optional filterOpsResourceIDs); + + _FinalStage filterOpsResourceIDs(String filterOpsResourceIDs); + + /** + *

Events with the specified action type.

+ */ + _FinalStage filterOpsActionType( + Optional filterOpsActionType); + + _FinalStage filterOpsActionType(AuditServiceListAuditEventsRequestFilterOpsActionType filterOpsActionType); + + /** + *

Resources with the specified type.

+ */ + _FinalStage filterOpsResourceType( + Optional filterOpsResourceType); + + _FinalStage filterOpsResourceType( + AuditServiceListAuditEventsRequestFilterOpsResourceType filterOpsResourceType); + + /** + *

Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, "login, get".

+ */ + _FinalStage filterOpsTags(Optional filterOpsTags); + + _FinalStage filterOpsTags(String filterOpsTags); + + /** + *

HTTP response code of the request.

+ */ + _FinalStage filterOpsResponseCode(Optional filterOpsResponseCode); + + _FinalStage filterOpsResponseCode(Integer filterOpsResponseCode); + + /** + *

Start timestamp for the query, in SQL format.

+ */ + _FinalStage filterOpsStartTime(Optional filterOpsStartTime); + + _FinalStage filterOpsStartTime(String filterOpsStartTime); + + /** + *

End timestamp for the query, in SQL format.

+ */ + _FinalStage filterOpsEndTime(Optional filterOpsEndTime); + + _FinalStage filterOpsEndTime(String filterOpsEndTime); + + /** + *

Name of the API called in the request.

+ */ + _FinalStage filterOpsApiName(Optional filterOpsApiName); + + _FinalStage filterOpsApiName(String filterOpsApiName); + + /** + *

Response message of the request.

+ */ + _FinalStage filterOpsResponseMessage(Optional filterOpsResponseMessage); + + _FinalStage filterOpsResponseMessage(String filterOpsResponseMessage); + + /** + *

HTTP method of the request.

+ */ + _FinalStage filterOpsHttpMethod(Optional filterOpsHttpMethod); + + _FinalStage filterOpsHttpMethod(String filterOpsHttpMethod); + + /** + *

HTTP URI of the request.

+ */ + _FinalStage filterOpsHttpUri(Optional filterOpsHttpUri); + + _FinalStage filterOpsHttpUri(String filterOpsHttpUri); + + /** + *

Fully-qualified field by which to sort results. Field names should be in camel case (for example, "capitalization.camelCase").

+ */ + _FinalStage sortOpsSortBy(Optional sortOpsSortBy); + + _FinalStage sortOpsSortBy(String sortOpsSortBy); + + /** + *

Ascending or descending ordering of results.

+ */ + _FinalStage sortOpsOrderBy(Optional sortOpsOrderBy); + + _FinalStage sortOpsOrderBy(AuditServiceListAuditEventsRequestSortOpsOrderBy sortOpsOrderBy); + + /** + *

Timestamp provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank.

+ */ + _FinalStage afterOpsTimestamp(Optional afterOpsTimestamp); + + _FinalStage afterOpsTimestamp(String afterOpsTimestamp); + + /** + *

Change ID provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank.

+ */ + _FinalStage afterOpsChangeId(Optional afterOpsChangeId); + + _FinalStage afterOpsChangeId(String afterOpsChangeId); + + /** + *

Number of results to return.

+ */ + _FinalStage limit(Optional limit); + + _FinalStage limit(Long limit); + + /** + *

Record position at which to start returning results.

+ */ + _FinalStage offset(Optional offset); + + _FinalStage offset(Long offset); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements FilterOpsAccountIdStage, _FinalStage { + private String filterOpsAccountId; + + private Optional offset = Optional.empty(); + + private Optional limit = Optional.empty(); + + private Optional afterOpsChangeId = Optional.empty(); + + private Optional afterOpsTimestamp = Optional.empty(); + + private Optional sortOpsOrderBy = Optional.empty(); + + private Optional sortOpsSortBy = Optional.empty(); + + private Optional filterOpsHttpUri = Optional.empty(); + + private Optional filterOpsHttpMethod = Optional.empty(); + + private Optional filterOpsResponseMessage = Optional.empty(); + + private Optional filterOpsApiName = Optional.empty(); + + private Optional filterOpsEndTime = Optional.empty(); + + private Optional filterOpsStartTime = Optional.empty(); + + private Optional filterOpsResponseCode = Optional.empty(); + + private Optional filterOpsTags = Optional.empty(); + + private Optional filterOpsResourceType = + Optional.empty(); + + private Optional filterOpsActionType = Optional.empty(); + + private Optional filterOpsResourceIDs = Optional.empty(); + + private Optional filterOpsVaultId = Optional.empty(); + + private Optional filterOpsWorkspaceId = Optional.empty(); + + private Optional filterOpsParentAccountId = Optional.empty(); + + private Optional filterOpsContextBearerTokenContextId = Optional.empty(); + + private Optional filterOpsContextJwtId = Optional.empty(); + + private Optional filterOpsContextAuthMode = + Optional.empty(); + + private Optional filterOpsContextOrigin = Optional.empty(); + + private Optional filterOpsContextIpAddress = Optional.empty(); + + private Optional filterOpsContextAccessType = + Optional.empty(); + + private Optional filterOpsContextActorType = + Optional.empty(); + + private Optional filterOpsContextActor = Optional.empty(); + + private Optional filterOpsContextSessionId = Optional.empty(); + + private Optional filterOpsContextTraceId = Optional.empty(); + + private Optional filterOpsContextRequestId = Optional.empty(); + + private Optional filterOpsContextChangeId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(AuditServiceListAuditEventsRequest other) { + filterOpsContextChangeId(other.getFilterOpsContextChangeId()); + filterOpsContextRequestId(other.getFilterOpsContextRequestId()); + filterOpsContextTraceId(other.getFilterOpsContextTraceId()); + filterOpsContextSessionId(other.getFilterOpsContextSessionId()); + filterOpsContextActor(other.getFilterOpsContextActor()); + filterOpsContextActorType(other.getFilterOpsContextActorType()); + filterOpsContextAccessType(other.getFilterOpsContextAccessType()); + filterOpsContextIpAddress(other.getFilterOpsContextIpAddress()); + filterOpsContextOrigin(other.getFilterOpsContextOrigin()); + filterOpsContextAuthMode(other.getFilterOpsContextAuthMode()); + filterOpsContextJwtId(other.getFilterOpsContextJwtId()); + filterOpsContextBearerTokenContextId(other.getFilterOpsContextBearerTokenContextId()); + filterOpsParentAccountId(other.getFilterOpsParentAccountId()); + filterOpsAccountId(other.getFilterOpsAccountId()); + filterOpsWorkspaceId(other.getFilterOpsWorkspaceId()); + filterOpsVaultId(other.getFilterOpsVaultId()); + filterOpsResourceIDs(other.getFilterOpsResourceIDs()); + filterOpsActionType(other.getFilterOpsActionType()); + filterOpsResourceType(other.getFilterOpsResourceType()); + filterOpsTags(other.getFilterOpsTags()); + filterOpsResponseCode(other.getFilterOpsResponseCode()); + filterOpsStartTime(other.getFilterOpsStartTime()); + filterOpsEndTime(other.getFilterOpsEndTime()); + filterOpsApiName(other.getFilterOpsApiName()); + filterOpsResponseMessage(other.getFilterOpsResponseMessage()); + filterOpsHttpMethod(other.getFilterOpsHttpMethod()); + filterOpsHttpUri(other.getFilterOpsHttpUri()); + sortOpsSortBy(other.getSortOpsSortBy()); + sortOpsOrderBy(other.getSortOpsOrderBy()); + afterOpsTimestamp(other.getAfterOpsTimestamp()); + afterOpsChangeId(other.getAfterOpsChangeId()); + limit(other.getLimit()); + offset(other.getOffset()); + return this; + } + + /** + * Resources with the specified account ID.

Resources with the specified account ID.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("filterOps.accountID") + public _FinalStage filterOpsAccountId(@NotNull String filterOpsAccountId) { + this.filterOpsAccountId = Objects.requireNonNull(filterOpsAccountId, "filterOpsAccountId must not be null"); + return this; + } + + /** + *

Record position at which to start returning results.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage offset(Long offset) { + this.offset = Optional.ofNullable(offset); + return this; + } + + /** + *

Record position at which to start returning results.

+ */ + @java.lang.Override + @JsonSetter(value = "offset", nulls = Nulls.SKIP) + public _FinalStage offset(Optional offset) { + this.offset = offset; + return this; + } + + /** + *

Number of results to return.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage limit(Long limit) { + this.limit = Optional.ofNullable(limit); + return this; + } + + /** + *

Number of results to return.

+ */ + @java.lang.Override + @JsonSetter(value = "limit", nulls = Nulls.SKIP) + public _FinalStage limit(Optional limit) { + this.limit = limit; + return this; + } + + /** + *

Change ID provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage afterOpsChangeId(String afterOpsChangeId) { + this.afterOpsChangeId = Optional.ofNullable(afterOpsChangeId); + return this; + } + + /** + *

Change ID provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank.

+ */ + @java.lang.Override + @JsonSetter(value = "afterOps.changeID", nulls = Nulls.SKIP) + public _FinalStage afterOpsChangeId(Optional afterOpsChangeId) { + this.afterOpsChangeId = afterOpsChangeId; + return this; + } + + /** + *

Timestamp provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage afterOpsTimestamp(String afterOpsTimestamp) { + this.afterOpsTimestamp = Optional.ofNullable(afterOpsTimestamp); + return this; + } + + /** + *

Timestamp provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank.

+ */ + @java.lang.Override + @JsonSetter(value = "afterOps.timestamp", nulls = Nulls.SKIP) + public _FinalStage afterOpsTimestamp(Optional afterOpsTimestamp) { + this.afterOpsTimestamp = afterOpsTimestamp; + return this; + } + + /** + *

Ascending or descending ordering of results.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sortOpsOrderBy(AuditServiceListAuditEventsRequestSortOpsOrderBy sortOpsOrderBy) { + this.sortOpsOrderBy = Optional.ofNullable(sortOpsOrderBy); + return this; + } + + /** + *

Ascending or descending ordering of results.

+ */ + @java.lang.Override + @JsonSetter(value = "sortOps.orderBy", nulls = Nulls.SKIP) + public _FinalStage sortOpsOrderBy(Optional sortOpsOrderBy) { + this.sortOpsOrderBy = sortOpsOrderBy; + return this; + } + + /** + *

Fully-qualified field by which to sort results. Field names should be in camel case (for example, "capitalization.camelCase").

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sortOpsSortBy(String sortOpsSortBy) { + this.sortOpsSortBy = Optional.ofNullable(sortOpsSortBy); + return this; + } + + /** + *

Fully-qualified field by which to sort results. Field names should be in camel case (for example, "capitalization.camelCase").

+ */ + @java.lang.Override + @JsonSetter(value = "sortOps.sortBy", nulls = Nulls.SKIP) + public _FinalStage sortOpsSortBy(Optional sortOpsSortBy) { + this.sortOpsSortBy = sortOpsSortBy; + return this; + } + + /** + *

HTTP URI of the request.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsHttpUri(String filterOpsHttpUri) { + this.filterOpsHttpUri = Optional.ofNullable(filterOpsHttpUri); + return this; + } + + /** + *

HTTP URI of the request.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.httpURI", nulls = Nulls.SKIP) + public _FinalStage filterOpsHttpUri(Optional filterOpsHttpUri) { + this.filterOpsHttpUri = filterOpsHttpUri; + return this; + } + + /** + *

HTTP method of the request.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsHttpMethod(String filterOpsHttpMethod) { + this.filterOpsHttpMethod = Optional.ofNullable(filterOpsHttpMethod); + return this; + } + + /** + *

HTTP method of the request.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.httpMethod", nulls = Nulls.SKIP) + public _FinalStage filterOpsHttpMethod(Optional filterOpsHttpMethod) { + this.filterOpsHttpMethod = filterOpsHttpMethod; + return this; + } + + /** + *

Response message of the request.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsResponseMessage(String filterOpsResponseMessage) { + this.filterOpsResponseMessage = Optional.ofNullable(filterOpsResponseMessage); + return this; + } + + /** + *

Response message of the request.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.responseMessage", nulls = Nulls.SKIP) + public _FinalStage filterOpsResponseMessage(Optional filterOpsResponseMessage) { + this.filterOpsResponseMessage = filterOpsResponseMessage; + return this; + } + + /** + *

Name of the API called in the request.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsApiName(String filterOpsApiName) { + this.filterOpsApiName = Optional.ofNullable(filterOpsApiName); + return this; + } + + /** + *

Name of the API called in the request.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.apiName", nulls = Nulls.SKIP) + public _FinalStage filterOpsApiName(Optional filterOpsApiName) { + this.filterOpsApiName = filterOpsApiName; + return this; + } + + /** + *

End timestamp for the query, in SQL format.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsEndTime(String filterOpsEndTime) { + this.filterOpsEndTime = Optional.ofNullable(filterOpsEndTime); + return this; + } + + /** + *

End timestamp for the query, in SQL format.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.endTime", nulls = Nulls.SKIP) + public _FinalStage filterOpsEndTime(Optional filterOpsEndTime) { + this.filterOpsEndTime = filterOpsEndTime; + return this; + } + + /** + *

Start timestamp for the query, in SQL format.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsStartTime(String filterOpsStartTime) { + this.filterOpsStartTime = Optional.ofNullable(filterOpsStartTime); + return this; + } + + /** + *

Start timestamp for the query, in SQL format.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.startTime", nulls = Nulls.SKIP) + public _FinalStage filterOpsStartTime(Optional filterOpsStartTime) { + this.filterOpsStartTime = filterOpsStartTime; + return this; + } + + /** + *

HTTP response code of the request.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsResponseCode(Integer filterOpsResponseCode) { + this.filterOpsResponseCode = Optional.ofNullable(filterOpsResponseCode); + return this; + } + + /** + *

HTTP response code of the request.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.responseCode", nulls = Nulls.SKIP) + public _FinalStage filterOpsResponseCode(Optional filterOpsResponseCode) { + this.filterOpsResponseCode = filterOpsResponseCode; + return this; + } + + /** + *

Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, "login, get".

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsTags(String filterOpsTags) { + this.filterOpsTags = Optional.ofNullable(filterOpsTags); + return this; + } + + /** + *

Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, "login, get".

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.tags", nulls = Nulls.SKIP) + public _FinalStage filterOpsTags(Optional filterOpsTags) { + this.filterOpsTags = filterOpsTags; + return this; + } + + /** + *

Resources with the specified type.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsResourceType( + AuditServiceListAuditEventsRequestFilterOpsResourceType filterOpsResourceType) { + this.filterOpsResourceType = Optional.ofNullable(filterOpsResourceType); + return this; + } + + /** + *

Resources with the specified type.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.resourceType", nulls = Nulls.SKIP) + public _FinalStage filterOpsResourceType( + Optional filterOpsResourceType) { + this.filterOpsResourceType = filterOpsResourceType; + return this; + } + + /** + *

Events with the specified action type.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsActionType( + AuditServiceListAuditEventsRequestFilterOpsActionType filterOpsActionType) { + this.filterOpsActionType = Optional.ofNullable(filterOpsActionType); + return this; + } + + /** + *

Events with the specified action type.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.actionType", nulls = Nulls.SKIP) + public _FinalStage filterOpsActionType( + Optional filterOpsActionType) { + this.filterOpsActionType = filterOpsActionType; + return this; + } + + /** + *

Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of "<resourceType>/<resourceID>". For example, "VAULT/12345, USER/67890".

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsResourceIDs(String filterOpsResourceIDs) { + this.filterOpsResourceIDs = Optional.ofNullable(filterOpsResourceIDs); + return this; + } + + /** + *

Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of "<resourceType>/<resourceID>". For example, "VAULT/12345, USER/67890".

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.resourceIDs", nulls = Nulls.SKIP) + public _FinalStage filterOpsResourceIDs(Optional filterOpsResourceIDs) { + this.filterOpsResourceIDs = filterOpsResourceIDs; + return this; + } + + /** + *

Resources with the specified vault ID.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsVaultId(String filterOpsVaultId) { + this.filterOpsVaultId = Optional.ofNullable(filterOpsVaultId); + return this; + } + + /** + *

Resources with the specified vault ID.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.vaultID", nulls = Nulls.SKIP) + public _FinalStage filterOpsVaultId(Optional filterOpsVaultId) { + this.filterOpsVaultId = filterOpsVaultId; + return this; + } + + /** + *

Resources with the specified workspace ID.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsWorkspaceId(String filterOpsWorkspaceId) { + this.filterOpsWorkspaceId = Optional.ofNullable(filterOpsWorkspaceId); + return this; + } + + /** + *

Resources with the specified workspace ID.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.workspaceID", nulls = Nulls.SKIP) + public _FinalStage filterOpsWorkspaceId(Optional filterOpsWorkspaceId) { + this.filterOpsWorkspaceId = filterOpsWorkspaceId; + return this; + } + + /** + *

Resources with the specified parent account ID.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsParentAccountId(String filterOpsParentAccountId) { + this.filterOpsParentAccountId = Optional.ofNullable(filterOpsParentAccountId); + return this; + } + + /** + *

Resources with the specified parent account ID.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.parentAccountID", nulls = Nulls.SKIP) + public _FinalStage filterOpsParentAccountId(Optional filterOpsParentAccountId) { + this.filterOpsParentAccountId = filterOpsParentAccountId; + return this; + } + + /** + *

Embedded User Context.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsContextBearerTokenContextId(String filterOpsContextBearerTokenContextId) { + this.filterOpsContextBearerTokenContextId = Optional.ofNullable(filterOpsContextBearerTokenContextId); + return this; + } + + /** + *

Embedded User Context.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.context.bearerTokenContextID", nulls = Nulls.SKIP) + public _FinalStage filterOpsContextBearerTokenContextId(Optional filterOpsContextBearerTokenContextId) { + this.filterOpsContextBearerTokenContextId = filterOpsContextBearerTokenContextId; + return this; + } + + /** + *

ID of the JWT token.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsContextJwtId(String filterOpsContextJwtId) { + this.filterOpsContextJwtId = Optional.ofNullable(filterOpsContextJwtId); + return this; + } + + /** + *

ID of the JWT token.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.context.jwtID", nulls = Nulls.SKIP) + public _FinalStage filterOpsContextJwtId(Optional filterOpsContextJwtId) { + this.filterOpsContextJwtId = filterOpsContextJwtId; + return this; + } + + /** + *

Authentication mode the actor used.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsContextAuthMode( + AuditServiceListAuditEventsRequestFilterOpsContextAuthMode filterOpsContextAuthMode) { + this.filterOpsContextAuthMode = Optional.ofNullable(filterOpsContextAuthMode); + return this; + } + + /** + *

Authentication mode the actor used.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.context.authMode", nulls = Nulls.SKIP) + public _FinalStage filterOpsContextAuthMode( + Optional filterOpsContextAuthMode) { + this.filterOpsContextAuthMode = filterOpsContextAuthMode; + return this; + } + + /** + *

HTTP Origin request header (including scheme, hostname, and port) of the request.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsContextOrigin(String filterOpsContextOrigin) { + this.filterOpsContextOrigin = Optional.ofNullable(filterOpsContextOrigin); + return this; + } + + /** + *

HTTP Origin request header (including scheme, hostname, and port) of the request.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.context.origin", nulls = Nulls.SKIP) + public _FinalStage filterOpsContextOrigin(Optional filterOpsContextOrigin) { + this.filterOpsContextOrigin = filterOpsContextOrigin; + return this; + } + + /** + *

IP Address of the client that made the request.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsContextIpAddress(String filterOpsContextIpAddress) { + this.filterOpsContextIpAddress = Optional.ofNullable(filterOpsContextIpAddress); + return this; + } + + /** + *

IP Address of the client that made the request.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.context.ipAddress", nulls = Nulls.SKIP) + public _FinalStage filterOpsContextIpAddress(Optional filterOpsContextIpAddress) { + this.filterOpsContextIpAddress = filterOpsContextIpAddress; + return this; + } + + /** + *

Type of access for the request.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsContextAccessType( + AuditServiceListAuditEventsRequestFilterOpsContextAccessType filterOpsContextAccessType) { + this.filterOpsContextAccessType = Optional.ofNullable(filterOpsContextAccessType); + return this; + } + + /** + *

Type of access for the request.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.context.accessType", nulls = Nulls.SKIP) + public _FinalStage filterOpsContextAccessType( + Optional filterOpsContextAccessType) { + this.filterOpsContextAccessType = filterOpsContextAccessType; + return this; + } + + /** + *

Type of member who sent the request.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsContextActorType( + AuditServiceListAuditEventsRequestFilterOpsContextActorType filterOpsContextActorType) { + this.filterOpsContextActorType = Optional.ofNullable(filterOpsContextActorType); + return this; + } + + /** + *

Type of member who sent the request.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.context.actorType", nulls = Nulls.SKIP) + public _FinalStage filterOpsContextActorType( + Optional filterOpsContextActorType) { + this.filterOpsContextActorType = filterOpsContextActorType; + return this; + } + + /** + *

Member who sent the request. Depending on actorType, this may be a user ID or a service account ID.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsContextActor(String filterOpsContextActor) { + this.filterOpsContextActor = Optional.ofNullable(filterOpsContextActor); + return this; + } + + /** + *

Member who sent the request. Depending on actorType, this may be a user ID or a service account ID.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.context.actor", nulls = Nulls.SKIP) + public _FinalStage filterOpsContextActor(Optional filterOpsContextActor) { + this.filterOpsContextActor = filterOpsContextActor; + return this; + } + + /** + *

ID for the session in which the request was sent.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsContextSessionId(String filterOpsContextSessionId) { + this.filterOpsContextSessionId = Optional.ofNullable(filterOpsContextSessionId); + return this; + } + + /** + *

ID for the session in which the request was sent.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.context.sessionID", nulls = Nulls.SKIP) + public _FinalStage filterOpsContextSessionId(Optional filterOpsContextSessionId) { + this.filterOpsContextSessionId = filterOpsContextSessionId; + return this; + } + + /** + *

ID for the request set by the service that received the request.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsContextTraceId(String filterOpsContextTraceId) { + this.filterOpsContextTraceId = Optional.ofNullable(filterOpsContextTraceId); + return this; + } + + /** + *

ID for the request set by the service that received the request.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.context.traceID", nulls = Nulls.SKIP) + public _FinalStage filterOpsContextTraceId(Optional filterOpsContextTraceId) { + this.filterOpsContextTraceId = filterOpsContextTraceId; + return this; + } + + /** + *

ID for the request that caused the event.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsContextRequestId(String filterOpsContextRequestId) { + this.filterOpsContextRequestId = Optional.ofNullable(filterOpsContextRequestId); + return this; + } + + /** + *

ID for the request that caused the event.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.context.requestID", nulls = Nulls.SKIP) + public _FinalStage filterOpsContextRequestId(Optional filterOpsContextRequestId) { + this.filterOpsContextRequestId = filterOpsContextRequestId; + return this; + } + + /** + *

ID for the audit event.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage filterOpsContextChangeId(String filterOpsContextChangeId) { + this.filterOpsContextChangeId = Optional.ofNullable(filterOpsContextChangeId); + return this; + } + + /** + *

ID for the audit event.

+ */ + @java.lang.Override + @JsonSetter(value = "filterOps.context.changeID", nulls = Nulls.SKIP) + public _FinalStage filterOpsContextChangeId(Optional filterOpsContextChangeId) { + this.filterOpsContextChangeId = filterOpsContextChangeId; + return this; + } + + @java.lang.Override + public AuditServiceListAuditEventsRequest build() { + return new AuditServiceListAuditEventsRequest( + filterOpsContextChangeId, + filterOpsContextRequestId, + filterOpsContextTraceId, + filterOpsContextSessionId, + filterOpsContextActor, + filterOpsContextActorType, + filterOpsContextAccessType, + filterOpsContextIpAddress, + filterOpsContextOrigin, + filterOpsContextAuthMode, + filterOpsContextJwtId, + filterOpsContextBearerTokenContextId, + filterOpsParentAccountId, + filterOpsAccountId, + filterOpsWorkspaceId, + filterOpsVaultId, + filterOpsResourceIDs, + filterOpsActionType, + filterOpsResourceType, + filterOpsTags, + filterOpsResponseCode, + filterOpsStartTime, + filterOpsEndTime, + filterOpsApiName, + filterOpsResponseMessage, + filterOpsHttpMethod, + filterOpsHttpUri, + sortOpsSortBy, + sortOpsOrderBy, + afterOpsTimestamp, + afterOpsChangeId, + limit, + offset, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsActionType.java b/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsActionType.java new file mode 100644 index 00000000..a9fb6d44 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsActionType.java @@ -0,0 +1,56 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum AuditServiceListAuditEventsRequestFilterOpsActionType { + NONE("NONE"), + + ASSIGN("ASSIGN"), + + CREATE("CREATE"), + + DELETE("DELETE"), + + EXECUTE("EXECUTE"), + + LIST("LIST"), + + READ("READ"), + + UNASSIGN("UNASSIGN"), + + UPDATE("UPDATE"), + + VALIDATE("VALIDATE"), + + LOGIN("LOGIN"), + + ROTATE("ROTATE"), + + SCHEDULEROTATION("SCHEDULEROTATION"), + + SCHEDULEROTATIONALERT("SCHEDULEROTATIONALERT"), + + IMPORT("IMPORT"), + + GETIMPORTPARAMETERS("GETIMPORTPARAMETERS"), + + PING("PING"), + + GETCLOUDPROVIDER("GETCLOUDPROVIDER"); + + private final String value; + + AuditServiceListAuditEventsRequestFilterOpsActionType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAccessType.java b/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAccessType.java new file mode 100644 index 00000000..0b082305 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAccessType.java @@ -0,0 +1,28 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum AuditServiceListAuditEventsRequestFilterOpsContextAccessType { + ACCESS_NONE("ACCESS_NONE"), + + API("API"), + + SQL("SQL"), + + OKTA_LOGIN("OKTA_LOGIN"); + + private final String value; + + AuditServiceListAuditEventsRequestFilterOpsContextAccessType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextActorType.java b/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextActorType.java new file mode 100644 index 00000000..76a357f4 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextActorType.java @@ -0,0 +1,26 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum AuditServiceListAuditEventsRequestFilterOpsContextActorType { + NONE("NONE"), + + USER("USER"), + + SERVICE_ACCOUNT("SERVICE_ACCOUNT"); + + private final String value; + + AuditServiceListAuditEventsRequestFilterOpsContextActorType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAuthMode.java b/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAuthMode.java new file mode 100644 index 00000000..cfca2e35 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsContextAuthMode.java @@ -0,0 +1,28 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum AuditServiceListAuditEventsRequestFilterOpsContextAuthMode { + AUTH_NONE("AUTH_NONE"), + + OKTA_JWT("OKTA_JWT"), + + SERVICE_ACCOUNT_JWT("SERVICE_ACCOUNT_JWT"), + + PAT_JWT("PAT_JWT"); + + private final String value; + + AuditServiceListAuditEventsRequestFilterOpsContextAuthMode(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsResourceType.java b/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsResourceType.java new file mode 100644 index 00000000..f5d2eafe --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestFilterOpsResourceType.java @@ -0,0 +1,80 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum AuditServiceListAuditEventsRequestFilterOpsResourceType { + NONE_API("NONE_API"), + + ACCOUNT("ACCOUNT"), + + AUDIT("AUDIT"), + + BASE_DATA_TYPE("BASE_DATA_TYPE"), + + FIELD_TEMPLATE("FIELD_TEMPLATE"), + + FILE("FILE"), + + KEY("KEY"), + + POLICY("POLICY"), + + PROTO_PARSE("PROTO_PARSE"), + + RECORD("RECORD"), + + ROLE("ROLE"), + + RULE("RULE"), + + SECRET("SECRET"), + + SERVICE_ACCOUNT("SERVICE_ACCOUNT"), + + TOKEN("TOKEN"), + + USER("USER"), + + VAULT("VAULT"), + + VAULT_TEMPLATE("VAULT_TEMPLATE"), + + WORKSPACE("WORKSPACE"), + + TABLE("TABLE"), + + POLICY_TEMPLATE("POLICY_TEMPLATE"), + + MEMBER("MEMBER"), + + TAG("TAG"), + + CONNECTION("CONNECTION"), + + MIGRATION("MIGRATION"), + + SCHEDULED_JOB("SCHEDULED_JOB"), + + JOB("JOB"), + + COLUMN_NAME("COLUMN_NAME"), + + NETWORK_TOKEN("NETWORK_TOKEN"), + + SUBSCRIPTION("SUBSCRIPTION"); + + private final String value; + + AuditServiceListAuditEventsRequestFilterOpsResourceType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestSortOpsOrderBy.java b/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestSortOpsOrderBy.java new file mode 100644 index 00000000..51fc2715 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/types/AuditServiceListAuditEventsRequestSortOpsOrderBy.java @@ -0,0 +1,24 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum AuditServiceListAuditEventsRequestSortOpsOrderBy { + ASCENDING("ASCENDING"), + + DESCENDING("DESCENDING"); + + private final String value; + + AuditServiceListAuditEventsRequestSortOpsOrderBy(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/authentication/AsyncAuthenticationClient.java b/src/main/java/com/skyflow/generated/rest/resources/authentication/AsyncAuthenticationClient.java new file mode 100644 index 00000000..43ffab73 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/authentication/AsyncAuthenticationClient.java @@ -0,0 +1,45 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.authentication; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.authentication.requests.V1GetAuthTokenRequest; +import com.skyflow.generated.rest.types.V1GetAuthTokenResponse; +import java.util.concurrent.CompletableFuture; + +public class AsyncAuthenticationClient { + protected final ClientOptions clientOptions; + + private final AsyncRawAuthenticationClient rawClient; + + public AsyncAuthenticationClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawAuthenticationClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawAuthenticationClient withRawResponse() { + return this.rawClient; + } + + /** + *

<p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p>

+ */ + public CompletableFuture authenticationServiceGetAuthToken(V1GetAuthTokenRequest request) { + return this.rawClient.authenticationServiceGetAuthToken(request).thenApply(response -> response.body()); + } + + /** + *

<p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p>

+ */ + public CompletableFuture authenticationServiceGetAuthToken( + V1GetAuthTokenRequest request, RequestOptions requestOptions) { + return this.rawClient + .authenticationServiceGetAuthToken(request, requestOptions) + .thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/authentication/AsyncRawAuthenticationClient.java b/src/main/java/com/skyflow/generated/rest/resources/authentication/AsyncRawAuthenticationClient.java new file mode 100644 index 00000000..eca4ab90 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/authentication/AsyncRawAuthenticationClient.java @@ -0,0 +1,126 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.authentication; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.errors.UnauthorizedError; +import com.skyflow.generated.rest.resources.authentication.requests.V1GetAuthTokenRequest; +import com.skyflow.generated.rest.types.V1GetAuthTokenResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawAuthenticationClient { + protected final ClientOptions clientOptions; + + public AsyncRawAuthenticationClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + *

<p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p>

+ */ + public CompletableFuture> authenticationServiceGetAuthToken( + V1GetAuthTokenRequest request) { + return authenticationServiceGetAuthToken(request, null); + } + + /** + *

<p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p>

+ */ + public CompletableFuture> authenticationServiceGetAuthToken( + V1GetAuthTokenRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/auth/sa/oauth/token") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), V1GetAuthTokenResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/authentication/AuthenticationClient.java b/src/main/java/com/skyflow/generated/rest/resources/authentication/AuthenticationClient.java new file mode 100644 index 00000000..662bfb3d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/authentication/AuthenticationClient.java @@ -0,0 +1,44 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.authentication; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.authentication.requests.V1GetAuthTokenRequest; +import com.skyflow.generated.rest.types.V1GetAuthTokenResponse; + +public class AuthenticationClient { + protected final ClientOptions clientOptions; + + private final RawAuthenticationClient rawClient; + + public AuthenticationClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawAuthenticationClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawAuthenticationClient withRawResponse() { + return this.rawClient; + } + + /** + *

<p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p>

+ */ + public V1GetAuthTokenResponse authenticationServiceGetAuthToken(V1GetAuthTokenRequest request) { + return this.rawClient.authenticationServiceGetAuthToken(request).body(); + } + + /** + *

<p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p>

+ */ + public V1GetAuthTokenResponse authenticationServiceGetAuthToken( + V1GetAuthTokenRequest request, RequestOptions requestOptions) { + return this.rawClient + .authenticationServiceGetAuthToken(request, requestOptions) + .body(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/authentication/RawAuthenticationClient.java b/src/main/java/com/skyflow/generated/rest/resources/authentication/RawAuthenticationClient.java new file mode 100644 index 00000000..3d242eff --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/authentication/RawAuthenticationClient.java @@ -0,0 +1,102 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.authentication; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.errors.UnauthorizedError; +import com.skyflow.generated.rest.resources.authentication.requests.V1GetAuthTokenRequest; +import com.skyflow.generated.rest.types.V1GetAuthTokenResponse; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawAuthenticationClient { + protected final ClientOptions clientOptions; + + public RawAuthenticationClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + *

<p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p>

+ */ + public ApiClientHttpResponse authenticationServiceGetAuthToken( + V1GetAuthTokenRequest request) { + return authenticationServiceGetAuthToken(request, null); + } + + /** + *

<p>Generates a Bearer Token to authenticate with Skyflow. This method doesn't require the <code>Authorization</code> header.</p><p><b>Note:</b> For recommended ways to authenticate, see <a href='/api-authentication/'>API authentication</a>.</p>

+ */ + public ApiClientHttpResponse authenticationServiceGetAuthToken( + V1GetAuthTokenRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/auth/sa/oauth/token") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1GetAuthTokenResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/authentication/requests/V1GetAuthTokenRequest.java b/src/main/java/com/skyflow/generated/rest/resources/authentication/requests/V1GetAuthTokenRequest.java new file mode 100644 index 00000000..8c4961b1 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/authentication/requests/V1GetAuthTokenRequest.java @@ -0,0 +1,335 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.authentication.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1GetAuthTokenRequest.Builder.class) +public final class V1GetAuthTokenRequest { + private final String grantType; + + private final String assertion; + + private final Optional subjectToken; + + private final Optional subjectTokenType; + + private final Optional requestedTokenUse; + + private final Optional scope; + + private final Map additionalProperties; + + private V1GetAuthTokenRequest( + String grantType, + String assertion, + Optional subjectToken, + Optional subjectTokenType, + Optional requestedTokenUse, + Optional scope, + Map additionalProperties) { + this.grantType = grantType; + this.assertion = assertion; + this.subjectToken = subjectToken; + this.subjectTokenType = subjectTokenType; + this.requestedTokenUse = requestedTokenUse; + this.scope = scope; + this.additionalProperties = additionalProperties; + } + + /** + * @return Grant type of the request. Set this to urn:ietf:params:oauth:grant-type:jwt-bearer. + */ + @JsonProperty("grant_type") + public String getGrantType() { + return grantType; + } + + /** + * @return User-signed JWT token that contains the following fields: <br/> <ul><li><code>iss</code>: Issuer of the JWT.</li><li><code>key</code>: Unique identifier for the key.</li><li><code>aud</code>: Recipient the JWT is intended for.</li><li><code>exp</code>: Time the JWT expires.</li><li><code>sub</code>: Subject of the JWT.</li><li><code>ctx</code>: (Optional) Value for <a href='/context-aware-overview/'>Context-aware authorization</a>.</li></ul> + */ + @JsonProperty("assertion") + public String getAssertion() { + return assertion; + } + + /** + * @return Subject token. + */ + @JsonProperty("subject_token") + public Optional getSubjectToken() { + return subjectToken; + } + + /** + * @return Subject token type. + */ + @JsonProperty("subject_token_type") + public Optional getSubjectTokenType() { + return subjectTokenType; + } + + /** + * @return Token use type. Either delegation or impersonation. + */ + @JsonProperty("requested_token_use") + public Optional getRequestedTokenUse() { + return requestedTokenUse; + } + + /** + * @return Subset of available <a href='#Roles'>roles</a> to associate with the requested token. Uses the format "role:<roleID1> role:<roleID2>". + */ + @JsonProperty("scope") + public Optional getScope() { + return scope; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1GetAuthTokenRequest && equalTo((V1GetAuthTokenRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1GetAuthTokenRequest other) { + return grantType.equals(other.grantType) + && assertion.equals(other.assertion) + && subjectToken.equals(other.subjectToken) + && subjectTokenType.equals(other.subjectTokenType) + && requestedTokenUse.equals(other.requestedTokenUse) + && scope.equals(other.scope); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.grantType, + this.assertion, + this.subjectToken, + this.subjectTokenType, + this.requestedTokenUse, + this.scope); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static GrantTypeStage builder() { + return new Builder(); + } + + public interface GrantTypeStage { + /** + * Grant type of the request. Set this to `urn:ietf:params:oauth:grant-type:jwt-bearer`. + */ + AssertionStage grantType(@NotNull String grantType); + + Builder from(V1GetAuthTokenRequest other); + } + + public interface AssertionStage { + /** + * User-signed JWT token that contains the following fields:
  • iss: Issuer of the JWT.
  • key: Unique identifier for the key.
  • aud: Recipient the JWT is intended for.
  • exp: Time the JWT expires.
  • sub: Subject of the JWT.
  • ctx: (Optional) Value for Context-aware authorization.
+ */ + _FinalStage assertion(@NotNull String assertion); + } + + public interface _FinalStage { + V1GetAuthTokenRequest build(); + + /** + *

Subject token.

+ */ + _FinalStage subjectToken(Optional subjectToken); + + _FinalStage subjectToken(String subjectToken); + + /** + *

Subject token type.

+ */ + _FinalStage subjectTokenType(Optional subjectTokenType); + + _FinalStage subjectTokenType(String subjectTokenType); + + /** + *

Token use type. Either delegation or impersonation.

+ */ + _FinalStage requestedTokenUse(Optional requestedTokenUse); + + _FinalStage requestedTokenUse(String requestedTokenUse); + + /** + *

Subset of available <a href='#Roles'>roles</a> to associate with the requested token. Uses the format "role:<roleID1> role:<roleID2>".

+ */ + _FinalStage scope(Optional scope); + + _FinalStage scope(String scope); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements GrantTypeStage, AssertionStage, _FinalStage { + private String grantType; + + private String assertion; + + private Optional scope = Optional.empty(); + + private Optional requestedTokenUse = Optional.empty(); + + private Optional subjectTokenType = Optional.empty(); + + private Optional subjectToken = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(V1GetAuthTokenRequest other) { + grantType(other.getGrantType()); + assertion(other.getAssertion()); + subjectToken(other.getSubjectToken()); + subjectTokenType(other.getSubjectTokenType()); + requestedTokenUse(other.getRequestedTokenUse()); + scope(other.getScope()); + return this; + } + + /** + * Grant type of the request. Set this to `urn:ietf:params:oauth:grant-type:jwt-bearer`.

Grant type of the request. Set this to urn:ietf:params:oauth:grant-type:jwt-bearer.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("grant_type") + public AssertionStage grantType(@NotNull String grantType) { + this.grantType = Objects.requireNonNull(grantType, "grantType must not be null"); + return this; + } + + /** + * User-signed JWT token that contains the following fields:
  • iss: Issuer of the JWT.
  • key: Unique identifier for the key.
  • aud: Recipient the JWT is intended for.
  • exp: Time the JWT expires.
  • sub: Subject of the JWT.
  • ctx: (Optional) Value for Context-aware authorization.

User-signed JWT token that contains the following fields: <br/> <ul><li><code>iss</code>: Issuer of the JWT.</li><li><code>key</code>: Unique identifier for the key.</li><li><code>aud</code>: Recipient the JWT is intended for.</li><li><code>exp</code>: Time the JWT expires.</li><li><code>sub</code>: Subject of the JWT.</li><li><code>ctx</code>: (Optional) Value for <a href='/context-aware-overview/'>Context-aware authorization</a>.</li></ul>

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("assertion") + public _FinalStage assertion(@NotNull String assertion) { + this.assertion = Objects.requireNonNull(assertion, "assertion must not be null"); + return this; + } + + /** + *

Subset of available <a href='#Roles'>roles</a> to associate with the requested token. Uses the format "role:<roleID1> role:<roleID2>".

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage scope(String scope) { + this.scope = Optional.ofNullable(scope); + return this; + } + + /** + *

Subset of available <a href='#Roles'>roles</a> to associate with the requested token. Uses the format "role:<roleID1> role:<roleID2>".

+ */ + @java.lang.Override + @JsonSetter(value = "scope", nulls = Nulls.SKIP) + public _FinalStage scope(Optional scope) { + this.scope = scope; + return this; + } + + /** + *

Token use type. Either delegation or impersonation.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage requestedTokenUse(String requestedTokenUse) { + this.requestedTokenUse = Optional.ofNullable(requestedTokenUse); + return this; + } + + /** + *

Token use type. Either delegation or impersonation.

+ */ + @java.lang.Override + @JsonSetter(value = "requested_token_use", nulls = Nulls.SKIP) + public _FinalStage requestedTokenUse(Optional requestedTokenUse) { + this.requestedTokenUse = requestedTokenUse; + return this; + } + + /** + *

Subject token type.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage subjectTokenType(String subjectTokenType) { + this.subjectTokenType = Optional.ofNullable(subjectTokenType); + return this; + } + + /** + *

Subject token type.

+ */ + @java.lang.Override + @JsonSetter(value = "subject_token_type", nulls = Nulls.SKIP) + public _FinalStage subjectTokenType(Optional subjectTokenType) { + this.subjectTokenType = subjectTokenType; + return this; + } + + /** + *

Subject token.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage subjectToken(String subjectToken) { + this.subjectToken = Optional.ofNullable(subjectToken); + return this; + } + + /** + *

Subject token.

+ */ + @java.lang.Override + @JsonSetter(value = "subject_token", nulls = Nulls.SKIP) + public _FinalStage subjectToken(Optional subjectToken) { + this.subjectToken = subjectToken; + return this; + } + + @java.lang.Override + public V1GetAuthTokenRequest build() { + return new V1GetAuthTokenRequest( + grantType, + assertion, + subjectToken, + subjectTokenType, + requestedTokenUse, + scope, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncBinLookupClient.java b/src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncBinLookupClient.java new file mode 100644 index 00000000..f10ed979 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncBinLookupClient.java @@ -0,0 +1,52 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.binlookup; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.binlookup.requests.V1BinListRequest; +import com.skyflow.generated.rest.types.V1BinListResponse; +import java.util.concurrent.CompletableFuture; + +public class AsyncBinLookupClient { + protected final ClientOptions clientOptions; + + private final AsyncRawBinLookupClient rawClient; + + public AsyncBinLookupClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawBinLookupClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawBinLookupClient withRawResponse() { + return this.rawClient; + } + + /** + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + */ + public CompletableFuture binListServiceListCardsOfBin() { + return this.rawClient.binListServiceListCardsOfBin().thenApply(response -> response.body()); + } + + /** + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + */ + public CompletableFuture binListServiceListCardsOfBin(V1BinListRequest request) { + return this.rawClient.binListServiceListCardsOfBin(request).thenApply(response -> response.body()); + } + + /** + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + */ + public CompletableFuture binListServiceListCardsOfBin( + V1BinListRequest request, RequestOptions requestOptions) { + return this.rawClient + .binListServiceListCardsOfBin(request, requestOptions) + .thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncRawBinLookupClient.java b/src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncRawBinLookupClient.java new file mode 100644 index 00000000..2a3f5f4f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/binlookup/AsyncRawBinLookupClient.java @@ -0,0 +1,118 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.binlookup; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.binlookup.requests.V1BinListRequest; +import com.skyflow.generated.rest.types.V1BinListResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawBinLookupClient { + protected final ClientOptions clientOptions; + + public AsyncRawBinLookupClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + */ + public CompletableFuture> binListServiceListCardsOfBin() { + return binListServiceListCardsOfBin(V1BinListRequest.builder().build()); + } + + /** + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + */ + public CompletableFuture> binListServiceListCardsOfBin( + V1BinListRequest request) { + return binListServiceListCardsOfBin(request, null); + } + + /** + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + */ + public CompletableFuture> binListServiceListCardsOfBin( + V1BinListRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/card_lookup") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1BinListResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/binlookup/BinLookupClient.java b/src/main/java/com/skyflow/generated/rest/resources/binlookup/BinLookupClient.java new file mode 100644 index 00000000..a7822986 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/binlookup/BinLookupClient.java @@ -0,0 +1,50 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.binlookup; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.binlookup.requests.V1BinListRequest; +import com.skyflow.generated.rest.types.V1BinListResponse; + +public class BinLookupClient { + protected final ClientOptions clientOptions; + + private final RawBinLookupClient rawClient; + + public BinLookupClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawBinLookupClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawBinLookupClient withRawResponse() { + return this.rawClient; + } + + /** + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + */ + public V1BinListResponse binListServiceListCardsOfBin() { + return this.rawClient.binListServiceListCardsOfBin().body(); + } + + /** + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + */ + public V1BinListResponse binListServiceListCardsOfBin(V1BinListRequest request) { + return this.rawClient.binListServiceListCardsOfBin(request).body(); + } + + /** + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + */ + public V1BinListResponse binListServiceListCardsOfBin(V1BinListRequest request, RequestOptions requestOptions) { + return this.rawClient + .binListServiceListCardsOfBin(request, requestOptions) + .body(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/binlookup/RawBinLookupClient.java b/src/main/java/com/skyflow/generated/rest/resources/binlookup/RawBinLookupClient.java new file mode 100644 index 00000000..bb08039b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/binlookup/RawBinLookupClient.java @@ -0,0 +1,98 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.binlookup; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.binlookup.requests.V1BinListRequest; +import com.skyflow.generated.rest.types.V1BinListResponse; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawBinLookupClient { + protected final ClientOptions clientOptions; + + public RawBinLookupClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + */ + public ApiClientHttpResponse binListServiceListCardsOfBin() { + return binListServiceListCardsOfBin(V1BinListRequest.builder().build()); + } + + /** + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + */ + public ApiClientHttpResponse binListServiceListCardsOfBin(V1BinListRequest request) { + return binListServiceListCardsOfBin(request, null); + } + + /** + * <b>Note</b>: This endpoint is in beta and subject to change. <br><br> Returns the specified card metadata. + */ + public ApiClientHttpResponse binListServiceListCardsOfBin( + V1BinListRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/card_lookup") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1BinListResponse.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/binlookup/requests/V1BinListRequest.java b/src/main/java/com/skyflow/generated/rest/resources/binlookup/requests/V1BinListRequest.java new file mode 100644 index 00000000..d4a1c21b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/binlookup/requests/V1BinListRequest.java @@ -0,0 +1,189 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.binlookup.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.V1VaultSchemaConfig; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1BinListRequest.Builder.class) +public final class V1BinListRequest { + private final Optional> fields; + + private final Optional bin; + + private final Optional vaultSchemaConfig; + + private final Optional skyflowId; + + private final Map additionalProperties; + + private V1BinListRequest( + Optional> fields, + Optional bin, + Optional vaultSchemaConfig, + Optional skyflowId, + Map additionalProperties) { + this.fields = fields; + this.bin = bin; + this.vaultSchemaConfig = vaultSchemaConfig; + this.skyflowId = skyflowId; + this.additionalProperties = additionalProperties; + } + + /** + * @return Fields to return. If not specified, all fields are returned. + */ + @JsonProperty("fields") + public Optional> getFields() { + return fields; + } + + /** + * @return BIN of the card. + */ + @JsonProperty("BIN") + public Optional getBin() { + return bin; + } + + @JsonProperty("vault_schema_config") + public Optional getVaultSchemaConfig() { + return vaultSchemaConfig; + } + + /** + * @return <code>skyflow_id</code> of the record. + */ + @JsonProperty("skyflow_id") + public Optional getSkyflowId() { + return skyflowId; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1BinListRequest && equalTo((V1BinListRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1BinListRequest other) { + return fields.equals(other.fields) + && bin.equals(other.bin) + && vaultSchemaConfig.equals(other.vaultSchemaConfig) + && skyflowId.equals(other.skyflowId); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.fields, this.bin, this.vaultSchemaConfig, this.skyflowId); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> fields = Optional.empty(); + + private Optional bin = Optional.empty(); + + private Optional vaultSchemaConfig = Optional.empty(); + + private Optional skyflowId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1BinListRequest other) { + fields(other.getFields()); + bin(other.getBin()); + vaultSchemaConfig(other.getVaultSchemaConfig()); + skyflowId(other.getSkyflowId()); + return this; + } + + /** + *

Fields to return. If not specified, all fields are returned.

+ */ + @JsonSetter(value = "fields", nulls = Nulls.SKIP) + public Builder fields(Optional> fields) { + this.fields = fields; + return this; + } + + public Builder fields(List fields) { + this.fields = Optional.ofNullable(fields); + return this; + } + + /** + *

BIN of the card.

+ */ + @JsonSetter(value = "BIN", nulls = Nulls.SKIP) + public Builder bin(Optional bin) { + this.bin = bin; + return this; + } + + public Builder bin(String bin) { + this.bin = Optional.ofNullable(bin); + return this; + } + + @JsonSetter(value = "vault_schema_config", nulls = Nulls.SKIP) + public Builder vaultSchemaConfig(Optional vaultSchemaConfig) { + this.vaultSchemaConfig = vaultSchemaConfig; + return this; + } + + public Builder vaultSchemaConfig(V1VaultSchemaConfig vaultSchemaConfig) { + this.vaultSchemaConfig = Optional.ofNullable(vaultSchemaConfig); + return this; + } + + /** + *

<code>skyflow_id</code> of the record.

+ */ + @JsonSetter(value = "skyflow_id", nulls = Nulls.SKIP) + public Builder skyflowId(Optional skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + public Builder skyflowId(String skyflowId) { + this.skyflowId = Optional.ofNullable(skyflowId); + return this; + } + + public V1BinListRequest build() { + return new V1BinListRequest(fields, bin, vaultSchemaConfig, skyflowId, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncDeprecatedClient.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncDeprecatedClient.java new file mode 100644 index 00000000..c1709f7f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncDeprecatedClient.java @@ -0,0 +1,89 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.deprecated; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectStatusRequest; +import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectTextRequest; +import com.skyflow.generated.rest.resources.deprecated.requests.V1DetectFileRequest; +import com.skyflow.generated.rest.types.V1DetectFileResponse; +import com.skyflow.generated.rest.types.V1DetectStatusResponse; +import com.skyflow.generated.rest.types.V1DetectTextResponse; +import java.util.concurrent.CompletableFuture; + +public class AsyncDeprecatedClient { + protected final ClientOptions clientOptions; + + private final AsyncRawDeprecatedClient rawClient; + + public AsyncDeprecatedClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawDeprecatedClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawDeprecatedClient withRawResponse() { + return this.rawClient; + } + + /** + * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. + */ + public CompletableFuture detectServiceDetectFileInput(V1DetectFileRequest request) { + return this.rawClient.detectServiceDetectFileInput(request).thenApply(response -> response.body()); + } + + /** + * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. + */ + public CompletableFuture detectServiceDetectFileInput( + V1DetectFileRequest request, RequestOptions requestOptions) { + return this.rawClient + .detectServiceDetectFileInput(request, requestOptions) + .thenApply(response -> response.body()); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. + */ + public CompletableFuture detectServiceDetectStatus(String id) { + return this.rawClient.detectServiceDetectStatus(id).thenApply(response -> response.body()); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. + */ + public CompletableFuture detectServiceDetectStatus( + String id, DetectServiceDetectStatusRequest request) { + return this.rawClient.detectServiceDetectStatus(id, request).thenApply(response -> response.body()); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. + */ + public CompletableFuture detectServiceDetectStatus( + String id, DetectServiceDetectStatusRequest request, RequestOptions requestOptions) { + return this.rawClient + .detectServiceDetectStatus(id, request, requestOptions) + .thenApply(response -> response.body()); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. + */ + public CompletableFuture detectServiceDetectText(DetectServiceDetectTextRequest request) { + return this.rawClient.detectServiceDetectText(request).thenApply(response -> response.body()); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. + */ + public CompletableFuture detectServiceDetectText( + DetectServiceDetectTextRequest request, RequestOptions requestOptions) { + return this.rawClient.detectServiceDetectText(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncRawDeprecatedClient.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncRawDeprecatedClient.java new file mode 100644 index 00000000..9c9ec79a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncRawDeprecatedClient.java @@ -0,0 +1,271 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.deprecated; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectStatusRequest; +import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectTextRequest; +import com.skyflow.generated.rest.resources.deprecated.requests.V1DetectFileRequest; +import com.skyflow.generated.rest.types.V1DetectFileResponse; +import com.skyflow.generated.rest.types.V1DetectStatusResponse; +import com.skyflow.generated.rest.types.V1DetectTextResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawDeprecatedClient { + protected final ClientOptions clientOptions; + + public AsyncRawDeprecatedClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. + */ + public CompletableFuture> detectServiceDetectFileInput( + V1DetectFileRequest request) { + return detectServiceDetectFileInput(request, null); + } + + /** + * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. + */ + public CompletableFuture> detectServiceDetectFileInput( + V1DetectFileRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/file") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetectFileResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. + */ + public CompletableFuture> detectServiceDetectStatus(String id) { + return detectServiceDetectStatus( + id, DetectServiceDetectStatusRequest.builder().build()); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. + */ + public CompletableFuture> detectServiceDetectStatus( + String id, DetectServiceDetectStatusRequest request) { + return detectServiceDetectStatus(id, request, null); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. + */ + public CompletableFuture> detectServiceDetectStatus( + String id, DetectServiceDetectStatusRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/status") + .addPathSegment(id); + if (request.getVaultId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "vault_id", request.getVaultId().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), V1DetectStatusResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. + */ + public CompletableFuture> detectServiceDetectText( + DetectServiceDetectTextRequest request) { + return detectServiceDetectText(request, null); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. + */ + public CompletableFuture> detectServiceDetectText( + DetectServiceDetectTextRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/text") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetectTextResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/DeprecatedClient.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/DeprecatedClient.java new file mode 100644 index 00000000..820a349b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/deprecated/DeprecatedClient.java @@ -0,0 +1,87 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.deprecated; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectStatusRequest; +import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectTextRequest; +import com.skyflow.generated.rest.resources.deprecated.requests.V1DetectFileRequest; +import com.skyflow.generated.rest.types.V1DetectFileResponse; +import com.skyflow.generated.rest.types.V1DetectStatusResponse; +import com.skyflow.generated.rest.types.V1DetectTextResponse; + +public class DeprecatedClient { + protected final ClientOptions clientOptions; + + private final RawDeprecatedClient rawClient; + + public DeprecatedClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawDeprecatedClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawDeprecatedClient withRawResponse() { + return this.rawClient; + } + + /** + * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. + */ + public V1DetectFileResponse detectServiceDetectFileInput(V1DetectFileRequest request) { + return this.rawClient.detectServiceDetectFileInput(request).body(); + } + + /** + * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. + */ + public V1DetectFileResponse detectServiceDetectFileInput( + V1DetectFileRequest request, RequestOptions requestOptions) { + return this.rawClient + .detectServiceDetectFileInput(request, requestOptions) + .body(); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. + */ + public V1DetectStatusResponse detectServiceDetectStatus(String id) { + return this.rawClient.detectServiceDetectStatus(id).body(); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. + */ + public V1DetectStatusResponse detectServiceDetectStatus(String id, DetectServiceDetectStatusRequest request) { + return this.rawClient.detectServiceDetectStatus(id, request).body(); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. + */ + public V1DetectStatusResponse detectServiceDetectStatus( + String id, DetectServiceDetectStatusRequest request, RequestOptions requestOptions) { + return this.rawClient + .detectServiceDetectStatus(id, request, requestOptions) + .body(); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. + */ + public V1DetectTextResponse detectServiceDetectText(DetectServiceDetectTextRequest request) { + return this.rawClient.detectServiceDetectText(request).body(); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. + */ + public V1DetectTextResponse detectServiceDetectText( + DetectServiceDetectTextRequest request, RequestOptions requestOptions) { + return this.rawClient.detectServiceDetectText(request, requestOptions).body(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/RawDeprecatedClient.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/RawDeprecatedClient.java new file mode 100644 index 00000000..4472487f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/deprecated/RawDeprecatedClient.java @@ -0,0 +1,222 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.deprecated; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectStatusRequest; +import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectTextRequest; +import com.skyflow.generated.rest.resources.deprecated.requests.V1DetectFileRequest; +import com.skyflow.generated.rest.types.V1DetectFileResponse; +import com.skyflow.generated.rest.types.V1DetectStatusResponse; +import com.skyflow.generated.rest.types.V1DetectTextResponse; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawDeprecatedClient { + protected final ClientOptions clientOptions; + + public RawDeprecatedClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. + */ + public ApiClientHttpResponse detectServiceDetectFileInput(V1DetectFileRequest request) { + return detectServiceDetectFileInput(request, null); + } + + /** + * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. + */ + public ApiClientHttpResponse detectServiceDetectFileInput( + V1DetectFileRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/file") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetectFileResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. + */ + public ApiClientHttpResponse detectServiceDetectStatus(String id) { + return detectServiceDetectStatus( + id, DetectServiceDetectStatusRequest.builder().build()); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. + */ + public ApiClientHttpResponse detectServiceDetectStatus( + String id, DetectServiceDetectStatusRequest request) { + return detectServiceDetectStatus(id, request, null); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. + */ + public ApiClientHttpResponse detectServiceDetectStatus( + String id, DetectServiceDetectStatusRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/status") + .addPathSegment(id); + if (request.getVaultId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "vault_id", request.getVaultId().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetectStatusResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. + */ + public ApiClientHttpResponse detectServiceDetectText(DetectServiceDetectTextRequest request) { + return detectServiceDetectText(request, null); + } + + /** + * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. + */ + public ApiClientHttpResponse detectServiceDetectText( + DetectServiceDetectTextRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/text") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetectTextResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectStatusRequest.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectStatusRequest.java new file mode 100644 index 00000000..45997db3 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectStatusRequest.java @@ -0,0 +1,101 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.deprecated.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetectServiceDetectStatusRequest.Builder.class) +public final class DetectServiceDetectStatusRequest { + private final Optional vaultId; + + private final Map additionalProperties; + + private DetectServiceDetectStatusRequest(Optional vaultId, Map additionalProperties) { + this.vaultId = vaultId; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vault_id") + public Optional getVaultId() { + return vaultId; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetectServiceDetectStatusRequest && equalTo((DetectServiceDetectStatusRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetectServiceDetectStatusRequest other) { + return vaultId.equals(other.vaultId); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional vaultId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DetectServiceDetectStatusRequest other) { + vaultId(other.getVaultId()); + return this; + } + + /** + *

ID of the vault.

+ */ + @JsonSetter(value = "vault_id", nulls = Nulls.SKIP) + public Builder vaultId(Optional vaultId) { + this.vaultId = vaultId; + return this; + } + + public Builder vaultId(String vaultId) { + this.vaultId = Optional.ofNullable(vaultId); + return this; + } + + public DetectServiceDetectStatusRequest build() { + return new DetectServiceDetectStatusRequest(vaultId, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectTextRequest.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectTextRequest.java new file mode 100644 index 00000000..3c4b4ea2 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectTextRequest.java @@ -0,0 +1,526 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.deprecated.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.DetectDataAccuracy; +import com.skyflow.generated.rest.types.DetectDataEntities; +import com.skyflow.generated.rest.types.DetectRequestDeidentifyOption; +import com.skyflow.generated.rest.types.V1AdvancedOptions; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetectServiceDetectTextRequest.Builder.class) +public final class DetectServiceDetectTextRequest { + private final String text; + + private final String vaultId; + + private final Optional sessionId; + + private final Optional> restrictEntityTypes; + + private final Optional deidentifyTokenFormat; + + private final Optional> allowRegex; + + private final Optional> restrictRegex; + + private final Optional returnEntities; + + private final Optional accuracy; + + private final Optional advancedOptions; + + private final Optional storeEntities; + + private final Map additionalProperties; + + private DetectServiceDetectTextRequest( + String text, + String vaultId, + Optional sessionId, + Optional> restrictEntityTypes, + Optional deidentifyTokenFormat, + Optional> allowRegex, + Optional> restrictRegex, + Optional returnEntities, + Optional accuracy, + Optional advancedOptions, + Optional storeEntities, + Map additionalProperties) { + this.text = text; + this.vaultId = vaultId; + this.sessionId = sessionId; + this.restrictEntityTypes = restrictEntityTypes; + this.deidentifyTokenFormat = deidentifyTokenFormat; + this.allowRegex = allowRegex; + this.restrictRegex = restrictRegex; + this.returnEntities = returnEntities; + this.accuracy = accuracy; + this.advancedOptions = advancedOptions; + this.storeEntities = storeEntities; + this.additionalProperties = additionalProperties; + } + + /** + * @return Data to deidentify. + */ + @JsonProperty("text") + public String getText() { + return text; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return Will give a handle to delete the tokens generated during a specific interaction. + */ + @JsonProperty("session_id") + public Optional getSessionId() { + return sessionId; + } + + /** + * @return Entities to detect and deidentify. + */ + @JsonProperty("restrict_entity_types") + public Optional> getRestrictEntityTypes() { + return restrictEntityTypes; + } + + @JsonProperty("deidentify_token_format") + public Optional getDeidentifyTokenFormat() { + return deidentifyTokenFormat; + } + + /** + * @return Regular expressions to ignore when detecting entities. + */ + @JsonProperty("allow_regex") + public Optional> getAllowRegex() { + return allowRegex; + } + + /** + * @return Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'. + */ + @JsonProperty("restrict_regex") + public Optional> getRestrictRegex() { + return restrictRegex; + } + + /** + * @return If true, returns the details for the detected entities. + */ + @JsonProperty("return_entities") + public Optional getReturnEntities() { + return returnEntities; + } + + @JsonProperty("accuracy") + public Optional getAccuracy() { + return accuracy; + } + + @JsonProperty("advanced_options") + public Optional getAdvancedOptions() { + return advancedOptions; + } + + /** + * @return Indicates whether entities should be stored in the vault. + */ + @JsonProperty("store_entities") + public Optional getStoreEntities() { + return storeEntities; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetectServiceDetectTextRequest && equalTo((DetectServiceDetectTextRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetectServiceDetectTextRequest other) { + return text.equals(other.text) + && vaultId.equals(other.vaultId) + && sessionId.equals(other.sessionId) + && restrictEntityTypes.equals(other.restrictEntityTypes) + && deidentifyTokenFormat.equals(other.deidentifyTokenFormat) + && allowRegex.equals(other.allowRegex) + && restrictRegex.equals(other.restrictRegex) + && returnEntities.equals(other.returnEntities) + && accuracy.equals(other.accuracy) + && advancedOptions.equals(other.advancedOptions) + && storeEntities.equals(other.storeEntities); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.text, + this.vaultId, + this.sessionId, + this.restrictEntityTypes, + this.deidentifyTokenFormat, + this.allowRegex, + this.restrictRegex, + this.returnEntities, + this.accuracy, + this.advancedOptions, + this.storeEntities); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TextStage builder() { + return new Builder(); + } + + public interface TextStage { + /** + * Data to deidentify. + */ + VaultIdStage text(@NotNull String text); + + Builder from(DetectServiceDetectTextRequest other); + } + + public interface VaultIdStage { + /** + * ID of the vault. + */ + _FinalStage vaultId(@NotNull String vaultId); + } + + public interface _FinalStage { + DetectServiceDetectTextRequest build(); + + /** + *

Will give a handle to delete the tokens generated during a specific interaction.

+ */ + _FinalStage sessionId(Optional sessionId); + + _FinalStage sessionId(String sessionId); + + /** + *

Entities to detect and deidentify.

+ */ + _FinalStage restrictEntityTypes(Optional> restrictEntityTypes); + + _FinalStage restrictEntityTypes(List restrictEntityTypes); + + _FinalStage deidentifyTokenFormat(Optional deidentifyTokenFormat); + + _FinalStage deidentifyTokenFormat(DetectRequestDeidentifyOption deidentifyTokenFormat); + + /** + *

Regular expressions to ignore when detecting entities.

+ */ + _FinalStage allowRegex(Optional> allowRegex); + + _FinalStage allowRegex(List allowRegex); + + /** + *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

+ */ + _FinalStage restrictRegex(Optional> restrictRegex); + + _FinalStage restrictRegex(List restrictRegex); + + /** + *

If true, returns the details for the detected entities.

+ */ + _FinalStage returnEntities(Optional returnEntities); + + _FinalStage returnEntities(Boolean returnEntities); + + _FinalStage accuracy(Optional accuracy); + + _FinalStage accuracy(DetectDataAccuracy accuracy); + + _FinalStage advancedOptions(Optional advancedOptions); + + _FinalStage advancedOptions(V1AdvancedOptions advancedOptions); + + /** + *

Indicates whether entities should be stored in the vault.

+ */ + _FinalStage storeEntities(Optional storeEntities); + + _FinalStage storeEntities(Boolean storeEntities); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TextStage, VaultIdStage, _FinalStage { + private String text; + + private String vaultId; + + private Optional storeEntities = Optional.empty(); + + private Optional advancedOptions = Optional.empty(); + + private Optional accuracy = Optional.empty(); + + private Optional returnEntities = Optional.empty(); + + private Optional> restrictRegex = Optional.empty(); + + private Optional> allowRegex = Optional.empty(); + + private Optional deidentifyTokenFormat = Optional.empty(); + + private Optional> restrictEntityTypes = Optional.empty(); + + private Optional sessionId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DetectServiceDetectTextRequest other) { + text(other.getText()); + vaultId(other.getVaultId()); + sessionId(other.getSessionId()); + restrictEntityTypes(other.getRestrictEntityTypes()); + deidentifyTokenFormat(other.getDeidentifyTokenFormat()); + allowRegex(other.getAllowRegex()); + restrictRegex(other.getRestrictRegex()); + returnEntities(other.getReturnEntities()); + accuracy(other.getAccuracy()); + advancedOptions(other.getAdvancedOptions()); + storeEntities(other.getStoreEntities()); + return this; + } + + /** + * Data to deidentify.

Data to deidentify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("text") + public VaultIdStage text(@NotNull String text) { + this.text = Objects.requireNonNull(text, "text must not be null"); + return this; + } + + /** + * ID of the vault.

ID of the vault.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("vault_id") + public _FinalStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + *

Indicates whether entities should be stored in the vault.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage storeEntities(Boolean storeEntities) { + this.storeEntities = Optional.ofNullable(storeEntities); + return this; + } + + /** + *

Indicates whether entities should be stored in the vault.

+ */ + @java.lang.Override + @JsonSetter(value = "store_entities", nulls = Nulls.SKIP) + public _FinalStage storeEntities(Optional storeEntities) { + this.storeEntities = storeEntities; + return this; + } + + @java.lang.Override + public _FinalStage advancedOptions(V1AdvancedOptions advancedOptions) { + this.advancedOptions = Optional.ofNullable(advancedOptions); + return this; + } + + @java.lang.Override + @JsonSetter(value = "advanced_options", nulls = Nulls.SKIP) + public _FinalStage advancedOptions(Optional advancedOptions) { + this.advancedOptions = advancedOptions; + return this; + } + + @java.lang.Override + public _FinalStage accuracy(DetectDataAccuracy accuracy) { + this.accuracy = Optional.ofNullable(accuracy); + return this; + } + + @java.lang.Override + @JsonSetter(value = "accuracy", nulls = Nulls.SKIP) + public _FinalStage accuracy(Optional accuracy) { + this.accuracy = accuracy; + return this; + } + + /** + *

If true, returns the details for the detected entities.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage returnEntities(Boolean returnEntities) { + this.returnEntities = Optional.ofNullable(returnEntities); + return this; + } + + /** + *

If true, returns the details for the detected entities.

+ */ + @java.lang.Override + @JsonSetter(value = "return_entities", nulls = Nulls.SKIP) + public _FinalStage returnEntities(Optional returnEntities) { + this.returnEntities = returnEntities; + return this; + } + + /** + *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage restrictRegex(List restrictRegex) { + this.restrictRegex = Optional.ofNullable(restrictRegex); + return this; + } + + /** + *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

+ */ + @java.lang.Override + @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) + public _FinalStage restrictRegex(Optional> restrictRegex) { + this.restrictRegex = restrictRegex; + return this; + } + + /** + *

Regular expressions to ignore when detecting entities.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage allowRegex(List allowRegex) { + this.allowRegex = Optional.ofNullable(allowRegex); + return this; + } + + /** + *

Regular expressions to ignore when detecting entities.

+ */ + @java.lang.Override + @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) + public _FinalStage allowRegex(Optional> allowRegex) { + this.allowRegex = allowRegex; + return this; + } + + @java.lang.Override + public _FinalStage deidentifyTokenFormat(DetectRequestDeidentifyOption deidentifyTokenFormat) { + this.deidentifyTokenFormat = Optional.ofNullable(deidentifyTokenFormat); + return this; + } + + @java.lang.Override + @JsonSetter(value = "deidentify_token_format", nulls = Nulls.SKIP) + public _FinalStage deidentifyTokenFormat(Optional deidentifyTokenFormat) { + this.deidentifyTokenFormat = deidentifyTokenFormat; + return this; + } + + /** + *

Entities to detect and deidentify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage restrictEntityTypes(List restrictEntityTypes) { + this.restrictEntityTypes = Optional.ofNullable(restrictEntityTypes); + return this; + } + + /** + *

Entities to detect and deidentify.

+ */ + @java.lang.Override + @JsonSetter(value = "restrict_entity_types", nulls = Nulls.SKIP) + public _FinalStage restrictEntityTypes(Optional> restrictEntityTypes) { + this.restrictEntityTypes = restrictEntityTypes; + return this; + } + + /** + *

Will give a handle to delete the tokens generated during a specific interaction.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(String sessionId) { + this.sessionId = Optional.ofNullable(sessionId); + return this; + } + + /** + *

Will give a handle to delete the tokens generated during a specific interaction.

+ */ + @java.lang.Override + @JsonSetter(value = "session_id", nulls = Nulls.SKIP) + public _FinalStage sessionId(Optional sessionId) { + this.sessionId = sessionId; + return this; + } + + @java.lang.Override + public DetectServiceDetectTextRequest build() { + return new DetectServiceDetectTextRequest( + text, + vaultId, + sessionId, + restrictEntityTypes, + deidentifyTokenFormat, + allowRegex, + restrictRegex, + returnEntities, + accuracy, + advancedOptions, + storeEntities, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/V1DetectFileRequest.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/V1DetectFileRequest.java new file mode 100644 index 00000000..8bdee935 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/V1DetectFileRequest.java @@ -0,0 +1,634 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.deprecated.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.DetectDataAccuracy; +import com.skyflow.generated.rest.types.DetectDataEntities; +import com.skyflow.generated.rest.types.DetectFileRequestDataType; +import com.skyflow.generated.rest.types.DetectRequestDeidentifyOption; +import com.skyflow.generated.rest.types.V1AdvancedOptions; +import com.skyflow.generated.rest.types.V1AudioConfig; +import com.skyflow.generated.rest.types.V1FileDataFormat; +import com.skyflow.generated.rest.types.V1ImageOptions; +import com.skyflow.generated.rest.types.V1PdfConfig; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1DetectFileRequest.Builder.class) +public final class V1DetectFileRequest { + private final String file; + + private final V1FileDataFormat dataFormat; + + private final DetectFileRequestDataType inputType; + + private final String vaultId; + + private final Optional sessionId; + + private final Optional> restrictEntityTypes; + + private final Optional> allowRegex; + + private final Optional> restrictRegex; + + private final Optional returnEntities; + + private final Optional accuracy; + + private final Optional audio; + + private final Optional image; + + private final Optional pdf; + + private final Optional advancedOptions; + + private final Optional deidentifyTokenFormat; + + private final Map additionalProperties; + + private V1DetectFileRequest( + String file, + V1FileDataFormat dataFormat, + DetectFileRequestDataType inputType, + String vaultId, + Optional sessionId, + Optional> restrictEntityTypes, + Optional> allowRegex, + Optional> restrictRegex, + Optional returnEntities, + Optional accuracy, + Optional audio, + Optional image, + Optional pdf, + Optional advancedOptions, + Optional deidentifyTokenFormat, + Map additionalProperties) { + this.file = file; + this.dataFormat = dataFormat; + this.inputType = inputType; + this.vaultId = vaultId; + this.sessionId = sessionId; + this.restrictEntityTypes = restrictEntityTypes; + this.allowRegex = allowRegex; + this.restrictRegex = restrictRegex; + this.returnEntities = returnEntities; + this.accuracy = accuracy; + this.audio = audio; + this.image = image; + this.pdf = pdf; + this.advancedOptions = advancedOptions; + this.deidentifyTokenFormat = deidentifyTokenFormat; + this.additionalProperties = additionalProperties; + } + + /** + * @return Path of the file or base64-encoded data that has to be processed. + */ + @JsonProperty("file") + public String getFile() { + return file; + } + + @JsonProperty("data_format") + public V1FileDataFormat getDataFormat() { + return dataFormat; + } + + @JsonProperty("input_type") + public DetectFileRequestDataType getInputType() { + return inputType; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return Will give a handle to delete the tokens generated during a specific interaction. + */ + @JsonProperty("session_id") + public Optional getSessionId() { + return sessionId; + } + + /** + * @return Entities to detect and deidentify. + */ + @JsonProperty("restrict_entity_types") + public Optional> getRestrictEntityTypes() { + return restrictEntityTypes; + } + + /** + * @return Regular expressions to ignore when detecting entities. + */ + @JsonProperty("allow_regex") + public Optional> getAllowRegex() { + return allowRegex; + } + + /** + * @return Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'. + */ + @JsonProperty("restrict_regex") + public Optional> getRestrictRegex() { + return restrictRegex; + } + + /** + * @return If true, returns the details for the detected entities. + */ + @JsonProperty("return_entities") + public Optional getReturnEntities() { + return returnEntities; + } + + @JsonProperty("accuracy") + public Optional getAccuracy() { + return accuracy; + } + + @JsonProperty("audio") + public Optional getAudio() { + return audio; + } + + @JsonProperty("image") + public Optional getImage() { + return image; + } + + @JsonProperty("pdf") + public Optional getPdf() { + return pdf; + } + + @JsonProperty("advanced_options") + public Optional getAdvancedOptions() { + return advancedOptions; + } + + @JsonProperty("deidentify_token_format") + public Optional getDeidentifyTokenFormat() { + return deidentifyTokenFormat; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1DetectFileRequest && equalTo((V1DetectFileRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1DetectFileRequest other) { + return file.equals(other.file) + && dataFormat.equals(other.dataFormat) + && inputType.equals(other.inputType) + && vaultId.equals(other.vaultId) + && sessionId.equals(other.sessionId) + && restrictEntityTypes.equals(other.restrictEntityTypes) + && allowRegex.equals(other.allowRegex) + && restrictRegex.equals(other.restrictRegex) + && returnEntities.equals(other.returnEntities) + && accuracy.equals(other.accuracy) + && audio.equals(other.audio) + && image.equals(other.image) + && pdf.equals(other.pdf) + && advancedOptions.equals(other.advancedOptions) + && deidentifyTokenFormat.equals(other.deidentifyTokenFormat); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.file, + this.dataFormat, + this.inputType, + this.vaultId, + this.sessionId, + this.restrictEntityTypes, + this.allowRegex, + this.restrictRegex, + this.returnEntities, + this.accuracy, + this.audio, + this.image, + this.pdf, + this.advancedOptions, + this.deidentifyTokenFormat); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static FileStage builder() { + return new Builder(); + } + + public interface FileStage { + /** + * Path of the file or base64-encoded data that has to be processed. + */ + DataFormatStage file(@NotNull String file); + + Builder from(V1DetectFileRequest other); + } + + public interface DataFormatStage { + InputTypeStage dataFormat(@NotNull V1FileDataFormat dataFormat); + } + + public interface InputTypeStage { + VaultIdStage inputType(@NotNull DetectFileRequestDataType inputType); + } + + public interface VaultIdStage { + /** + * ID of the vault. + */ + _FinalStage vaultId(@NotNull String vaultId); + } + + public interface _FinalStage { + V1DetectFileRequest build(); + + /** + *

Will give a handle to delete the tokens generated during a specific interaction.

+ */ + _FinalStage sessionId(Optional sessionId); + + _FinalStage sessionId(String sessionId); + + /** + *

Entities to detect and deidentify.

+ */ + _FinalStage restrictEntityTypes(Optional> restrictEntityTypes); + + _FinalStage restrictEntityTypes(List restrictEntityTypes); + + /** + *

Regular expressions to ignore when detecting entities.

+ */ + _FinalStage allowRegex(Optional> allowRegex); + + _FinalStage allowRegex(List allowRegex); + + /** + *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

+ */ + _FinalStage restrictRegex(Optional> restrictRegex); + + _FinalStage restrictRegex(List restrictRegex); + + /** + *

If true, returns the details for the detected entities.

+ */ + _FinalStage returnEntities(Optional returnEntities); + + _FinalStage returnEntities(Boolean returnEntities); + + _FinalStage accuracy(Optional accuracy); + + _FinalStage accuracy(DetectDataAccuracy accuracy); + + _FinalStage audio(Optional audio); + + _FinalStage audio(V1AudioConfig audio); + + _FinalStage image(Optional image); + + _FinalStage image(V1ImageOptions image); + + _FinalStage pdf(Optional pdf); + + _FinalStage pdf(V1PdfConfig pdf); + + _FinalStage advancedOptions(Optional advancedOptions); + + _FinalStage advancedOptions(V1AdvancedOptions advancedOptions); + + _FinalStage deidentifyTokenFormat(Optional deidentifyTokenFormat); + + _FinalStage deidentifyTokenFormat(DetectRequestDeidentifyOption deidentifyTokenFormat); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements FileStage, DataFormatStage, InputTypeStage, VaultIdStage, _FinalStage { + private String file; + + private V1FileDataFormat dataFormat; + + private DetectFileRequestDataType inputType; + + private String vaultId; + + private Optional deidentifyTokenFormat = Optional.empty(); + + private Optional advancedOptions = Optional.empty(); + + private Optional pdf = Optional.empty(); + + private Optional image = Optional.empty(); + + private Optional audio = Optional.empty(); + + private Optional accuracy = Optional.empty(); + + private Optional returnEntities = Optional.empty(); + + private Optional> restrictRegex = Optional.empty(); + + private Optional> allowRegex = Optional.empty(); + + private Optional> restrictEntityTypes = Optional.empty(); + + private Optional sessionId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(V1DetectFileRequest other) { + file(other.getFile()); + dataFormat(other.getDataFormat()); + inputType(other.getInputType()); + vaultId(other.getVaultId()); + sessionId(other.getSessionId()); + restrictEntityTypes(other.getRestrictEntityTypes()); + allowRegex(other.getAllowRegex()); + restrictRegex(other.getRestrictRegex()); + returnEntities(other.getReturnEntities()); + accuracy(other.getAccuracy()); + audio(other.getAudio()); + image(other.getImage()); + pdf(other.getPdf()); + advancedOptions(other.getAdvancedOptions()); + deidentifyTokenFormat(other.getDeidentifyTokenFormat()); + return this; + } + + /** + * Path of the file or base64-encoded data that has to be processed.

Path of the file or base64-encoded data that has to be processed.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("file") + public DataFormatStage file(@NotNull String file) { + this.file = Objects.requireNonNull(file, "file must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("data_format") + public InputTypeStage dataFormat(@NotNull V1FileDataFormat dataFormat) { + this.dataFormat = Objects.requireNonNull(dataFormat, "dataFormat must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("input_type") + public VaultIdStage inputType(@NotNull DetectFileRequestDataType inputType) { + this.inputType = Objects.requireNonNull(inputType, "inputType must not be null"); + return this; + } + + /** + * ID of the vault.

ID of the vault.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("vault_id") + public _FinalStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage deidentifyTokenFormat(DetectRequestDeidentifyOption deidentifyTokenFormat) { + this.deidentifyTokenFormat = Optional.ofNullable(deidentifyTokenFormat); + return this; + } + + @java.lang.Override + @JsonSetter(value = "deidentify_token_format", nulls = Nulls.SKIP) + public _FinalStage deidentifyTokenFormat(Optional deidentifyTokenFormat) { + this.deidentifyTokenFormat = deidentifyTokenFormat; + return this; + } + + @java.lang.Override + public _FinalStage advancedOptions(V1AdvancedOptions advancedOptions) { + this.advancedOptions = Optional.ofNullable(advancedOptions); + return this; + } + + @java.lang.Override + @JsonSetter(value = "advanced_options", nulls = Nulls.SKIP) + public _FinalStage advancedOptions(Optional advancedOptions) { + this.advancedOptions = advancedOptions; + return this; + } + + @java.lang.Override + public _FinalStage pdf(V1PdfConfig pdf) { + this.pdf = Optional.ofNullable(pdf); + return this; + } + + @java.lang.Override + @JsonSetter(value = "pdf", nulls = Nulls.SKIP) + public _FinalStage pdf(Optional pdf) { + this.pdf = pdf; + return this; + } + + @java.lang.Override + public _FinalStage image(V1ImageOptions image) { + this.image = Optional.ofNullable(image); + return this; + } + + @java.lang.Override + @JsonSetter(value = "image", nulls = Nulls.SKIP) + public _FinalStage image(Optional image) { + this.image = image; + return this; + } + + @java.lang.Override + public _FinalStage audio(V1AudioConfig audio) { + this.audio = Optional.ofNullable(audio); + return this; + } + + @java.lang.Override + @JsonSetter(value = "audio", nulls = Nulls.SKIP) + public _FinalStage audio(Optional audio) { + this.audio = audio; + return this; + } + + @java.lang.Override + public _FinalStage accuracy(DetectDataAccuracy accuracy) { + this.accuracy = Optional.ofNullable(accuracy); + return this; + } + + @java.lang.Override + @JsonSetter(value = "accuracy", nulls = Nulls.SKIP) + public _FinalStage accuracy(Optional accuracy) { + this.accuracy = accuracy; + return this; + } + + /** + *

If true, returns the details for the detected entities.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage returnEntities(Boolean returnEntities) { + this.returnEntities = Optional.ofNullable(returnEntities); + return this; + } + + /** + *

If true, returns the details for the detected entities.

+ */ + @java.lang.Override + @JsonSetter(value = "return_entities", nulls = Nulls.SKIP) + public _FinalStage returnEntities(Optional returnEntities) { + this.returnEntities = returnEntities; + return this; + } + + /** + *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage restrictRegex(List restrictRegex) { + this.restrictRegex = Optional.ofNullable(restrictRegex); + return this; + } + + /** + *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

+ */ + @java.lang.Override + @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) + public _FinalStage restrictRegex(Optional> restrictRegex) { + this.restrictRegex = restrictRegex; + return this; + } + + /** + *

Regular expressions to ignore when detecting entities.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage allowRegex(List allowRegex) { + this.allowRegex = Optional.ofNullable(allowRegex); + return this; + } + + /** + *

Regular expressions to ignore when detecting entities.

+ */ + @java.lang.Override + @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) + public _FinalStage allowRegex(Optional> allowRegex) { + this.allowRegex = allowRegex; + return this; + } + + /** + *

Entities to detect and deidentify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage restrictEntityTypes(List restrictEntityTypes) { + this.restrictEntityTypes = Optional.ofNullable(restrictEntityTypes); + return this; + } + + /** + *

Entities to detect and deidentify.

+ */ + @java.lang.Override + @JsonSetter(value = "restrict_entity_types", nulls = Nulls.SKIP) + public _FinalStage restrictEntityTypes(Optional> restrictEntityTypes) { + this.restrictEntityTypes = restrictEntityTypes; + return this; + } + + /** + *

Will give a handle to delete the tokens generated during a specific interaction.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(String sessionId) { + this.sessionId = Optional.ofNullable(sessionId); + return this; + } + + /** + *

Will give a handle to delete the tokens generated during a specific interaction.

+ */ + @java.lang.Override + @JsonSetter(value = "session_id", nulls = Nulls.SKIP) + public _FinalStage sessionId(Optional sessionId) { + this.sessionId = sessionId; + return this; + } + + @java.lang.Override + public V1DetectFileRequest build() { + return new V1DetectFileRequest( + file, + dataFormat, + inputType, + vaultId, + sessionId, + restrictEntityTypes, + allowRegex, + restrictRegex, + returnEntities, + accuracy, + audio, + image, + pdf, + advancedOptions, + deidentifyTokenFormat, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/AsyncFilesClient.java b/src/main/java/com/skyflow/generated/rest/resources/files/AsyncFilesClient.java new file mode 100644 index 00000000..48692d9f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/AsyncFilesClient.java @@ -0,0 +1,188 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyAudioRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyDocumentRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyImageRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyPdfRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyPresentationRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifySpreadsheetRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyStructuredTextRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest; +import com.skyflow.generated.rest.resources.files.requests.GetRunRequest; +import com.skyflow.generated.rest.types.DeidentifyFileResponse; +import com.skyflow.generated.rest.types.DeidentifyStatusResponse; +import java.util.concurrent.CompletableFuture; + +public class AsyncFilesClient { + protected final ClientOptions clientOptions; + + private final AsyncRawFilesClient rawClient; + + public AsyncFilesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawFilesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawFilesClient withRawResponse() { + return this.rawClient; + } + + /** + * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + */ + public CompletableFuture deidentifyFile(DeidentifyFileRequest request) { + return this.rawClient.deidentifyFile(request).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + */ + public CompletableFuture deidentifyFile( + DeidentifyFileRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyFile(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyDocument(DeidentifyDocumentRequest request) { + return this.rawClient.deidentifyDocument(request).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyDocument( + DeidentifyDocumentRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyDocument(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyPdf(DeidentifyPdfRequest request) { + return this.rawClient.deidentifyPdf(request).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyPdf( + DeidentifyPdfRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyPdf(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyImage(DeidentifyImageRequest request) { + return this.rawClient.deidentifyImage(request).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyImage( + DeidentifyImageRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyImage(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyText(DeidentifyTextRequest request) { + return this.rawClient.deidentifyText(request).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyText( + DeidentifyTextRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyText(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyStructuredText(DeidentifyStructuredTextRequest request) { + return this.rawClient.deidentifyStructuredText(request).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyStructuredText( + DeidentifyStructuredTextRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyStructuredText(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifySpreadsheet(DeidentifySpreadsheetRequest request) { + return this.rawClient.deidentifySpreadsheet(request).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifySpreadsheet( + DeidentifySpreadsheetRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifySpreadsheet(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyPresentation(DeidentifyPresentationRequest request) { + return this.rawClient.deidentifyPresentation(request).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyPresentation( + DeidentifyPresentationRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyPresentation(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyAudio(DeidentifyAudioRequest request) { + return this.rawClient.deidentifyAudio(request).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture deidentifyAudio( + DeidentifyAudioRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyAudio(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Returns the status of the detect run. + */ + public CompletableFuture getRun(String runId, GetRunRequest request) { + return this.rawClient.getRun(runId, request).thenApply(response -> response.body()); + } + + /** + * Returns the status of the detect run. + */ + public CompletableFuture getRun( + String runId, GetRunRequest request, RequestOptions requestOptions) { + return this.rawClient.getRun(runId, request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/AsyncRawFilesClient.java b/src/main/java/com/skyflow/generated/rest/resources/files/AsyncRawFilesClient.java new file mode 100644 index 00000000..f400bb2a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/AsyncRawFilesClient.java @@ -0,0 +1,929 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.InternalServerError; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.errors.UnauthorizedError; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyAudioRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyDocumentRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyImageRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyPdfRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyPresentationRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifySpreadsheetRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyStructuredTextRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest; +import com.skyflow.generated.rest.resources.files.requests.GetRunRequest; +import com.skyflow.generated.rest.types.DeidentifyFileResponse; +import com.skyflow.generated.rest.types.DeidentifyStatusResponse; +import com.skyflow.generated.rest.types.ErrorResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawFilesClient { + protected final ClientOptions clientOptions; + + public AsyncRawFilesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + */ + public CompletableFuture> deidentifyFile( + DeidentifyFileRequest request) { + return deidentifyFile(request, null); + } + + /** + * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + */ + public CompletableFuture> deidentifyFile( + DeidentifyFileRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), DeidentifyFileResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyDocument( + DeidentifyDocumentRequest request) { + return deidentifyDocument(request, null); + } + + /** + * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyDocument( + DeidentifyDocumentRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/document") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), DeidentifyFileResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyPdf( + DeidentifyPdfRequest request) { + return deidentifyPdf(request, null); + } + + /** + * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyPdf( + DeidentifyPdfRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/document/pdf") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), DeidentifyFileResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyImage( + DeidentifyImageRequest request) { + return deidentifyImage(request, null); + } + + /** + * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyImage( + DeidentifyImageRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/image") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), DeidentifyFileResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyText( + DeidentifyTextRequest request) { + return deidentifyText(request, null); + } + + /** + * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyText( + DeidentifyTextRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/text") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), DeidentifyFileResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyStructuredText( + DeidentifyStructuredTextRequest request) { + return deidentifyStructuredText(request, null); + } + + /** + * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyStructuredText( + DeidentifyStructuredTextRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/structured_text") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), DeidentifyFileResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifySpreadsheet( + DeidentifySpreadsheetRequest request) { + return deidentifySpreadsheet(request, null); + } + + /** + * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifySpreadsheet( + DeidentifySpreadsheetRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/spreadsheet") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), DeidentifyFileResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyPresentation( + DeidentifyPresentationRequest request) { + return deidentifyPresentation(request, null); + } + + /** + * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyPresentation( + DeidentifyPresentationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/presentation") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), DeidentifyFileResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyAudio( + DeidentifyAudioRequest request) { + return deidentifyAudio(request, null); + } + + /** + * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public CompletableFuture> deidentifyAudio( + DeidentifyAudioRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/audio") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), DeidentifyFileResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Returns the status of the detect run. + */ + public CompletableFuture> getRun( + String runId, GetRunRequest request) { + return getRun(runId, request, null); + } + + /** + * Returns the status of the detect run. + */ + public CompletableFuture> getRun( + String runId, GetRunRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/runs") + .addPathSegment(runId); + QueryStringMapper.addQueryParameter(httpUrl, "vault_id", request.getVaultId(), false); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), DeidentifyStatusResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/FilesClient.java b/src/main/java/com/skyflow/generated/rest/resources/files/FilesClient.java new file mode 100644 index 00000000..89898d41 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/FilesClient.java @@ -0,0 +1,180 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyAudioRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyDocumentRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyImageRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyPdfRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyPresentationRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifySpreadsheetRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyStructuredTextRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest; +import com.skyflow.generated.rest.resources.files.requests.GetRunRequest; +import com.skyflow.generated.rest.types.DeidentifyFileResponse; +import com.skyflow.generated.rest.types.DeidentifyStatusResponse; + +public class FilesClient { + protected final ClientOptions clientOptions; + + private final RawFilesClient rawClient; + + public FilesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawFilesClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawFilesClient withRawResponse() { + return this.rawClient; + } + + /** + * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + */ + public DeidentifyFileResponse deidentifyFile(DeidentifyFileRequest request) { + return this.rawClient.deidentifyFile(request).body(); + } + + /** + * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + */ + public DeidentifyFileResponse deidentifyFile(DeidentifyFileRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyFile(request, requestOptions).body(); + } + + /** + * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyDocument(DeidentifyDocumentRequest request) { + return this.rawClient.deidentifyDocument(request).body(); + } + + /** + * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyDocument(DeidentifyDocumentRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyDocument(request, requestOptions).body(); + } + + /** + * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyPdf(DeidentifyPdfRequest request) { + return this.rawClient.deidentifyPdf(request).body(); + } + + /** + * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyPdf(DeidentifyPdfRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyPdf(request, requestOptions).body(); + } + + /** + * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyImage(DeidentifyImageRequest request) { + return this.rawClient.deidentifyImage(request).body(); + } + + /** + * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyImage(DeidentifyImageRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyImage(request, requestOptions).body(); + } + + /** + * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyText(DeidentifyTextRequest request) { + return this.rawClient.deidentifyText(request).body(); + } + + /** + * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyText(DeidentifyTextRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyText(request, requestOptions).body(); + } + + /** + * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyStructuredText(DeidentifyStructuredTextRequest request) { + return this.rawClient.deidentifyStructuredText(request).body(); + } + + /** + * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyStructuredText( + DeidentifyStructuredTextRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyStructuredText(request, requestOptions).body(); + } + + /** + * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifySpreadsheet(DeidentifySpreadsheetRequest request) { + return this.rawClient.deidentifySpreadsheet(request).body(); + } + + /** + * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifySpreadsheet( + DeidentifySpreadsheetRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifySpreadsheet(request, requestOptions).body(); + } + + /** + * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyPresentation(DeidentifyPresentationRequest request) { + return this.rawClient.deidentifyPresentation(request).body(); + } + + /** + * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyPresentation( + DeidentifyPresentationRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyPresentation(request, requestOptions).body(); + } + + /** + * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyAudio(DeidentifyAudioRequest request) { + return this.rawClient.deidentifyAudio(request).body(); + } + + /** + * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public DeidentifyFileResponse deidentifyAudio(DeidentifyAudioRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyAudio(request, requestOptions).body(); + } + + /** + * Returns the status of the detect run. + */ + public DeidentifyStatusResponse getRun(String runId, GetRunRequest request) { + return this.rawClient.getRun(runId, request).body(); + } + + /** + * Returns the status of the detect run. + */ + public DeidentifyStatusResponse getRun(String runId, GetRunRequest request, RequestOptions requestOptions) { + return this.rawClient.getRun(runId, request, requestOptions).body(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/RawFilesClient.java b/src/main/java/com/skyflow/generated/rest/resources/files/RawFilesClient.java new file mode 100644 index 00000000..85939625 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/RawFilesClient.java @@ -0,0 +1,714 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.InternalServerError; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.errors.UnauthorizedError; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyAudioRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyDocumentRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyImageRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyPdfRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyPresentationRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifySpreadsheetRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyStructuredTextRequest; +import com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest; +import com.skyflow.generated.rest.resources.files.requests.GetRunRequest; +import com.skyflow.generated.rest.types.DeidentifyFileResponse; +import com.skyflow.generated.rest.types.DeidentifyStatusResponse; +import com.skyflow.generated.rest.types.ErrorResponse; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawFilesClient { + protected final ClientOptions clientOptions; + + public RawFilesClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + */ + public ApiClientHttpResponse deidentifyFile(DeidentifyFileRequest request) { + return deidentifyFile(request, null); + } + + /** + * De-identifies sensitive data from a file. This operation includes options applicable to all supported file types.<br/><br/>For more specific options, see the category-specific operations (like <a href='#deidentify_document'>De-identify Document</a>) and the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>). + */ + public ApiClientHttpResponse deidentifyFile( + DeidentifyFileRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyDocument(DeidentifyDocumentRequest request) { + return deidentifyDocument(request, null); + } + + /** + * De-identifies sensitive data from a document file. This operation includes options applicable to all supported document file types.<br/><br/>For more specific options, see the file type-specific opertions (like <a href='#deidentify_pdf'>De-identify PDF</a>) where they're available. For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyDocument( + DeidentifyDocumentRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/document") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyPdf(DeidentifyPdfRequest request) { + return deidentifyPdf(request, null); + } + + /** + * De-identifies sensitive data from a PDF file. This operation includes options specific to PDF files.<br/><br/>For broader file type support, see <a href='#deidentify_document'>De-identify Document</a> and <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyPdf( + DeidentifyPdfRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/document/pdf") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyImage(DeidentifyImageRequest request) { + return deidentifyImage(request, null); + } + + /** + * De-identifies sensitive data from an image file. This operation includes options applicable to all supported image file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyImage( + DeidentifyImageRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/image") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyText(DeidentifyTextRequest request) { + return deidentifyText(request, null); + } + + /** + * De-identifies sensitive data from a text file. This operation includes options applicable to all supported image text types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyText( + DeidentifyTextRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/text") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyStructuredText( + DeidentifyStructuredTextRequest request) { + return deidentifyStructuredText(request, null); + } + + /** + * De-identifies sensitive data from a structured text file. This operation includes options applicable to all supported structured text file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyStructuredText( + DeidentifyStructuredTextRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/structured_text") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifySpreadsheet(DeidentifySpreadsheetRequest request) { + return deidentifySpreadsheet(request, null); + } + + /** + * De-identifies sensitive data from a spreadsheet file. This operation includes options applicable to all supported spreadsheet file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifySpreadsheet( + DeidentifySpreadsheetRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/spreadsheet") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyPresentation(DeidentifyPresentationRequest request) { + return deidentifyPresentation(request, null); + } + + /** + * De-identifies sensitive data from a presentation file. This operation includes options applicable to all supported presentation file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyPresentation( + DeidentifyPresentationRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/presentation") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyAudio(DeidentifyAudioRequest request) { + return deidentifyAudio(request, null); + } + + /** + * De-identifies sensitive data from an audio file. This operation includes options applicable to all supported audio file types.<br/><br/>For broader file type support, see <a href='#deidentify_file'>De-identify File</a>. + */ + public ApiClientHttpResponse deidentifyAudio( + DeidentifyAudioRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/file/audio") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyFileResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Returns the status of the detect run. + */ + public ApiClientHttpResponse getRun(String runId, GetRunRequest request) { + return getRun(runId, request, null); + } + + /** + * Returns the status of the detect run. + */ + public ApiClientHttpResponse getRun( + String runId, GetRunRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/runs") + .addPathSegment(runId); + QueryStringMapper.addQueryParameter(httpUrl, "vault_id", request.getVaultId(), false); + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyStatusResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyAudioRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyAudioRequest.java new file mode 100644 index 00000000..5f4929aa --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyAudioRequest.java @@ -0,0 +1,582 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.files.types.DeidentifyAudioRequestFile; +import com.skyflow.generated.rest.resources.files.types.DeidentifyAudioRequestOutputTranscription; +import com.skyflow.generated.rest.types.EntityType; +import com.skyflow.generated.rest.types.TokenTypeWithoutVault; +import com.skyflow.generated.rest.types.Transformations; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyAudioRequest.Builder.class) +public final class DeidentifyAudioRequest { + private final String vaultId; + + private final DeidentifyAudioRequestFile file; + + private final Optional outputProcessedAudio; + + private final Optional outputTranscription; + + private final Optional bleepGain; + + private final Optional bleepFrequency; + + private final Optional bleepStartPadding; + + private final Optional bleepStopPadding; + + private final Optional> entityTypes; + + private final Optional tokenType; + + private final Optional> allowRegex; + + private final Optional> restrictRegex; + + private final Optional transformations; + + private final Map additionalProperties; + + private DeidentifyAudioRequest( + String vaultId, + DeidentifyAudioRequestFile file, + Optional outputProcessedAudio, + Optional outputTranscription, + Optional bleepGain, + Optional bleepFrequency, + Optional bleepStartPadding, + Optional bleepStopPadding, + Optional> entityTypes, + Optional tokenType, + Optional> allowRegex, + Optional> restrictRegex, + Optional transformations, + Map additionalProperties) { + this.vaultId = vaultId; + this.file = file; + this.outputProcessedAudio = outputProcessedAudio; + this.outputTranscription = outputTranscription; + this.bleepGain = bleepGain; + this.bleepFrequency = bleepFrequency; + this.bleepStartPadding = bleepStartPadding; + this.bleepStopPadding = bleepStopPadding; + this.entityTypes = entityTypes; + this.tokenType = tokenType; + this.allowRegex = allowRegex; + this.restrictRegex = restrictRegex; + this.transformations = transformations; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return File to de-identify. Files are specified as Base64-encoded data. + */ + @JsonProperty("file") + public DeidentifyAudioRequestFile getFile() { + return file; + } + + /** + * @return If true, includes processed audio file in the response. + */ + @JsonProperty("output_processed_audio") + public Optional getOutputProcessedAudio() { + return outputProcessedAudio; + } + + /** + * @return Type of transcription to output. + */ + @JsonProperty("output_transcription") + public Optional getOutputTranscription() { + return outputTranscription; + } + + /** + * @return Relative loudness of the bleep in dB. Positive values increase its loudness, and negative values decrease it. + */ + @JsonProperty("bleep_gain") + public Optional getBleepGain() { + return bleepGain; + } + + /** + * @return The pitch of the bleep sound, in Hz. The higher the number, the higher the pitch. + */ + @JsonProperty("bleep_frequency") + public Optional getBleepFrequency() { + return bleepFrequency; + } + + /** + * @return Padding added to the beginning of a bleep, in seconds. + */ + @JsonProperty("bleep_start_padding") + public Optional getBleepStartPadding() { + return bleepStartPadding; + } + + /** + * @return Padding added to the end of a bleep, in seconds. + */ + @JsonProperty("bleep_stop_padding") + public Optional getBleepStopPadding() { + return bleepStopPadding; + } + + @JsonProperty("entity_types") + public Optional> getEntityTypes() { + return entityTypes; + } + + @JsonProperty("token_type") + public Optional getTokenType() { + return tokenType; + } + + @JsonProperty("allow_regex") + public Optional> getAllowRegex() { + return allowRegex; + } + + @JsonProperty("restrict_regex") + public Optional> getRestrictRegex() { + return restrictRegex; + } + + @JsonProperty("transformations") + public Optional getTransformations() { + return transformations; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyAudioRequest && equalTo((DeidentifyAudioRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyAudioRequest other) { + return vaultId.equals(other.vaultId) + && file.equals(other.file) + && outputProcessedAudio.equals(other.outputProcessedAudio) + && outputTranscription.equals(other.outputTranscription) + && bleepGain.equals(other.bleepGain) + && bleepFrequency.equals(other.bleepFrequency) + && bleepStartPadding.equals(other.bleepStartPadding) + && bleepStopPadding.equals(other.bleepStopPadding) + && entityTypes.equals(other.entityTypes) + && tokenType.equals(other.tokenType) + && allowRegex.equals(other.allowRegex) + && restrictRegex.equals(other.restrictRegex) + && transformations.equals(other.transformations); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.vaultId, + this.file, + this.outputProcessedAudio, + this.outputTranscription, + this.bleepGain, + this.bleepFrequency, + this.bleepStartPadding, + this.bleepStopPadding, + this.entityTypes, + this.tokenType, + this.allowRegex, + this.restrictRegex, + this.transformations); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + FileStage vaultId(@NotNull String vaultId); + + Builder from(DeidentifyAudioRequest other); + } + + public interface FileStage { + /** + * File to de-identify. Files are specified as Base64-encoded data. + */ + _FinalStage file(@NotNull DeidentifyAudioRequestFile file); + } + + public interface _FinalStage { + DeidentifyAudioRequest build(); + + /** + *

If true, includes processed audio file in the response.

+ */ + _FinalStage outputProcessedAudio(Optional outputProcessedAudio); + + _FinalStage outputProcessedAudio(Boolean outputProcessedAudio); + + /** + *

Type of transcription to output.

+ */ + _FinalStage outputTranscription(Optional outputTranscription); + + _FinalStage outputTranscription(DeidentifyAudioRequestOutputTranscription outputTranscription); + + /** + *

Relative loudness of the bleep in dB. Positive values increase its loudness, and negative values decrease it.

+ */ + _FinalStage bleepGain(Optional bleepGain); + + _FinalStage bleepGain(Double bleepGain); + + /** + *

The pitch of the bleep sound, in Hz. The higher the number, the higher the pitch.

+ */ + _FinalStage bleepFrequency(Optional bleepFrequency); + + _FinalStage bleepFrequency(Double bleepFrequency); + + /** + *

Padding added to the beginning of a bleep, in seconds.

+ */ + _FinalStage bleepStartPadding(Optional bleepStartPadding); + + _FinalStage bleepStartPadding(Double bleepStartPadding); + + /** + *

Padding added to the end of a bleep, in seconds.

+ */ + _FinalStage bleepStopPadding(Optional bleepStopPadding); + + _FinalStage bleepStopPadding(Double bleepStopPadding); + + _FinalStage entityTypes(Optional> entityTypes); + + _FinalStage entityTypes(List entityTypes); + + _FinalStage tokenType(Optional tokenType); + + _FinalStage tokenType(TokenTypeWithoutVault tokenType); + + _FinalStage allowRegex(Optional> allowRegex); + + _FinalStage allowRegex(List allowRegex); + + _FinalStage restrictRegex(Optional> restrictRegex); + + _FinalStage restrictRegex(List restrictRegex); + + _FinalStage transformations(Optional transformations); + + _FinalStage transformations(Transformations transformations); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, FileStage, _FinalStage { + private String vaultId; + + private DeidentifyAudioRequestFile file; + + private Optional transformations = Optional.empty(); + + private Optional> restrictRegex = Optional.empty(); + + private Optional> allowRegex = Optional.empty(); + + private Optional tokenType = Optional.empty(); + + private Optional> entityTypes = Optional.empty(); + + private Optional bleepStopPadding = Optional.empty(); + + private Optional bleepStartPadding = Optional.empty(); + + private Optional bleepFrequency = Optional.empty(); + + private Optional bleepGain = Optional.empty(); + + private Optional outputTranscription = Optional.empty(); + + private Optional outputProcessedAudio = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyAudioRequest other) { + vaultId(other.getVaultId()); + file(other.getFile()); + outputProcessedAudio(other.getOutputProcessedAudio()); + outputTranscription(other.getOutputTranscription()); + bleepGain(other.getBleepGain()); + bleepFrequency(other.getBleepFrequency()); + bleepStartPadding(other.getBleepStartPadding()); + bleepStopPadding(other.getBleepStopPadding()); + entityTypes(other.getEntityTypes()); + tokenType(other.getTokenType()); + allowRegex(other.getAllowRegex()); + restrictRegex(other.getRestrictRegex()); + transformations(other.getTransformations()); + return this; + } + + @java.lang.Override + @JsonSetter("vault_id") + public FileStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + * File to de-identify. Files are specified as Base64-encoded data.

File to de-identify. Files are specified as Base64-encoded data.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("file") + public _FinalStage file(@NotNull DeidentifyAudioRequestFile file) { + this.file = Objects.requireNonNull(file, "file must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage transformations(Transformations transformations) { + this.transformations = Optional.ofNullable(transformations); + return this; + } + + @java.lang.Override + @JsonSetter(value = "transformations", nulls = Nulls.SKIP) + public _FinalStage transformations(Optional transformations) { + this.transformations = transformations; + return this; + } + + @java.lang.Override + public _FinalStage restrictRegex(List restrictRegex) { + this.restrictRegex = Optional.ofNullable(restrictRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) + public _FinalStage restrictRegex(Optional> restrictRegex) { + this.restrictRegex = restrictRegex; + return this; + } + + @java.lang.Override + public _FinalStage allowRegex(List allowRegex) { + this.allowRegex = Optional.ofNullable(allowRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) + public _FinalStage allowRegex(Optional> allowRegex) { + this.allowRegex = allowRegex; + return this; + } + + @java.lang.Override + public _FinalStage tokenType(TokenTypeWithoutVault tokenType) { + this.tokenType = Optional.ofNullable(tokenType); + return this; + } + + @java.lang.Override + @JsonSetter(value = "token_type", nulls = Nulls.SKIP) + public _FinalStage tokenType(Optional tokenType) { + this.tokenType = tokenType; + return this; + } + + @java.lang.Override + public _FinalStage entityTypes(List entityTypes) { + this.entityTypes = Optional.ofNullable(entityTypes); + return this; + } + + @java.lang.Override + @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) + public _FinalStage entityTypes(Optional> entityTypes) { + this.entityTypes = entityTypes; + return this; + } + + /** + *

Padding added to the end of a bleep, in seconds.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage bleepStopPadding(Double bleepStopPadding) { + this.bleepStopPadding = Optional.ofNullable(bleepStopPadding); + return this; + } + + /** + *

Padding added to the end of a bleep, in seconds.

+ */ + @java.lang.Override + @JsonSetter(value = "bleep_stop_padding", nulls = Nulls.SKIP) + public _FinalStage bleepStopPadding(Optional bleepStopPadding) { + this.bleepStopPadding = bleepStopPadding; + return this; + } + + /** + *

Padding added to the beginning of a bleep, in seconds.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage bleepStartPadding(Double bleepStartPadding) { + this.bleepStartPadding = Optional.ofNullable(bleepStartPadding); + return this; + } + + /** + *

Padding added to the beginning of a bleep, in seconds.

+ */ + @java.lang.Override + @JsonSetter(value = "bleep_start_padding", nulls = Nulls.SKIP) + public _FinalStage bleepStartPadding(Optional bleepStartPadding) { + this.bleepStartPadding = bleepStartPadding; + return this; + } + + /** + *

The pitch of the bleep sound, in Hz. The higher the number, the higher the pitch.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage bleepFrequency(Double bleepFrequency) { + this.bleepFrequency = Optional.ofNullable(bleepFrequency); + return this; + } + + /** + *

The pitch of the bleep sound, in Hz. The higher the number, the higher the pitch.

+ */ + @java.lang.Override + @JsonSetter(value = "bleep_frequency", nulls = Nulls.SKIP) + public _FinalStage bleepFrequency(Optional bleepFrequency) { + this.bleepFrequency = bleepFrequency; + return this; + } + + /** + *

Relative loudness of the bleep in dB. Positive values increase its loudness, and negative values decrease it.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage bleepGain(Double bleepGain) { + this.bleepGain = Optional.ofNullable(bleepGain); + return this; + } + + /** + *

Relative loudness of the bleep in dB. Positive values increase its loudness, and negative values decrease it.

+ */ + @java.lang.Override + @JsonSetter(value = "bleep_gain", nulls = Nulls.SKIP) + public _FinalStage bleepGain(Optional bleepGain) { + this.bleepGain = bleepGain; + return this; + } + + /** + *

Type of transcription to output.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage outputTranscription(DeidentifyAudioRequestOutputTranscription outputTranscription) { + this.outputTranscription = Optional.ofNullable(outputTranscription); + return this; + } + + /** + *

Type of transcription to output.

+ */ + @java.lang.Override + @JsonSetter(value = "output_transcription", nulls = Nulls.SKIP) + public _FinalStage outputTranscription( + Optional outputTranscription) { + this.outputTranscription = outputTranscription; + return this; + } + + /** + *

If true, includes processed audio file in the response.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage outputProcessedAudio(Boolean outputProcessedAudio) { + this.outputProcessedAudio = Optional.ofNullable(outputProcessedAudio); + return this; + } + + /** + *

If true, includes processed audio file in the response.

+ */ + @java.lang.Override + @JsonSetter(value = "output_processed_audio", nulls = Nulls.SKIP) + public _FinalStage outputProcessedAudio(Optional outputProcessedAudio) { + this.outputProcessedAudio = outputProcessedAudio; + return this; + } + + @java.lang.Override + public DeidentifyAudioRequest build() { + return new DeidentifyAudioRequest( + vaultId, + file, + outputProcessedAudio, + outputTranscription, + bleepGain, + bleepFrequency, + bleepStartPadding, + bleepStopPadding, + entityTypes, + tokenType, + allowRegex, + restrictRegex, + transformations, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyDocumentRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyDocumentRequest.java new file mode 100644 index 00000000..bf6f307e --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyDocumentRequest.java @@ -0,0 +1,310 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.files.types.DeidentifyDocumentRequestFile; +import com.skyflow.generated.rest.types.EntityType; +import com.skyflow.generated.rest.types.TokenTypeWithoutVault; +import com.skyflow.generated.rest.types.Transformations; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyDocumentRequest.Builder.class) +public final class DeidentifyDocumentRequest { + private final String vaultId; + + private final DeidentifyDocumentRequestFile file; + + private final Optional> entityTypes; + + private final Optional tokenType; + + private final Optional> allowRegex; + + private final Optional> restrictRegex; + + private final Optional transformations; + + private final Map additionalProperties; + + private DeidentifyDocumentRequest( + String vaultId, + DeidentifyDocumentRequestFile file, + Optional> entityTypes, + Optional tokenType, + Optional> allowRegex, + Optional> restrictRegex, + Optional transformations, + Map additionalProperties) { + this.vaultId = vaultId; + this.file = file; + this.entityTypes = entityTypes; + this.tokenType = tokenType; + this.allowRegex = allowRegex; + this.restrictRegex = restrictRegex; + this.transformations = transformations; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return File to de-identify. Files are specified as Base64-encoded data. + */ + @JsonProperty("file") + public DeidentifyDocumentRequestFile getFile() { + return file; + } + + @JsonProperty("entity_types") + public Optional> getEntityTypes() { + return entityTypes; + } + + @JsonProperty("token_type") + public Optional getTokenType() { + return tokenType; + } + + @JsonProperty("allow_regex") + public Optional> getAllowRegex() { + return allowRegex; + } + + @JsonProperty("restrict_regex") + public Optional> getRestrictRegex() { + return restrictRegex; + } + + @JsonProperty("transformations") + public Optional getTransformations() { + return transformations; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyDocumentRequest && equalTo((DeidentifyDocumentRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyDocumentRequest other) { + return vaultId.equals(other.vaultId) + && file.equals(other.file) + && entityTypes.equals(other.entityTypes) + && tokenType.equals(other.tokenType) + && allowRegex.equals(other.allowRegex) + && restrictRegex.equals(other.restrictRegex) + && transformations.equals(other.transformations); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.vaultId, + this.file, + this.entityTypes, + this.tokenType, + this.allowRegex, + this.restrictRegex, + this.transformations); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + FileStage vaultId(@NotNull String vaultId); + + Builder from(DeidentifyDocumentRequest other); + } + + public interface FileStage { + /** + * File to de-identify. Files are specified as Base64-encoded data. + */ + _FinalStage file(@NotNull DeidentifyDocumentRequestFile file); + } + + public interface _FinalStage { + DeidentifyDocumentRequest build(); + + _FinalStage entityTypes(Optional> entityTypes); + + _FinalStage entityTypes(List entityTypes); + + _FinalStage tokenType(Optional tokenType); + + _FinalStage tokenType(TokenTypeWithoutVault tokenType); + + _FinalStage allowRegex(Optional> allowRegex); + + _FinalStage allowRegex(List allowRegex); + + _FinalStage restrictRegex(Optional> restrictRegex); + + _FinalStage restrictRegex(List restrictRegex); + + _FinalStage transformations(Optional transformations); + + _FinalStage transformations(Transformations transformations); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, FileStage, _FinalStage { + private String vaultId; + + private DeidentifyDocumentRequestFile file; + + private Optional transformations = Optional.empty(); + + private Optional> restrictRegex = Optional.empty(); + + private Optional> allowRegex = Optional.empty(); + + private Optional tokenType = Optional.empty(); + + private Optional> entityTypes = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyDocumentRequest other) { + vaultId(other.getVaultId()); + file(other.getFile()); + entityTypes(other.getEntityTypes()); + tokenType(other.getTokenType()); + allowRegex(other.getAllowRegex()); + restrictRegex(other.getRestrictRegex()); + transformations(other.getTransformations()); + return this; + } + + @java.lang.Override + @JsonSetter("vault_id") + public FileStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + * File to de-identify. Files are specified as Base64-encoded data.

File to de-identify. Files are specified as Base64-encoded data.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("file") + public _FinalStage file(@NotNull DeidentifyDocumentRequestFile file) { + this.file = Objects.requireNonNull(file, "file must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage transformations(Transformations transformations) { + this.transformations = Optional.ofNullable(transformations); + return this; + } + + @java.lang.Override + @JsonSetter(value = "transformations", nulls = Nulls.SKIP) + public _FinalStage transformations(Optional transformations) { + this.transformations = transformations; + return this; + } + + @java.lang.Override + public _FinalStage restrictRegex(List restrictRegex) { + this.restrictRegex = Optional.ofNullable(restrictRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) + public _FinalStage restrictRegex(Optional> restrictRegex) { + this.restrictRegex = restrictRegex; + return this; + } + + @java.lang.Override + public _FinalStage allowRegex(List allowRegex) { + this.allowRegex = Optional.ofNullable(allowRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) + public _FinalStage allowRegex(Optional> allowRegex) { + this.allowRegex = allowRegex; + return this; + } + + @java.lang.Override + public _FinalStage tokenType(TokenTypeWithoutVault tokenType) { + this.tokenType = Optional.ofNullable(tokenType); + return this; + } + + @java.lang.Override + @JsonSetter(value = "token_type", nulls = Nulls.SKIP) + public _FinalStage tokenType(Optional tokenType) { + this.tokenType = tokenType; + return this; + } + + @java.lang.Override + public _FinalStage entityTypes(List entityTypes) { + this.entityTypes = Optional.ofNullable(entityTypes); + return this; + } + + @java.lang.Override + @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) + public _FinalStage entityTypes(Optional> entityTypes) { + this.entityTypes = entityTypes; + return this; + } + + @java.lang.Override + public DeidentifyDocumentRequest build() { + return new DeidentifyDocumentRequest( + vaultId, + file, + entityTypes, + tokenType, + allowRegex, + restrictRegex, + transformations, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequest.java new file mode 100644 index 00000000..1cbcd8f1 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequest.java @@ -0,0 +1,310 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.files.types.DeidentifyFileRequestFile; +import com.skyflow.generated.rest.types.EntityType; +import com.skyflow.generated.rest.types.TokenTypeWithoutVault; +import com.skyflow.generated.rest.types.Transformations; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyFileRequest.Builder.class) +public final class DeidentifyFileRequest { + private final String vaultId; + + private final DeidentifyFileRequestFile file; + + private final Optional> entityTypes; + + private final Optional tokenType; + + private final Optional> allowRegex; + + private final Optional> restrictRegex; + + private final Optional transformations; + + private final Map additionalProperties; + + private DeidentifyFileRequest( + String vaultId, + DeidentifyFileRequestFile file, + Optional> entityTypes, + Optional tokenType, + Optional> allowRegex, + Optional> restrictRegex, + Optional transformations, + Map additionalProperties) { + this.vaultId = vaultId; + this.file = file; + this.entityTypes = entityTypes; + this.tokenType = tokenType; + this.allowRegex = allowRegex; + this.restrictRegex = restrictRegex; + this.transformations = transformations; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return File to de-identify. Files are specified as Base64-encoded data. + */ + @JsonProperty("file") + public DeidentifyFileRequestFile getFile() { + return file; + } + + @JsonProperty("entity_types") + public Optional> getEntityTypes() { + return entityTypes; + } + + @JsonProperty("token_type") + public Optional getTokenType() { + return tokenType; + } + + @JsonProperty("allow_regex") + public Optional> getAllowRegex() { + return allowRegex; + } + + @JsonProperty("restrict_regex") + public Optional> getRestrictRegex() { + return restrictRegex; + } + + @JsonProperty("transformations") + public Optional getTransformations() { + return transformations; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyFileRequest && equalTo((DeidentifyFileRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyFileRequest other) { + return vaultId.equals(other.vaultId) + && file.equals(other.file) + && entityTypes.equals(other.entityTypes) + && tokenType.equals(other.tokenType) + && allowRegex.equals(other.allowRegex) + && restrictRegex.equals(other.restrictRegex) + && transformations.equals(other.transformations); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.vaultId, + this.file, + this.entityTypes, + this.tokenType, + this.allowRegex, + this.restrictRegex, + this.transformations); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + FileStage vaultId(@NotNull String vaultId); + + Builder from(DeidentifyFileRequest other); + } + + public interface FileStage { + /** + * File to de-identify. Files are specified as Base64-encoded data. + */ + _FinalStage file(@NotNull DeidentifyFileRequestFile file); + } + + public interface _FinalStage { + DeidentifyFileRequest build(); + + _FinalStage entityTypes(Optional> entityTypes); + + _FinalStage entityTypes(List entityTypes); + + _FinalStage tokenType(Optional tokenType); + + _FinalStage tokenType(TokenTypeWithoutVault tokenType); + + _FinalStage allowRegex(Optional> allowRegex); + + _FinalStage allowRegex(List allowRegex); + + _FinalStage restrictRegex(Optional> restrictRegex); + + _FinalStage restrictRegex(List restrictRegex); + + _FinalStage transformations(Optional transformations); + + _FinalStage transformations(Transformations transformations); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, FileStage, _FinalStage { + private String vaultId; + + private DeidentifyFileRequestFile file; + + private Optional transformations = Optional.empty(); + + private Optional> restrictRegex = Optional.empty(); + + private Optional> allowRegex = Optional.empty(); + + private Optional tokenType = Optional.empty(); + + private Optional> entityTypes = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyFileRequest other) { + vaultId(other.getVaultId()); + file(other.getFile()); + entityTypes(other.getEntityTypes()); + tokenType(other.getTokenType()); + allowRegex(other.getAllowRegex()); + restrictRegex(other.getRestrictRegex()); + transformations(other.getTransformations()); + return this; + } + + @java.lang.Override + @JsonSetter("vault_id") + public FileStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + * File to de-identify. Files are specified as Base64-encoded data.

File to de-identify. Files are specified as Base64-encoded data.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("file") + public _FinalStage file(@NotNull DeidentifyFileRequestFile file) { + this.file = Objects.requireNonNull(file, "file must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage transformations(Transformations transformations) { + this.transformations = Optional.ofNullable(transformations); + return this; + } + + @java.lang.Override + @JsonSetter(value = "transformations", nulls = Nulls.SKIP) + public _FinalStage transformations(Optional transformations) { + this.transformations = transformations; + return this; + } + + @java.lang.Override + public _FinalStage restrictRegex(List restrictRegex) { + this.restrictRegex = Optional.ofNullable(restrictRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) + public _FinalStage restrictRegex(Optional> restrictRegex) { + this.restrictRegex = restrictRegex; + return this; + } + + @java.lang.Override + public _FinalStage allowRegex(List allowRegex) { + this.allowRegex = Optional.ofNullable(allowRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) + public _FinalStage allowRegex(Optional> allowRegex) { + this.allowRegex = allowRegex; + return this; + } + + @java.lang.Override + public _FinalStage tokenType(TokenTypeWithoutVault tokenType) { + this.tokenType = Optional.ofNullable(tokenType); + return this; + } + + @java.lang.Override + @JsonSetter(value = "token_type", nulls = Nulls.SKIP) + public _FinalStage tokenType(Optional tokenType) { + this.tokenType = tokenType; + return this; + } + + @java.lang.Override + public _FinalStage entityTypes(List entityTypes) { + this.entityTypes = Optional.ofNullable(entityTypes); + return this; + } + + @java.lang.Override + @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) + public _FinalStage entityTypes(Optional> entityTypes) { + this.entityTypes = entityTypes; + return this; + } + + @java.lang.Override + public DeidentifyFileRequest build() { + return new DeidentifyFileRequest( + vaultId, + file, + entityTypes, + tokenType, + allowRegex, + restrictRegex, + transformations, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyImageRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyImageRequest.java new file mode 100644 index 00000000..41de24b2 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyImageRequest.java @@ -0,0 +1,446 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.files.types.DeidentifyImageRequestFile; +import com.skyflow.generated.rest.resources.files.types.DeidentifyImageRequestMaskingMethod; +import com.skyflow.generated.rest.types.EntityType; +import com.skyflow.generated.rest.types.TokenTypeWithoutVault; +import com.skyflow.generated.rest.types.Transformations; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyImageRequest.Builder.class) +public final class DeidentifyImageRequest { + private final String vaultId; + + private final DeidentifyImageRequestFile file; + + private final Optional outputProcessedImage; + + private final Optional outputOcrText; + + private final Optional maskingMethod; + + private final Optional> entityTypes; + + private final Optional tokenType; + + private final Optional> allowRegex; + + private final Optional> restrictRegex; + + private final Optional transformations; + + private final Map additionalProperties; + + private DeidentifyImageRequest( + String vaultId, + DeidentifyImageRequestFile file, + Optional outputProcessedImage, + Optional outputOcrText, + Optional maskingMethod, + Optional> entityTypes, + Optional tokenType, + Optional> allowRegex, + Optional> restrictRegex, + Optional transformations, + Map additionalProperties) { + this.vaultId = vaultId; + this.file = file; + this.outputProcessedImage = outputProcessedImage; + this.outputOcrText = outputOcrText; + this.maskingMethod = maskingMethod; + this.entityTypes = entityTypes; + this.tokenType = tokenType; + this.allowRegex = allowRegex; + this.restrictRegex = restrictRegex; + this.transformations = transformations; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return File to de-identify. Files are specified as Base64-encoded data. + */ + @JsonProperty("file") + public DeidentifyImageRequestFile getFile() { + return file; + } + + /** + * @return If true, includes processed image in the output. + */ + @JsonProperty("output_processed_image") + public Optional getOutputProcessedImage() { + return outputProcessedImage; + } + + /** + * @return If true, includes OCR text output in the response. + */ + @JsonProperty("output_ocr_text") + public Optional getOutputOcrText() { + return outputOcrText; + } + + /** + * @return Method to mask the entities in the image. + */ + @JsonProperty("masking_method") + public Optional getMaskingMethod() { + return maskingMethod; + } + + @JsonProperty("entity_types") + public Optional> getEntityTypes() { + return entityTypes; + } + + @JsonProperty("token_type") + public Optional getTokenType() { + return tokenType; + } + + @JsonProperty("allow_regex") + public Optional> getAllowRegex() { + return allowRegex; + } + + @JsonProperty("restrict_regex") + public Optional> getRestrictRegex() { + return restrictRegex; + } + + @JsonProperty("transformations") + public Optional getTransformations() { + return transformations; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyImageRequest && equalTo((DeidentifyImageRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyImageRequest other) { + return vaultId.equals(other.vaultId) + && file.equals(other.file) + && outputProcessedImage.equals(other.outputProcessedImage) + && outputOcrText.equals(other.outputOcrText) + && maskingMethod.equals(other.maskingMethod) + && entityTypes.equals(other.entityTypes) + && tokenType.equals(other.tokenType) + && allowRegex.equals(other.allowRegex) + && restrictRegex.equals(other.restrictRegex) + && transformations.equals(other.transformations); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.vaultId, + this.file, + this.outputProcessedImage, + this.outputOcrText, + this.maskingMethod, + this.entityTypes, + this.tokenType, + this.allowRegex, + this.restrictRegex, + this.transformations); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + FileStage vaultId(@NotNull String vaultId); + + Builder from(DeidentifyImageRequest other); + } + + public interface FileStage { + /** + * File to de-identify. Files are specified as Base64-encoded data. + */ + _FinalStage file(@NotNull DeidentifyImageRequestFile file); + } + + public interface _FinalStage { + DeidentifyImageRequest build(); + + /** + *

If true, includes processed image in the output.

+ */ + _FinalStage outputProcessedImage(Optional outputProcessedImage); + + _FinalStage outputProcessedImage(Boolean outputProcessedImage); + + /** + *

If true, includes OCR text output in the response.

+ */ + _FinalStage outputOcrText(Optional outputOcrText); + + _FinalStage outputOcrText(Boolean outputOcrText); + + /** + *

Method to mask the entities in the image.

+ */ + _FinalStage maskingMethod(Optional maskingMethod); + + _FinalStage maskingMethod(DeidentifyImageRequestMaskingMethod maskingMethod); + + _FinalStage entityTypes(Optional> entityTypes); + + _FinalStage entityTypes(List entityTypes); + + _FinalStage tokenType(Optional tokenType); + + _FinalStage tokenType(TokenTypeWithoutVault tokenType); + + _FinalStage allowRegex(Optional> allowRegex); + + _FinalStage allowRegex(List allowRegex); + + _FinalStage restrictRegex(Optional> restrictRegex); + + _FinalStage restrictRegex(List restrictRegex); + + _FinalStage transformations(Optional transformations); + + _FinalStage transformations(Transformations transformations); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, FileStage, _FinalStage { + private String vaultId; + + private DeidentifyImageRequestFile file; + + private Optional transformations = Optional.empty(); + + private Optional> restrictRegex = Optional.empty(); + + private Optional> allowRegex = Optional.empty(); + + private Optional tokenType = Optional.empty(); + + private Optional> entityTypes = Optional.empty(); + + private Optional maskingMethod = Optional.empty(); + + private Optional outputOcrText = Optional.empty(); + + private Optional outputProcessedImage = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyImageRequest other) { + vaultId(other.getVaultId()); + file(other.getFile()); + outputProcessedImage(other.getOutputProcessedImage()); + outputOcrText(other.getOutputOcrText()); + maskingMethod(other.getMaskingMethod()); + entityTypes(other.getEntityTypes()); + tokenType(other.getTokenType()); + allowRegex(other.getAllowRegex()); + restrictRegex(other.getRestrictRegex()); + transformations(other.getTransformations()); + return this; + } + + @java.lang.Override + @JsonSetter("vault_id") + public FileStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + * File to de-identify. Files are specified as Base64-encoded data.

File to de-identify. Files are specified as Base64-encoded data.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("file") + public _FinalStage file(@NotNull DeidentifyImageRequestFile file) { + this.file = Objects.requireNonNull(file, "file must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage transformations(Transformations transformations) { + this.transformations = Optional.ofNullable(transformations); + return this; + } + + @java.lang.Override + @JsonSetter(value = "transformations", nulls = Nulls.SKIP) + public _FinalStage transformations(Optional transformations) { + this.transformations = transformations; + return this; + } + + @java.lang.Override + public _FinalStage restrictRegex(List restrictRegex) { + this.restrictRegex = Optional.ofNullable(restrictRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) + public _FinalStage restrictRegex(Optional> restrictRegex) { + this.restrictRegex = restrictRegex; + return this; + } + + @java.lang.Override + public _FinalStage allowRegex(List allowRegex) { + this.allowRegex = Optional.ofNullable(allowRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) + public _FinalStage allowRegex(Optional> allowRegex) { + this.allowRegex = allowRegex; + return this; + } + + @java.lang.Override + public _FinalStage tokenType(TokenTypeWithoutVault tokenType) { + this.tokenType = Optional.ofNullable(tokenType); + return this; + } + + @java.lang.Override + @JsonSetter(value = "token_type", nulls = Nulls.SKIP) + public _FinalStage tokenType(Optional tokenType) { + this.tokenType = tokenType; + return this; + } + + @java.lang.Override + public _FinalStage entityTypes(List entityTypes) { + this.entityTypes = Optional.ofNullable(entityTypes); + return this; + } + + @java.lang.Override + @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) + public _FinalStage entityTypes(Optional> entityTypes) { + this.entityTypes = entityTypes; + return this; + } + + /** + *

Method to mask the entities in the image.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage maskingMethod(DeidentifyImageRequestMaskingMethod maskingMethod) { + this.maskingMethod = Optional.ofNullable(maskingMethod); + return this; + } + + /** + *

Method to mask the entities in the image.

+ */ + @java.lang.Override + @JsonSetter(value = "masking_method", nulls = Nulls.SKIP) + public _FinalStage maskingMethod(Optional maskingMethod) { + this.maskingMethod = maskingMethod; + return this; + } + + /** + *

If true, includes OCR text output in the response.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage outputOcrText(Boolean outputOcrText) { + this.outputOcrText = Optional.ofNullable(outputOcrText); + return this; + } + + /** + *

If true, includes OCR text output in the response.

+ */ + @java.lang.Override + @JsonSetter(value = "output_ocr_text", nulls = Nulls.SKIP) + public _FinalStage outputOcrText(Optional outputOcrText) { + this.outputOcrText = outputOcrText; + return this; + } + + /** + *

If true, includes processed image in the output.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage outputProcessedImage(Boolean outputProcessedImage) { + this.outputProcessedImage = Optional.ofNullable(outputProcessedImage); + return this; + } + + /** + *

If true, includes processed image in the output.

+ */ + @java.lang.Override + @JsonSetter(value = "output_processed_image", nulls = Nulls.SKIP) + public _FinalStage outputProcessedImage(Optional outputProcessedImage) { + this.outputProcessedImage = outputProcessedImage; + return this; + } + + @java.lang.Override + public DeidentifyImageRequest build() { + return new DeidentifyImageRequest( + vaultId, + file, + outputProcessedImage, + outputOcrText, + maskingMethod, + entityTypes, + tokenType, + allowRegex, + restrictRegex, + transformations, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPdfRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPdfRequest.java new file mode 100644 index 00000000..83fbb14f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPdfRequest.java @@ -0,0 +1,400 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.files.types.DeidentifyPdfRequestFile; +import com.skyflow.generated.rest.types.EntityType; +import com.skyflow.generated.rest.types.TokenTypeWithoutVault; +import com.skyflow.generated.rest.types.Transformations; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyPdfRequest.Builder.class) +public final class DeidentifyPdfRequest { + private final String vaultId; + + private final DeidentifyPdfRequestFile file; + + private final Optional density; + + private final Optional maxResolution; + + private final Optional> entityTypes; + + private final Optional tokenType; + + private final Optional> allowRegex; + + private final Optional> restrictRegex; + + private final Optional transformations; + + private final Map additionalProperties; + + private DeidentifyPdfRequest( + String vaultId, + DeidentifyPdfRequestFile file, + Optional density, + Optional maxResolution, + Optional> entityTypes, + Optional tokenType, + Optional> allowRegex, + Optional> restrictRegex, + Optional transformations, + Map additionalProperties) { + this.vaultId = vaultId; + this.file = file; + this.density = density; + this.maxResolution = maxResolution; + this.entityTypes = entityTypes; + this.tokenType = tokenType; + this.allowRegex = allowRegex; + this.restrictRegex = restrictRegex; + this.transformations = transformations; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return File to de-identify. Files are specified as Base64-encoded data. + */ + @JsonProperty("file") + public DeidentifyPdfRequestFile getFile() { + return file; + } + + /** + * @return Pixel density at which to process the PDF file. + */ + @JsonProperty("density") + public Optional getDensity() { + return density; + } + + /** + * @return Max resolution at which to process the PDF file. + */ + @JsonProperty("max_resolution") + public Optional getMaxResolution() { + return maxResolution; + } + + @JsonProperty("entity_types") + public Optional> getEntityTypes() { + return entityTypes; + } + + @JsonProperty("token_type") + public Optional getTokenType() { + return tokenType; + } + + @JsonProperty("allow_regex") + public Optional> getAllowRegex() { + return allowRegex; + } + + @JsonProperty("restrict_regex") + public Optional> getRestrictRegex() { + return restrictRegex; + } + + @JsonProperty("transformations") + public Optional getTransformations() { + return transformations; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyPdfRequest && equalTo((DeidentifyPdfRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyPdfRequest other) { + return vaultId.equals(other.vaultId) + && file.equals(other.file) + && density.equals(other.density) + && maxResolution.equals(other.maxResolution) + && entityTypes.equals(other.entityTypes) + && tokenType.equals(other.tokenType) + && allowRegex.equals(other.allowRegex) + && restrictRegex.equals(other.restrictRegex) + && transformations.equals(other.transformations); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.vaultId, + this.file, + this.density, + this.maxResolution, + this.entityTypes, + this.tokenType, + this.allowRegex, + this.restrictRegex, + this.transformations); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + FileStage vaultId(@NotNull String vaultId); + + Builder from(DeidentifyPdfRequest other); + } + + public interface FileStage { + /** + * File to de-identify. Files are specified as Base64-encoded data. + */ + _FinalStage file(@NotNull DeidentifyPdfRequestFile file); + } + + public interface _FinalStage { + DeidentifyPdfRequest build(); + + /** + *

Pixel density at which to process the PDF file.

+ */ + _FinalStage density(Optional density); + + _FinalStage density(Integer density); + + /** + *

Max resolution at which to process the PDF file.

+ */ + _FinalStage maxResolution(Optional maxResolution); + + _FinalStage maxResolution(Integer maxResolution); + + _FinalStage entityTypes(Optional> entityTypes); + + _FinalStage entityTypes(List entityTypes); + + _FinalStage tokenType(Optional tokenType); + + _FinalStage tokenType(TokenTypeWithoutVault tokenType); + + _FinalStage allowRegex(Optional> allowRegex); + + _FinalStage allowRegex(List allowRegex); + + _FinalStage restrictRegex(Optional> restrictRegex); + + _FinalStage restrictRegex(List restrictRegex); + + _FinalStage transformations(Optional transformations); + + _FinalStage transformations(Transformations transformations); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, FileStage, _FinalStage { + private String vaultId; + + private DeidentifyPdfRequestFile file; + + private Optional transformations = Optional.empty(); + + private Optional> restrictRegex = Optional.empty(); + + private Optional> allowRegex = Optional.empty(); + + private Optional tokenType = Optional.empty(); + + private Optional> entityTypes = Optional.empty(); + + private Optional maxResolution = Optional.empty(); + + private Optional density = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyPdfRequest other) { + vaultId(other.getVaultId()); + file(other.getFile()); + density(other.getDensity()); + maxResolution(other.getMaxResolution()); + entityTypes(other.getEntityTypes()); + tokenType(other.getTokenType()); + allowRegex(other.getAllowRegex()); + restrictRegex(other.getRestrictRegex()); + transformations(other.getTransformations()); + return this; + } + + @java.lang.Override + @JsonSetter("vault_id") + public FileStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + * File to de-identify. Files are specified as Base64-encoded data.

File to de-identify. Files are specified as Base64-encoded data.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("file") + public _FinalStage file(@NotNull DeidentifyPdfRequestFile file) { + this.file = Objects.requireNonNull(file, "file must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage transformations(Transformations transformations) { + this.transformations = Optional.ofNullable(transformations); + return this; + } + + @java.lang.Override + @JsonSetter(value = "transformations", nulls = Nulls.SKIP) + public _FinalStage transformations(Optional transformations) { + this.transformations = transformations; + return this; + } + + @java.lang.Override + public _FinalStage restrictRegex(List restrictRegex) { + this.restrictRegex = Optional.ofNullable(restrictRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) + public _FinalStage restrictRegex(Optional> restrictRegex) { + this.restrictRegex = restrictRegex; + return this; + } + + @java.lang.Override + public _FinalStage allowRegex(List allowRegex) { + this.allowRegex = Optional.ofNullable(allowRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) + public _FinalStage allowRegex(Optional> allowRegex) { + this.allowRegex = allowRegex; + return this; + } + + @java.lang.Override + public _FinalStage tokenType(TokenTypeWithoutVault tokenType) { + this.tokenType = Optional.ofNullable(tokenType); + return this; + } + + @java.lang.Override + @JsonSetter(value = "token_type", nulls = Nulls.SKIP) + public _FinalStage tokenType(Optional tokenType) { + this.tokenType = tokenType; + return this; + } + + @java.lang.Override + public _FinalStage entityTypes(List entityTypes) { + this.entityTypes = Optional.ofNullable(entityTypes); + return this; + } + + @java.lang.Override + @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) + public _FinalStage entityTypes(Optional> entityTypes) { + this.entityTypes = entityTypes; + return this; + } + + /** + *

Max resolution at which to process the PDF file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage maxResolution(Integer maxResolution) { + this.maxResolution = Optional.ofNullable(maxResolution); + return this; + } + + /** + *

Max resolution at which to process the PDF file.

+ */ + @java.lang.Override + @JsonSetter(value = "max_resolution", nulls = Nulls.SKIP) + public _FinalStage maxResolution(Optional maxResolution) { + this.maxResolution = maxResolution; + return this; + } + + /** + *

Pixel density at which to process the PDF file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage density(Integer density) { + this.density = Optional.ofNullable(density); + return this; + } + + /** + *

Pixel density at which to process the PDF file.

+ */ + @java.lang.Override + @JsonSetter(value = "density", nulls = Nulls.SKIP) + public _FinalStage density(Optional density) { + this.density = density; + return this; + } + + @java.lang.Override + public DeidentifyPdfRequest build() { + return new DeidentifyPdfRequest( + vaultId, + file, + density, + maxResolution, + entityTypes, + tokenType, + allowRegex, + restrictRegex, + transformations, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPresentationRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPresentationRequest.java new file mode 100644 index 00000000..47a63a5b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPresentationRequest.java @@ -0,0 +1,310 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.files.types.DeidentifyPresentationRequestFile; +import com.skyflow.generated.rest.types.EntityType; +import com.skyflow.generated.rest.types.TokenTypeWithoutVault; +import com.skyflow.generated.rest.types.Transformations; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyPresentationRequest.Builder.class) +public final class DeidentifyPresentationRequest { + private final String vaultId; + + private final DeidentifyPresentationRequestFile file; + + private final Optional> entityTypes; + + private final Optional tokenType; + + private final Optional> allowRegex; + + private final Optional> restrictRegex; + + private final Optional transformations; + + private final Map additionalProperties; + + private DeidentifyPresentationRequest( + String vaultId, + DeidentifyPresentationRequestFile file, + Optional> entityTypes, + Optional tokenType, + Optional> allowRegex, + Optional> restrictRegex, + Optional transformations, + Map additionalProperties) { + this.vaultId = vaultId; + this.file = file; + this.entityTypes = entityTypes; + this.tokenType = tokenType; + this.allowRegex = allowRegex; + this.restrictRegex = restrictRegex; + this.transformations = transformations; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return File to de-identify. Files are specified as Base64-encoded data. + */ + @JsonProperty("file") + public DeidentifyPresentationRequestFile getFile() { + return file; + } + + @JsonProperty("entity_types") + public Optional> getEntityTypes() { + return entityTypes; + } + + @JsonProperty("token_type") + public Optional getTokenType() { + return tokenType; + } + + @JsonProperty("allow_regex") + public Optional> getAllowRegex() { + return allowRegex; + } + + @JsonProperty("restrict_regex") + public Optional> getRestrictRegex() { + return restrictRegex; + } + + @JsonProperty("transformations") + public Optional getTransformations() { + return transformations; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyPresentationRequest && equalTo((DeidentifyPresentationRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyPresentationRequest other) { + return vaultId.equals(other.vaultId) + && file.equals(other.file) + && entityTypes.equals(other.entityTypes) + && tokenType.equals(other.tokenType) + && allowRegex.equals(other.allowRegex) + && restrictRegex.equals(other.restrictRegex) + && transformations.equals(other.transformations); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.vaultId, + this.file, + this.entityTypes, + this.tokenType, + this.allowRegex, + this.restrictRegex, + this.transformations); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + FileStage vaultId(@NotNull String vaultId); + + Builder from(DeidentifyPresentationRequest other); + } + + public interface FileStage { + /** + * File to de-identify. Files are specified as Base64-encoded data. + */ + _FinalStage file(@NotNull DeidentifyPresentationRequestFile file); + } + + public interface _FinalStage { + DeidentifyPresentationRequest build(); + + _FinalStage entityTypes(Optional> entityTypes); + + _FinalStage entityTypes(List entityTypes); + + _FinalStage tokenType(Optional tokenType); + + _FinalStage tokenType(TokenTypeWithoutVault tokenType); + + _FinalStage allowRegex(Optional> allowRegex); + + _FinalStage allowRegex(List allowRegex); + + _FinalStage restrictRegex(Optional> restrictRegex); + + _FinalStage restrictRegex(List restrictRegex); + + _FinalStage transformations(Optional transformations); + + _FinalStage transformations(Transformations transformations); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, FileStage, _FinalStage { + private String vaultId; + + private DeidentifyPresentationRequestFile file; + + private Optional transformations = Optional.empty(); + + private Optional> restrictRegex = Optional.empty(); + + private Optional> allowRegex = Optional.empty(); + + private Optional tokenType = Optional.empty(); + + private Optional> entityTypes = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyPresentationRequest other) { + vaultId(other.getVaultId()); + file(other.getFile()); + entityTypes(other.getEntityTypes()); + tokenType(other.getTokenType()); + allowRegex(other.getAllowRegex()); + restrictRegex(other.getRestrictRegex()); + transformations(other.getTransformations()); + return this; + } + + @java.lang.Override + @JsonSetter("vault_id") + public FileStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + * File to de-identify. Files are specified as Base64-encoded data.

File to de-identify. Files are specified as Base64-encoded data.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("file") + public _FinalStage file(@NotNull DeidentifyPresentationRequestFile file) { + this.file = Objects.requireNonNull(file, "file must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage transformations(Transformations transformations) { + this.transformations = Optional.ofNullable(transformations); + return this; + } + + @java.lang.Override + @JsonSetter(value = "transformations", nulls = Nulls.SKIP) + public _FinalStage transformations(Optional transformations) { + this.transformations = transformations; + return this; + } + + @java.lang.Override + public _FinalStage restrictRegex(List restrictRegex) { + this.restrictRegex = Optional.ofNullable(restrictRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) + public _FinalStage restrictRegex(Optional> restrictRegex) { + this.restrictRegex = restrictRegex; + return this; + } + + @java.lang.Override + public _FinalStage allowRegex(List allowRegex) { + this.allowRegex = Optional.ofNullable(allowRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) + public _FinalStage allowRegex(Optional> allowRegex) { + this.allowRegex = allowRegex; + return this; + } + + @java.lang.Override + public _FinalStage tokenType(TokenTypeWithoutVault tokenType) { + this.tokenType = Optional.ofNullable(tokenType); + return this; + } + + @java.lang.Override + @JsonSetter(value = "token_type", nulls = Nulls.SKIP) + public _FinalStage tokenType(Optional tokenType) { + this.tokenType = tokenType; + return this; + } + + @java.lang.Override + public _FinalStage entityTypes(List entityTypes) { + this.entityTypes = Optional.ofNullable(entityTypes); + return this; + } + + @java.lang.Override + @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) + public _FinalStage entityTypes(Optional> entityTypes) { + this.entityTypes = entityTypes; + return this; + } + + @java.lang.Override + public DeidentifyPresentationRequest build() { + return new DeidentifyPresentationRequest( + vaultId, + file, + entityTypes, + tokenType, + allowRegex, + restrictRegex, + transformations, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifySpreadsheetRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifySpreadsheetRequest.java new file mode 100644 index 00000000..b72b412b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifySpreadsheetRequest.java @@ -0,0 +1,310 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.files.types.DeidentifySpreadsheetRequestFile; +import com.skyflow.generated.rest.types.EntityType; +import com.skyflow.generated.rest.types.TokenTypeWithoutVault; +import com.skyflow.generated.rest.types.Transformations; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifySpreadsheetRequest.Builder.class) +public final class DeidentifySpreadsheetRequest { + private final String vaultId; + + private final DeidentifySpreadsheetRequestFile file; + + private final Optional> entityTypes; + + private final Optional tokenType; + + private final Optional> allowRegex; + + private final Optional> restrictRegex; + + private final Optional transformations; + + private final Map additionalProperties; + + private DeidentifySpreadsheetRequest( + String vaultId, + DeidentifySpreadsheetRequestFile file, + Optional> entityTypes, + Optional tokenType, + Optional> allowRegex, + Optional> restrictRegex, + Optional transformations, + Map additionalProperties) { + this.vaultId = vaultId; + this.file = file; + this.entityTypes = entityTypes; + this.tokenType = tokenType; + this.allowRegex = allowRegex; + this.restrictRegex = restrictRegex; + this.transformations = transformations; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return File to de-identify. Files are specified as Base64-encoded data. + */ + @JsonProperty("file") + public DeidentifySpreadsheetRequestFile getFile() { + return file; + } + + @JsonProperty("entity_types") + public Optional> getEntityTypes() { + return entityTypes; + } + + @JsonProperty("token_type") + public Optional getTokenType() { + return tokenType; + } + + @JsonProperty("allow_regex") + public Optional> getAllowRegex() { + return allowRegex; + } + + @JsonProperty("restrict_regex") + public Optional> getRestrictRegex() { + return restrictRegex; + } + + @JsonProperty("transformations") + public Optional getTransformations() { + return transformations; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifySpreadsheetRequest && equalTo((DeidentifySpreadsheetRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifySpreadsheetRequest other) { + return vaultId.equals(other.vaultId) + && file.equals(other.file) + && entityTypes.equals(other.entityTypes) + && tokenType.equals(other.tokenType) + && allowRegex.equals(other.allowRegex) + && restrictRegex.equals(other.restrictRegex) + && transformations.equals(other.transformations); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.vaultId, + this.file, + this.entityTypes, + this.tokenType, + this.allowRegex, + this.restrictRegex, + this.transformations); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + FileStage vaultId(@NotNull String vaultId); + + Builder from(DeidentifySpreadsheetRequest other); + } + + public interface FileStage { + /** + * File to de-identify. Files are specified as Base64-encoded data. + */ + _FinalStage file(@NotNull DeidentifySpreadsheetRequestFile file); + } + + public interface _FinalStage { + DeidentifySpreadsheetRequest build(); + + _FinalStage entityTypes(Optional> entityTypes); + + _FinalStage entityTypes(List entityTypes); + + _FinalStage tokenType(Optional tokenType); + + _FinalStage tokenType(TokenTypeWithoutVault tokenType); + + _FinalStage allowRegex(Optional> allowRegex); + + _FinalStage allowRegex(List allowRegex); + + _FinalStage restrictRegex(Optional> restrictRegex); + + _FinalStage restrictRegex(List restrictRegex); + + _FinalStage transformations(Optional transformations); + + _FinalStage transformations(Transformations transformations); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, FileStage, _FinalStage { + private String vaultId; + + private DeidentifySpreadsheetRequestFile file; + + private Optional transformations = Optional.empty(); + + private Optional> restrictRegex = Optional.empty(); + + private Optional> allowRegex = Optional.empty(); + + private Optional tokenType = Optional.empty(); + + private Optional> entityTypes = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifySpreadsheetRequest other) { + vaultId(other.getVaultId()); + file(other.getFile()); + entityTypes(other.getEntityTypes()); + tokenType(other.getTokenType()); + allowRegex(other.getAllowRegex()); + restrictRegex(other.getRestrictRegex()); + transformations(other.getTransformations()); + return this; + } + + @java.lang.Override + @JsonSetter("vault_id") + public FileStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + * File to de-identify. Files are specified as Base64-encoded data.

File to de-identify. Files are specified as Base64-encoded data.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("file") + public _FinalStage file(@NotNull DeidentifySpreadsheetRequestFile file) { + this.file = Objects.requireNonNull(file, "file must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage transformations(Transformations transformations) { + this.transformations = Optional.ofNullable(transformations); + return this; + } + + @java.lang.Override + @JsonSetter(value = "transformations", nulls = Nulls.SKIP) + public _FinalStage transformations(Optional transformations) { + this.transformations = transformations; + return this; + } + + @java.lang.Override + public _FinalStage restrictRegex(List restrictRegex) { + this.restrictRegex = Optional.ofNullable(restrictRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) + public _FinalStage restrictRegex(Optional> restrictRegex) { + this.restrictRegex = restrictRegex; + return this; + } + + @java.lang.Override + public _FinalStage allowRegex(List allowRegex) { + this.allowRegex = Optional.ofNullable(allowRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) + public _FinalStage allowRegex(Optional> allowRegex) { + this.allowRegex = allowRegex; + return this; + } + + @java.lang.Override + public _FinalStage tokenType(TokenTypeWithoutVault tokenType) { + this.tokenType = Optional.ofNullable(tokenType); + return this; + } + + @java.lang.Override + @JsonSetter(value = "token_type", nulls = Nulls.SKIP) + public _FinalStage tokenType(Optional tokenType) { + this.tokenType = tokenType; + return this; + } + + @java.lang.Override + public _FinalStage entityTypes(List entityTypes) { + this.entityTypes = Optional.ofNullable(entityTypes); + return this; + } + + @java.lang.Override + @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) + public _FinalStage entityTypes(Optional> entityTypes) { + this.entityTypes = entityTypes; + return this; + } + + @java.lang.Override + public DeidentifySpreadsheetRequest build() { + return new DeidentifySpreadsheetRequest( + vaultId, + file, + entityTypes, + tokenType, + allowRegex, + restrictRegex, + transformations, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyStructuredTextRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyStructuredTextRequest.java new file mode 100644 index 00000000..a61a5ba0 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyStructuredTextRequest.java @@ -0,0 +1,310 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.files.types.DeidentifyStructuredTextRequestFile; +import com.skyflow.generated.rest.types.EntityType; +import com.skyflow.generated.rest.types.TokenTypeWithoutVault; +import com.skyflow.generated.rest.types.Transformations; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyStructuredTextRequest.Builder.class) +public final class DeidentifyStructuredTextRequest { + private final String vaultId; + + private final DeidentifyStructuredTextRequestFile file; + + private final Optional> entityTypes; + + private final Optional tokenType; + + private final Optional> allowRegex; + + private final Optional> restrictRegex; + + private final Optional transformations; + + private final Map additionalProperties; + + private DeidentifyStructuredTextRequest( + String vaultId, + DeidentifyStructuredTextRequestFile file, + Optional> entityTypes, + Optional tokenType, + Optional> allowRegex, + Optional> restrictRegex, + Optional transformations, + Map additionalProperties) { + this.vaultId = vaultId; + this.file = file; + this.entityTypes = entityTypes; + this.tokenType = tokenType; + this.allowRegex = allowRegex; + this.restrictRegex = restrictRegex; + this.transformations = transformations; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return File to de-identify. Files are specified as Base64-encoded data. + */ + @JsonProperty("file") + public DeidentifyStructuredTextRequestFile getFile() { + return file; + } + + @JsonProperty("entity_types") + public Optional> getEntityTypes() { + return entityTypes; + } + + @JsonProperty("token_type") + public Optional getTokenType() { + return tokenType; + } + + @JsonProperty("allow_regex") + public Optional> getAllowRegex() { + return allowRegex; + } + + @JsonProperty("restrict_regex") + public Optional> getRestrictRegex() { + return restrictRegex; + } + + @JsonProperty("transformations") + public Optional getTransformations() { + return transformations; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyStructuredTextRequest && equalTo((DeidentifyStructuredTextRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyStructuredTextRequest other) { + return vaultId.equals(other.vaultId) + && file.equals(other.file) + && entityTypes.equals(other.entityTypes) + && tokenType.equals(other.tokenType) + && allowRegex.equals(other.allowRegex) + && restrictRegex.equals(other.restrictRegex) + && transformations.equals(other.transformations); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.vaultId, + this.file, + this.entityTypes, + this.tokenType, + this.allowRegex, + this.restrictRegex, + this.transformations); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + FileStage vaultId(@NotNull String vaultId); + + Builder from(DeidentifyStructuredTextRequest other); + } + + public interface FileStage { + /** + * File to de-identify. Files are specified as Base64-encoded data. + */ + _FinalStage file(@NotNull DeidentifyStructuredTextRequestFile file); + } + + public interface _FinalStage { + DeidentifyStructuredTextRequest build(); + + _FinalStage entityTypes(Optional> entityTypes); + + _FinalStage entityTypes(List entityTypes); + + _FinalStage tokenType(Optional tokenType); + + _FinalStage tokenType(TokenTypeWithoutVault tokenType); + + _FinalStage allowRegex(Optional> allowRegex); + + _FinalStage allowRegex(List allowRegex); + + _FinalStage restrictRegex(Optional> restrictRegex); + + _FinalStage restrictRegex(List restrictRegex); + + _FinalStage transformations(Optional transformations); + + _FinalStage transformations(Transformations transformations); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, FileStage, _FinalStage { + private String vaultId; + + private DeidentifyStructuredTextRequestFile file; + + private Optional transformations = Optional.empty(); + + private Optional> restrictRegex = Optional.empty(); + + private Optional> allowRegex = Optional.empty(); + + private Optional tokenType = Optional.empty(); + + private Optional> entityTypes = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyStructuredTextRequest other) { + vaultId(other.getVaultId()); + file(other.getFile()); + entityTypes(other.getEntityTypes()); + tokenType(other.getTokenType()); + allowRegex(other.getAllowRegex()); + restrictRegex(other.getRestrictRegex()); + transformations(other.getTransformations()); + return this; + } + + @java.lang.Override + @JsonSetter("vault_id") + public FileStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + * File to de-identify. Files are specified as Base64-encoded data.

File to de-identify. Files are specified as Base64-encoded data.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("file") + public _FinalStage file(@NotNull DeidentifyStructuredTextRequestFile file) { + this.file = Objects.requireNonNull(file, "file must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage transformations(Transformations transformations) { + this.transformations = Optional.ofNullable(transformations); + return this; + } + + @java.lang.Override + @JsonSetter(value = "transformations", nulls = Nulls.SKIP) + public _FinalStage transformations(Optional transformations) { + this.transformations = transformations; + return this; + } + + @java.lang.Override + public _FinalStage restrictRegex(List restrictRegex) { + this.restrictRegex = Optional.ofNullable(restrictRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) + public _FinalStage restrictRegex(Optional> restrictRegex) { + this.restrictRegex = restrictRegex; + return this; + } + + @java.lang.Override + public _FinalStage allowRegex(List allowRegex) { + this.allowRegex = Optional.ofNullable(allowRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) + public _FinalStage allowRegex(Optional> allowRegex) { + this.allowRegex = allowRegex; + return this; + } + + @java.lang.Override + public _FinalStage tokenType(TokenTypeWithoutVault tokenType) { + this.tokenType = Optional.ofNullable(tokenType); + return this; + } + + @java.lang.Override + @JsonSetter(value = "token_type", nulls = Nulls.SKIP) + public _FinalStage tokenType(Optional tokenType) { + this.tokenType = tokenType; + return this; + } + + @java.lang.Override + public _FinalStage entityTypes(List entityTypes) { + this.entityTypes = Optional.ofNullable(entityTypes); + return this; + } + + @java.lang.Override + @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) + public _FinalStage entityTypes(Optional> entityTypes) { + this.entityTypes = entityTypes; + return this; + } + + @java.lang.Override + public DeidentifyStructuredTextRequest build() { + return new DeidentifyStructuredTextRequest( + vaultId, + file, + entityTypes, + tokenType, + allowRegex, + restrictRegex, + transformations, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyTextRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyTextRequest.java new file mode 100644 index 00000000..4eb0ac6c --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyTextRequest.java @@ -0,0 +1,310 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.files.types.DeidentifyTextRequestFile; +import com.skyflow.generated.rest.types.EntityType; +import com.skyflow.generated.rest.types.TokenTypeWithoutVault; +import com.skyflow.generated.rest.types.Transformations; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyTextRequest.Builder.class) +public final class DeidentifyTextRequest { + private final String vaultId; + + private final DeidentifyTextRequestFile file; + + private final Optional> entityTypes; + + private final Optional tokenType; + + private final Optional> allowRegex; + + private final Optional> restrictRegex; + + private final Optional transformations; + + private final Map additionalProperties; + + private DeidentifyTextRequest( + String vaultId, + DeidentifyTextRequestFile file, + Optional> entityTypes, + Optional tokenType, + Optional> allowRegex, + Optional> restrictRegex, + Optional transformations, + Map additionalProperties) { + this.vaultId = vaultId; + this.file = file; + this.entityTypes = entityTypes; + this.tokenType = tokenType; + this.allowRegex = allowRegex; + this.restrictRegex = restrictRegex; + this.transformations = transformations; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return File to de-identify. Files are specified as Base64-encoded data. + */ + @JsonProperty("file") + public DeidentifyTextRequestFile getFile() { + return file; + } + + @JsonProperty("entity_types") + public Optional> getEntityTypes() { + return entityTypes; + } + + @JsonProperty("token_type") + public Optional getTokenType() { + return tokenType; + } + + @JsonProperty("allow_regex") + public Optional> getAllowRegex() { + return allowRegex; + } + + @JsonProperty("restrict_regex") + public Optional> getRestrictRegex() { + return restrictRegex; + } + + @JsonProperty("transformations") + public Optional getTransformations() { + return transformations; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyTextRequest && equalTo((DeidentifyTextRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyTextRequest other) { + return vaultId.equals(other.vaultId) + && file.equals(other.file) + && entityTypes.equals(other.entityTypes) + && tokenType.equals(other.tokenType) + && allowRegex.equals(other.allowRegex) + && restrictRegex.equals(other.restrictRegex) + && transformations.equals(other.transformations); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.vaultId, + this.file, + this.entityTypes, + this.tokenType, + this.allowRegex, + this.restrictRegex, + this.transformations); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + FileStage vaultId(@NotNull String vaultId); + + Builder from(DeidentifyTextRequest other); + } + + public interface FileStage { + /** + * File to de-identify. Files are specified as Base64-encoded data. + */ + _FinalStage file(@NotNull DeidentifyTextRequestFile file); + } + + public interface _FinalStage { + DeidentifyTextRequest build(); + + _FinalStage entityTypes(Optional> entityTypes); + + _FinalStage entityTypes(List entityTypes); + + _FinalStage tokenType(Optional tokenType); + + _FinalStage tokenType(TokenTypeWithoutVault tokenType); + + _FinalStage allowRegex(Optional> allowRegex); + + _FinalStage allowRegex(List allowRegex); + + _FinalStage restrictRegex(Optional> restrictRegex); + + _FinalStage restrictRegex(List restrictRegex); + + _FinalStage transformations(Optional transformations); + + _FinalStage transformations(Transformations transformations); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, FileStage, _FinalStage { + private String vaultId; + + private DeidentifyTextRequestFile file; + + private Optional transformations = Optional.empty(); + + private Optional> restrictRegex = Optional.empty(); + + private Optional> allowRegex = Optional.empty(); + + private Optional tokenType = Optional.empty(); + + private Optional> entityTypes = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyTextRequest other) { + vaultId(other.getVaultId()); + file(other.getFile()); + entityTypes(other.getEntityTypes()); + tokenType(other.getTokenType()); + allowRegex(other.getAllowRegex()); + restrictRegex(other.getRestrictRegex()); + transformations(other.getTransformations()); + return this; + } + + @java.lang.Override + @JsonSetter("vault_id") + public FileStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + * File to de-identify. Files are specified as Base64-encoded data.

File to de-identify. Files are specified as Base64-encoded data.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("file") + public _FinalStage file(@NotNull DeidentifyTextRequestFile file) { + this.file = Objects.requireNonNull(file, "file must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage transformations(Transformations transformations) { + this.transformations = Optional.ofNullable(transformations); + return this; + } + + @java.lang.Override + @JsonSetter(value = "transformations", nulls = Nulls.SKIP) + public _FinalStage transformations(Optional transformations) { + this.transformations = transformations; + return this; + } + + @java.lang.Override + public _FinalStage restrictRegex(List restrictRegex) { + this.restrictRegex = Optional.ofNullable(restrictRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) + public _FinalStage restrictRegex(Optional> restrictRegex) { + this.restrictRegex = restrictRegex; + return this; + } + + @java.lang.Override + public _FinalStage allowRegex(List allowRegex) { + this.allowRegex = Optional.ofNullable(allowRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) + public _FinalStage allowRegex(Optional> allowRegex) { + this.allowRegex = allowRegex; + return this; + } + + @java.lang.Override + public _FinalStage tokenType(TokenTypeWithoutVault tokenType) { + this.tokenType = Optional.ofNullable(tokenType); + return this; + } + + @java.lang.Override + @JsonSetter(value = "token_type", nulls = Nulls.SKIP) + public _FinalStage tokenType(Optional tokenType) { + this.tokenType = tokenType; + return this; + } + + @java.lang.Override + public _FinalStage entityTypes(List entityTypes) { + this.entityTypes = Optional.ofNullable(entityTypes); + return this; + } + + @java.lang.Override + @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) + public _FinalStage entityTypes(Optional> entityTypes) { + this.entityTypes = entityTypes; + return this; + } + + @java.lang.Override + public DeidentifyTextRequest build() { + return new DeidentifyTextRequest( + vaultId, + file, + entityTypes, + tokenType, + allowRegex, + restrictRegex, + transformations, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/GetRunRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/GetRunRequest.java new file mode 100644 index 00000000..390d2090 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/GetRunRequest.java @@ -0,0 +1,112 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = GetRunRequest.Builder.class) +public final class GetRunRequest { + private final String vaultId; + + private final Map additionalProperties; + + private GetRunRequest(String vaultId, Map additionalProperties) { + this.vaultId = vaultId; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GetRunRequest && equalTo((GetRunRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GetRunRequest other) { + return vaultId.equals(other.vaultId); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + /** + * ID of the vault. + */ + _FinalStage vaultId(@NotNull String vaultId); + + Builder from(GetRunRequest other); + } + + public interface _FinalStage { + GetRunRequest build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, _FinalStage { + private String vaultId; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(GetRunRequest other) { + vaultId(other.getVaultId()); + return this; + } + + /** + * ID of the vault.

ID of the vault.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("vault_id") + public _FinalStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + @java.lang.Override + public GetRunRequest build() { + return new GetRunRequest(vaultId, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyAudioRequestFile.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyAudioRequestFile.java new file mode 100644 index 00000000..ad124de0 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyAudioRequestFile.java @@ -0,0 +1,145 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyAudioRequestFile.Builder.class) +public final class DeidentifyAudioRequestFile { + private final String base64; + + private final DeidentifyAudioRequestFileDataFormat dataFormat; + + private final Map additionalProperties; + + private DeidentifyAudioRequestFile( + String base64, DeidentifyAudioRequestFileDataFormat dataFormat, Map additionalProperties) { + this.base64 = base64; + this.dataFormat = dataFormat; + this.additionalProperties = additionalProperties; + } + + /** + * @return Base64-encoded data of the file to de-identify. + */ + @JsonProperty("base64") + public String getBase64() { + return base64; + } + + /** + * @return Data format of the file. + */ + @JsonProperty("data_format") + public DeidentifyAudioRequestFileDataFormat getDataFormat() { + return dataFormat; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyAudioRequestFile && equalTo((DeidentifyAudioRequestFile) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyAudioRequestFile other) { + return base64.equals(other.base64) && dataFormat.equals(other.dataFormat); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.base64, this.dataFormat); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Base64Stage builder() { + return new Builder(); + } + + public interface Base64Stage { + /** + * Base64-encoded data of the file to de-identify. + */ + DataFormatStage base64(@NotNull String base64); + + Builder from(DeidentifyAudioRequestFile other); + } + + public interface DataFormatStage { + /** + * Data format of the file. + */ + _FinalStage dataFormat(@NotNull DeidentifyAudioRequestFileDataFormat dataFormat); + } + + public interface _FinalStage { + DeidentifyAudioRequestFile build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements Base64Stage, DataFormatStage, _FinalStage { + private String base64; + + private DeidentifyAudioRequestFileDataFormat dataFormat; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyAudioRequestFile other) { + base64(other.getBase64()); + dataFormat(other.getDataFormat()); + return this; + } + + /** + * Base64-encoded data of the file to de-identify.

Base64-encoded data of the file to de-identify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("base64") + public DataFormatStage base64(@NotNull String base64) { + this.base64 = Objects.requireNonNull(base64, "base64 must not be null"); + return this; + } + + /** + * Data format of the file.

Data format of the file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("data_format") + public _FinalStage dataFormat(@NotNull DeidentifyAudioRequestFileDataFormat dataFormat) { + this.dataFormat = Objects.requireNonNull(dataFormat, "dataFormat must not be null"); + return this; + } + + @java.lang.Override + public DeidentifyAudioRequestFile build() { + return new DeidentifyAudioRequestFile(base64, dataFormat, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyAudioRequestFileDataFormat.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyAudioRequestFileDataFormat.java new file mode 100644 index 00000000..05203b05 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyAudioRequestFileDataFormat.java @@ -0,0 +1,24 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DeidentifyAudioRequestFileDataFormat { + MP_3("mp3"), + + WAV("wav"); + + private final String value; + + DeidentifyAudioRequestFileDataFormat(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyAudioRequestOutputTranscription.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyAudioRequestOutputTranscription.java new file mode 100644 index 00000000..bd2d8aac --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyAudioRequestOutputTranscription.java @@ -0,0 +1,30 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DeidentifyAudioRequestOutputTranscription { + DIARIZED_TRANSCRIPTION("diarized_transcription"), + + MEDICAL_DIARIZED_TRANSCRIPTION("medical_diarized_transcription"), + + MEDICAL_TRANSCRIPTION("medical_transcription"), + + PLAINTEXT_TRANSCRIPTION("plaintext_transcription"), + + TRANSCRIPTION("transcription"); + + private final String value; + + DeidentifyAudioRequestOutputTranscription(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyDocumentRequestFile.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyDocumentRequestFile.java new file mode 100644 index 00000000..76c7972c --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyDocumentRequestFile.java @@ -0,0 +1,147 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyDocumentRequestFile.Builder.class) +public final class DeidentifyDocumentRequestFile { + private final String base64; + + private final DeidentifyDocumentRequestFileDataFormat dataFormat; + + private final Map additionalProperties; + + private DeidentifyDocumentRequestFile( + String base64, + DeidentifyDocumentRequestFileDataFormat dataFormat, + Map additionalProperties) { + this.base64 = base64; + this.dataFormat = dataFormat; + this.additionalProperties = additionalProperties; + } + + /** + * @return Base64-encoded data of the file to de-identify. + */ + @JsonProperty("base64") + public String getBase64() { + return base64; + } + + /** + * @return Data format of the file. + */ + @JsonProperty("data_format") + public DeidentifyDocumentRequestFileDataFormat getDataFormat() { + return dataFormat; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyDocumentRequestFile && equalTo((DeidentifyDocumentRequestFile) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyDocumentRequestFile other) { + return base64.equals(other.base64) && dataFormat.equals(other.dataFormat); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.base64, this.dataFormat); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Base64Stage builder() { + return new Builder(); + } + + public interface Base64Stage { + /** + * Base64-encoded data of the file to de-identify. + */ + DataFormatStage base64(@NotNull String base64); + + Builder from(DeidentifyDocumentRequestFile other); + } + + public interface DataFormatStage { + /** + * Data format of the file. + */ + _FinalStage dataFormat(@NotNull DeidentifyDocumentRequestFileDataFormat dataFormat); + } + + public interface _FinalStage { + DeidentifyDocumentRequestFile build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements Base64Stage, DataFormatStage, _FinalStage { + private String base64; + + private DeidentifyDocumentRequestFileDataFormat dataFormat; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyDocumentRequestFile other) { + base64(other.getBase64()); + dataFormat(other.getDataFormat()); + return this; + } + + /** + * Base64-encoded data of the file to de-identify.

Base64-encoded data of the file to de-identify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("base64") + public DataFormatStage base64(@NotNull String base64) { + this.base64 = Objects.requireNonNull(base64, "base64 must not be null"); + return this; + } + + /** + * Data format of the file.

Data format of the file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("data_format") + public _FinalStage dataFormat(@NotNull DeidentifyDocumentRequestFileDataFormat dataFormat) { + this.dataFormat = Objects.requireNonNull(dataFormat, "dataFormat must not be null"); + return this; + } + + @java.lang.Override + public DeidentifyDocumentRequestFile build() { + return new DeidentifyDocumentRequestFile(base64, dataFormat, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyDocumentRequestFileDataFormat.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyDocumentRequestFileDataFormat.java new file mode 100644 index 00000000..6b741b95 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyDocumentRequestFileDataFormat.java @@ -0,0 +1,26 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DeidentifyDocumentRequestFileDataFormat { + DOC("doc"), + + DOCX("docx"), + + PDF("pdf"); + + private final String value; + + DeidentifyDocumentRequestFileDataFormat(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestFile.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestFile.java new file mode 100644 index 00000000..f21ddeef --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestFile.java @@ -0,0 +1,145 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyFileRequestFile.Builder.class) +public final class DeidentifyFileRequestFile { + private final String base64; + + private final DeidentifyFileRequestFileDataFormat dataFormat; + + private final Map additionalProperties; + + private DeidentifyFileRequestFile( + String base64, DeidentifyFileRequestFileDataFormat dataFormat, Map additionalProperties) { + this.base64 = base64; + this.dataFormat = dataFormat; + this.additionalProperties = additionalProperties; + } + + /** + * @return Base64-encoded data of the file to de-identify. + */ + @JsonProperty("base64") + public String getBase64() { + return base64; + } + + /** + * @return Data format of the file. + */ + @JsonProperty("data_format") + public DeidentifyFileRequestFileDataFormat getDataFormat() { + return dataFormat; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyFileRequestFile && equalTo((DeidentifyFileRequestFile) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyFileRequestFile other) { + return base64.equals(other.base64) && dataFormat.equals(other.dataFormat); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.base64, this.dataFormat); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Base64Stage builder() { + return new Builder(); + } + + public interface Base64Stage { + /** + * Base64-encoded data of the file to de-identify. + */ + DataFormatStage base64(@NotNull String base64); + + Builder from(DeidentifyFileRequestFile other); + } + + public interface DataFormatStage { + /** + * Data format of the file. + */ + _FinalStage dataFormat(@NotNull DeidentifyFileRequestFileDataFormat dataFormat); + } + + public interface _FinalStage { + DeidentifyFileRequestFile build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements Base64Stage, DataFormatStage, _FinalStage { + private String base64; + + private DeidentifyFileRequestFileDataFormat dataFormat; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyFileRequestFile other) { + base64(other.getBase64()); + dataFormat(other.getDataFormat()); + return this; + } + + /** + * Base64-encoded data of the file to de-identify.

Base64-encoded data of the file to de-identify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("base64") + public DataFormatStage base64(@NotNull String base64) { + this.base64 = Objects.requireNonNull(base64, "base64 must not be null"); + return this; + } + + /** + * Data format of the file.

Data format of the file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("data_format") + public _FinalStage dataFormat(@NotNull DeidentifyFileRequestFileDataFormat dataFormat) { + this.dataFormat = Objects.requireNonNull(dataFormat, "dataFormat must not be null"); + return this; + } + + @java.lang.Override + public DeidentifyFileRequestFile build() { + return new DeidentifyFileRequestFile(base64, dataFormat, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestFileDataFormat.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestFileDataFormat.java new file mode 100644 index 00000000..afc90bc3 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestFileDataFormat.java @@ -0,0 +1,58 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DeidentifyFileRequestFileDataFormat { + BMP("bmp"), + + CSV("csv"), + + DOC("doc"), + + DOCX("docx"), + + JPEG("jpeg"), + + JPG("jpg"), + + JSON("json"), + + MP_3("mp3"), + + PDF("pdf"), + + PNG("png"), + + PPT("ppt"), + + PPTX("pptx"), + + TIF("tif"), + + TIFF("tiff"), + + TXT("txt"), + + WAV("wav"), + + XLS("xls"), + + XLSX("xlsx"), + + XML("xml"); + + private final String value; + + DeidentifyFileRequestFileDataFormat(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyImageRequestFile.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyImageRequestFile.java new file mode 100644 index 00000000..116fd94d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyImageRequestFile.java @@ -0,0 +1,145 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyImageRequestFile.Builder.class) +public final class DeidentifyImageRequestFile { + private final String base64; + + private final DeidentifyImageRequestFileDataFormat dataFormat; + + private final Map additionalProperties; + + private DeidentifyImageRequestFile( + String base64, DeidentifyImageRequestFileDataFormat dataFormat, Map additionalProperties) { + this.base64 = base64; + this.dataFormat = dataFormat; + this.additionalProperties = additionalProperties; + } + + /** + * @return Base64-encoded data of the file to de-identify. + */ + @JsonProperty("base64") + public String getBase64() { + return base64; + } + + /** + * @return Data format of the file. + */ + @JsonProperty("data_format") + public DeidentifyImageRequestFileDataFormat getDataFormat() { + return dataFormat; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyImageRequestFile && equalTo((DeidentifyImageRequestFile) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyImageRequestFile other) { + return base64.equals(other.base64) && dataFormat.equals(other.dataFormat); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.base64, this.dataFormat); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Base64Stage builder() { + return new Builder(); + } + + public interface Base64Stage { + /** + * Base64-encoded data of the file to de-identify. + */ + DataFormatStage base64(@NotNull String base64); + + Builder from(DeidentifyImageRequestFile other); + } + + public interface DataFormatStage { + /** + * Data format of the file. + */ + _FinalStage dataFormat(@NotNull DeidentifyImageRequestFileDataFormat dataFormat); + } + + public interface _FinalStage { + DeidentifyImageRequestFile build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements Base64Stage, DataFormatStage, _FinalStage { + private String base64; + + private DeidentifyImageRequestFileDataFormat dataFormat; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyImageRequestFile other) { + base64(other.getBase64()); + dataFormat(other.getDataFormat()); + return this; + } + + /** + * Base64-encoded data of the file to de-identify.

Base64-encoded data of the file to de-identify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("base64") + public DataFormatStage base64(@NotNull String base64) { + this.base64 = Objects.requireNonNull(base64, "base64 must not be null"); + return this; + } + + /** + * Data format of the file.

Data format of the file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("data_format") + public _FinalStage dataFormat(@NotNull DeidentifyImageRequestFileDataFormat dataFormat) { + this.dataFormat = Objects.requireNonNull(dataFormat, "dataFormat must not be null"); + return this; + } + + @java.lang.Override + public DeidentifyImageRequestFile build() { + return new DeidentifyImageRequestFile(base64, dataFormat, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyImageRequestFileDataFormat.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyImageRequestFileDataFormat.java new file mode 100644 index 00000000..cfb324d9 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyImageRequestFileDataFormat.java @@ -0,0 +1,32 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DeidentifyImageRequestFileDataFormat { + BMP("bmp"), + + JPEG("jpeg"), + + JPG("jpg"), + + PNG("png"), + + TIF("tif"), + + TIFF("tiff"); + + private final String value; + + DeidentifyImageRequestFileDataFormat(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyImageRequestMaskingMethod.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyImageRequestMaskingMethod.java new file mode 100644 index 00000000..8cf5bf3c --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyImageRequestMaskingMethod.java @@ -0,0 +1,24 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DeidentifyImageRequestMaskingMethod { + BLACKBOX("blackbox"), + + BLUR("blur"); + + private final String value; + + DeidentifyImageRequestMaskingMethod(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyPdfRequestFile.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyPdfRequestFile.java new file mode 100644 index 00000000..14028aab --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyPdfRequestFile.java @@ -0,0 +1,120 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyPdfRequestFile.Builder.class) +public final class DeidentifyPdfRequestFile { + private final String base64; + + private final Map additionalProperties; + + private DeidentifyPdfRequestFile(String base64, Map additionalProperties) { + this.base64 = base64; + this.additionalProperties = additionalProperties; + } + + /** + * @return Base64-encoded data of the file to de-identify. + */ + @JsonProperty("base64") + public String getBase64() { + return base64; + } + + /** + * @return Data format of the file. + */ + @JsonProperty("data_format") + public String getDataFormat() { + return "pdf"; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyPdfRequestFile && equalTo((DeidentifyPdfRequestFile) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyPdfRequestFile other) { + return base64.equals(other.base64); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.base64); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Base64Stage builder() { + return new Builder(); + } + + public interface Base64Stage { + /** + * Base64-encoded data of the file to de-identify. + */ + _FinalStage base64(@NotNull String base64); + + Builder from(DeidentifyPdfRequestFile other); + } + + public interface _FinalStage { + DeidentifyPdfRequestFile build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements Base64Stage, _FinalStage { + private String base64; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyPdfRequestFile other) { + base64(other.getBase64()); + return this; + } + + /** + * Base64-encoded data of the file to de-identify.

Base64-encoded data of the file to de-identify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("base64") + public _FinalStage base64(@NotNull String base64) { + this.base64 = Objects.requireNonNull(base64, "base64 must not be null"); + return this; + } + + @java.lang.Override + public DeidentifyPdfRequestFile build() { + return new DeidentifyPdfRequestFile(base64, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyPresentationRequestFile.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyPresentationRequestFile.java new file mode 100644 index 00000000..1b2e247f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyPresentationRequestFile.java @@ -0,0 +1,147 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyPresentationRequestFile.Builder.class) +public final class DeidentifyPresentationRequestFile { + private final String base64; + + private final DeidentifyPresentationRequestFileDataFormat dataFormat; + + private final Map additionalProperties; + + private DeidentifyPresentationRequestFile( + String base64, + DeidentifyPresentationRequestFileDataFormat dataFormat, + Map additionalProperties) { + this.base64 = base64; + this.dataFormat = dataFormat; + this.additionalProperties = additionalProperties; + } + + /** + * @return Base64-encoded data of the file to de-identify. + */ + @JsonProperty("base64") + public String getBase64() { + return base64; + } + + /** + * @return Data format of the file. + */ + @JsonProperty("data_format") + public DeidentifyPresentationRequestFileDataFormat getDataFormat() { + return dataFormat; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyPresentationRequestFile && equalTo((DeidentifyPresentationRequestFile) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyPresentationRequestFile other) { + return base64.equals(other.base64) && dataFormat.equals(other.dataFormat); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.base64, this.dataFormat); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Base64Stage builder() { + return new Builder(); + } + + public interface Base64Stage { + /** + * Base64-encoded data of the file to de-identify. + */ + DataFormatStage base64(@NotNull String base64); + + Builder from(DeidentifyPresentationRequestFile other); + } + + public interface DataFormatStage { + /** + * Data format of the file. + */ + _FinalStage dataFormat(@NotNull DeidentifyPresentationRequestFileDataFormat dataFormat); + } + + public interface _FinalStage { + DeidentifyPresentationRequestFile build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements Base64Stage, DataFormatStage, _FinalStage { + private String base64; + + private DeidentifyPresentationRequestFileDataFormat dataFormat; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyPresentationRequestFile other) { + base64(other.getBase64()); + dataFormat(other.getDataFormat()); + return this; + } + + /** + * Base64-encoded data of the file to de-identify.

Base64-encoded data of the file to de-identify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("base64") + public DataFormatStage base64(@NotNull String base64) { + this.base64 = Objects.requireNonNull(base64, "base64 must not be null"); + return this; + } + + /** + * Data format of the file.

Data format of the file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("data_format") + public _FinalStage dataFormat(@NotNull DeidentifyPresentationRequestFileDataFormat dataFormat) { + this.dataFormat = Objects.requireNonNull(dataFormat, "dataFormat must not be null"); + return this; + } + + @java.lang.Override + public DeidentifyPresentationRequestFile build() { + return new DeidentifyPresentationRequestFile(base64, dataFormat, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyPresentationRequestFileDataFormat.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyPresentationRequestFileDataFormat.java new file mode 100644 index 00000000..e6bcd268 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyPresentationRequestFileDataFormat.java @@ -0,0 +1,24 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DeidentifyPresentationRequestFileDataFormat { + PPT("ppt"), + + PPTX("pptx"); + + private final String value; + + DeidentifyPresentationRequestFileDataFormat(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifySpreadsheetRequestFile.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifySpreadsheetRequestFile.java new file mode 100644 index 00000000..2e291563 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifySpreadsheetRequestFile.java @@ -0,0 +1,147 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifySpreadsheetRequestFile.Builder.class) +public final class DeidentifySpreadsheetRequestFile { + private final String base64; + + private final DeidentifySpreadsheetRequestFileDataFormat dataFormat; + + private final Map additionalProperties; + + private DeidentifySpreadsheetRequestFile( + String base64, + DeidentifySpreadsheetRequestFileDataFormat dataFormat, + Map additionalProperties) { + this.base64 = base64; + this.dataFormat = dataFormat; + this.additionalProperties = additionalProperties; + } + + /** + * @return Base64-encoded data of the file to de-identify. + */ + @JsonProperty("base64") + public String getBase64() { + return base64; + } + + /** + * @return Data format of the file. + */ + @JsonProperty("data_format") + public DeidentifySpreadsheetRequestFileDataFormat getDataFormat() { + return dataFormat; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifySpreadsheetRequestFile && equalTo((DeidentifySpreadsheetRequestFile) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifySpreadsheetRequestFile other) { + return base64.equals(other.base64) && dataFormat.equals(other.dataFormat); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.base64, this.dataFormat); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Base64Stage builder() { + return new Builder(); + } + + public interface Base64Stage { + /** + * Base64-encoded data of the file to de-identify. + */ + DataFormatStage base64(@NotNull String base64); + + Builder from(DeidentifySpreadsheetRequestFile other); + } + + public interface DataFormatStage { + /** + * Data format of the file. + */ + _FinalStage dataFormat(@NotNull DeidentifySpreadsheetRequestFileDataFormat dataFormat); + } + + public interface _FinalStage { + DeidentifySpreadsheetRequestFile build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements Base64Stage, DataFormatStage, _FinalStage { + private String base64; + + private DeidentifySpreadsheetRequestFileDataFormat dataFormat; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifySpreadsheetRequestFile other) { + base64(other.getBase64()); + dataFormat(other.getDataFormat()); + return this; + } + + /** + * Base64-encoded data of the file to de-identify.

Base64-encoded data of the file to de-identify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("base64") + public DataFormatStage base64(@NotNull String base64) { + this.base64 = Objects.requireNonNull(base64, "base64 must not be null"); + return this; + } + + /** + * Data format of the file.

Data format of the file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("data_format") + public _FinalStage dataFormat(@NotNull DeidentifySpreadsheetRequestFileDataFormat dataFormat) { + this.dataFormat = Objects.requireNonNull(dataFormat, "dataFormat must not be null"); + return this; + } + + @java.lang.Override + public DeidentifySpreadsheetRequestFile build() { + return new DeidentifySpreadsheetRequestFile(base64, dataFormat, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifySpreadsheetRequestFileDataFormat.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifySpreadsheetRequestFileDataFormat.java new file mode 100644 index 00000000..795a2666 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifySpreadsheetRequestFileDataFormat.java @@ -0,0 +1,26 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DeidentifySpreadsheetRequestFileDataFormat { + CSV("csv"), + + XLS("xls"), + + XLSX("xlsx"); + + private final String value; + + DeidentifySpreadsheetRequestFileDataFormat(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyStructuredTextRequestFile.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyStructuredTextRequestFile.java new file mode 100644 index 00000000..d8d5193a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyStructuredTextRequestFile.java @@ -0,0 +1,148 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyStructuredTextRequestFile.Builder.class) +public final class DeidentifyStructuredTextRequestFile { + private final String base64; + + private final DeidentifyStructuredTextRequestFileDataFormat dataFormat; + + private final Map additionalProperties; + + private DeidentifyStructuredTextRequestFile( + String base64, + DeidentifyStructuredTextRequestFileDataFormat dataFormat, + Map additionalProperties) { + this.base64 = base64; + this.dataFormat = dataFormat; + this.additionalProperties = additionalProperties; + } + + /** + * @return Base64-encoded data of the file to de-identify. + */ + @JsonProperty("base64") + public String getBase64() { + return base64; + } + + /** + * @return Data format of the file. + */ + @JsonProperty("data_format") + public DeidentifyStructuredTextRequestFileDataFormat getDataFormat() { + return dataFormat; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyStructuredTextRequestFile + && equalTo((DeidentifyStructuredTextRequestFile) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyStructuredTextRequestFile other) { + return base64.equals(other.base64) && dataFormat.equals(other.dataFormat); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.base64, this.dataFormat); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Base64Stage builder() { + return new Builder(); + } + + public interface Base64Stage { + /** + * Base64-encoded data of the file to de-identify. + */ + DataFormatStage base64(@NotNull String base64); + + Builder from(DeidentifyStructuredTextRequestFile other); + } + + public interface DataFormatStage { + /** + * Data format of the file. + */ + _FinalStage dataFormat(@NotNull DeidentifyStructuredTextRequestFileDataFormat dataFormat); + } + + public interface _FinalStage { + DeidentifyStructuredTextRequestFile build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements Base64Stage, DataFormatStage, _FinalStage { + private String base64; + + private DeidentifyStructuredTextRequestFileDataFormat dataFormat; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyStructuredTextRequestFile other) { + base64(other.getBase64()); + dataFormat(other.getDataFormat()); + return this; + } + + /** + * Base64-encoded data of the file to de-identify.

Base64-encoded data of the file to de-identify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("base64") + public DataFormatStage base64(@NotNull String base64) { + this.base64 = Objects.requireNonNull(base64, "base64 must not be null"); + return this; + } + + /** + * Data format of the file.

Data format of the file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("data_format") + public _FinalStage dataFormat(@NotNull DeidentifyStructuredTextRequestFileDataFormat dataFormat) { + this.dataFormat = Objects.requireNonNull(dataFormat, "dataFormat must not be null"); + return this; + } + + @java.lang.Override + public DeidentifyStructuredTextRequestFile build() { + return new DeidentifyStructuredTextRequestFile(base64, dataFormat, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyStructuredTextRequestFileDataFormat.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyStructuredTextRequestFileDataFormat.java new file mode 100644 index 00000000..11b30288 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyStructuredTextRequestFileDataFormat.java @@ -0,0 +1,24 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DeidentifyStructuredTextRequestFileDataFormat { + JSON("json"), + + XML("xml"); + + private final String value; + + DeidentifyStructuredTextRequestFileDataFormat(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyTextRequestFile.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyTextRequestFile.java new file mode 100644 index 00000000..c7cbc5b3 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyTextRequestFile.java @@ -0,0 +1,120 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyTextRequestFile.Builder.class) +public final class DeidentifyTextRequestFile { + private final String base64; + + private final Map additionalProperties; + + private DeidentifyTextRequestFile(String base64, Map additionalProperties) { + this.base64 = base64; + this.additionalProperties = additionalProperties; + } + + /** + * @return Base64-encoded data of the file to de-identify. + */ + @JsonProperty("base64") + public String getBase64() { + return base64; + } + + /** + * @return Data format of the file. + */ + @JsonProperty("data_format") + public String getDataFormat() { + return "txt"; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyTextRequestFile && equalTo((DeidentifyTextRequestFile) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyTextRequestFile other) { + return base64.equals(other.base64); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.base64); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Base64Stage builder() { + return new Builder(); + } + + public interface Base64Stage { + /** + * Base64-encoded data of the file to de-identify. + */ + _FinalStage base64(@NotNull String base64); + + Builder from(DeidentifyTextRequestFile other); + } + + public interface _FinalStage { + DeidentifyTextRequestFile build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements Base64Stage, _FinalStage { + private String base64; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyTextRequestFile other) { + base64(other.getBase64()); + return this; + } + + /** + * Base64-encoded data of the file to de-identify.

Base64-encoded data of the file to de-identify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("base64") + public _FinalStage base64(@NotNull String base64) { + this.base64 = Objects.requireNonNull(base64, "base64 must not be null"); + return this; + } + + @java.lang.Override + public DeidentifyTextRequestFile build() { + return new DeidentifyTextRequestFile(base64, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/query/AsyncQueryClient.java b/src/main/java/com/skyflow/generated/rest/resources/query/AsyncQueryClient.java new file mode 100644 index 00000000..894c97b5 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/query/AsyncQueryClient.java @@ -0,0 +1,53 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.query; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.query.requests.QueryServiceExecuteQueryBody; +import com.skyflow.generated.rest.types.V1GetQueryResponse; +import java.util.concurrent.CompletableFuture; + +public class AsyncQueryClient { + protected final ClientOptions clientOptions; + + private final AsyncRawQueryClient rawClient; + + public AsyncQueryClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawQueryClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawQueryClient withRawResponse() { + return this.rawClient; + } + + /** + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + */ + public CompletableFuture queryServiceExecuteQuery(String vaultId) { + return this.rawClient.queryServiceExecuteQuery(vaultId).thenApply(response -> response.body()); + } + + /** + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + */ + public CompletableFuture queryServiceExecuteQuery( + String vaultId, QueryServiceExecuteQueryBody request) { + return this.rawClient.queryServiceExecuteQuery(vaultId, request).thenApply(response -> response.body()); + } + + /** + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + */ + public CompletableFuture queryServiceExecuteQuery( + String vaultId, QueryServiceExecuteQueryBody request, RequestOptions requestOptions) { + return this.rawClient + .queryServiceExecuteQuery(vaultId, request, requestOptions) + .thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/query/AsyncRawQueryClient.java b/src/main/java/com/skyflow/generated/rest/resources/query/AsyncRawQueryClient.java new file mode 100644 index 00000000..96e2dc0b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/query/AsyncRawQueryClient.java @@ -0,0 +1,121 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.query; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.query.requests.QueryServiceExecuteQueryBody; +import com.skyflow.generated.rest.types.V1GetQueryResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawQueryClient { + protected final ClientOptions clientOptions; + + public AsyncRawQueryClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + */ + public CompletableFuture> queryServiceExecuteQuery(String vaultId) { + return queryServiceExecuteQuery( + vaultId, QueryServiceExecuteQueryBody.builder().build()); + } + + /** + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + */ + public CompletableFuture> queryServiceExecuteQuery( + String vaultId, QueryServiceExecuteQueryBody request) { + return queryServiceExecuteQuery(vaultId, request, null); + } + + /** + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + */ + public CompletableFuture> queryServiceExecuteQuery( + String vaultId, QueryServiceExecuteQueryBody request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegments("query") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1GetQueryResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/query/QueryClient.java b/src/main/java/com/skyflow/generated/rest/resources/query/QueryClient.java new file mode 100644 index 00000000..39bb709d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/query/QueryClient.java @@ -0,0 +1,51 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.query; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.query.requests.QueryServiceExecuteQueryBody; +import com.skyflow.generated.rest.types.V1GetQueryResponse; + +public class QueryClient { + protected final ClientOptions clientOptions; + + private final RawQueryClient rawClient; + + public QueryClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawQueryClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawQueryClient withRawResponse() { + return this.rawClient; + } + + /** + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + */ + public V1GetQueryResponse queryServiceExecuteQuery(String vaultId) { + return this.rawClient.queryServiceExecuteQuery(vaultId).body(); + } + + /** + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + */ + public V1GetQueryResponse queryServiceExecuteQuery(String vaultId, QueryServiceExecuteQueryBody request) { + return this.rawClient.queryServiceExecuteQuery(vaultId, request).body(); + } + + /** + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + */ + public V1GetQueryResponse queryServiceExecuteQuery( + String vaultId, QueryServiceExecuteQueryBody request, RequestOptions requestOptions) { + return this.rawClient + .queryServiceExecuteQuery(vaultId, request, requestOptions) + .body(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/query/RawQueryClient.java b/src/main/java/com/skyflow/generated/rest/resources/query/RawQueryClient.java new file mode 100644 index 00000000..3e5bee51 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/query/RawQueryClient.java @@ -0,0 +1,102 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.query; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.query.requests.QueryServiceExecuteQueryBody; +import com.skyflow.generated.rest.types.V1GetQueryResponse; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawQueryClient { + protected final ClientOptions clientOptions; + + public RawQueryClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + */ + public ApiClientHttpResponse queryServiceExecuteQuery(String vaultId) { + return queryServiceExecuteQuery( + vaultId, QueryServiceExecuteQueryBody.builder().build()); + } + + /** + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + */ + public ApiClientHttpResponse queryServiceExecuteQuery( + String vaultId, QueryServiceExecuteQueryBody request) { + return queryServiceExecuteQuery(vaultId, request, null); + } + + /** + * Returns records for a valid SQL query. This endpoint <ul><li>Can return redacted record values.</li><li>Supports only the <code>SELECT</code> command.</li><li>Returns a maximum of 25 records. To return additional records, perform another query using the <code>OFFSET</code> keyword.</li><li>Can't modify the vault or perform transactions.</li><li>Can't return tokens.</li><li>Can't return file download or render URLs.</li><li>Doesn't support the <code>WHERE</code> keyword with columns using transient tokenization.</li><li>Doesn't support ? conditional for columns with column-level encryption disabled.</li><ul> + */ + public ApiClientHttpResponse queryServiceExecuteQuery( + String vaultId, QueryServiceExecuteQueryBody request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegments("query") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1GetQueryResponse.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/query/requests/QueryServiceExecuteQueryBody.java b/src/main/java/com/skyflow/generated/rest/resources/query/requests/QueryServiceExecuteQueryBody.java new file mode 100644 index 00000000..dfa21d15 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/query/requests/QueryServiceExecuteQueryBody.java @@ -0,0 +1,101 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.query.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = QueryServiceExecuteQueryBody.Builder.class) +public final class QueryServiceExecuteQueryBody { + private final Optional query; + + private final Map additionalProperties; + + private QueryServiceExecuteQueryBody(Optional query, Map additionalProperties) { + this.query = query; + this.additionalProperties = additionalProperties; + } + + /** + * @return The SQL query to execute.<br><br><b>Supported commands:</b> <ul> <li><code>SELECT</code></li> </ul> <b>Supported operators:</b> <ul> <li><code>></code></li> <li><code><</code></li> <li><code>=</code></li> <li><code>AND</code></li> <li><code>OR</code></li> <li><code>NOT</code></li> <li><code>LIKE</code></li> <li><code>ILIKE</code></li> <li><code>NULL</code></li> <li><code>NOT NULL</code></li> </ul> <b>Supported keywords:</b> <ul> <li><code>FROM</code></li> <li><code>JOIN</code></li> <li><code>INNER JOIN</code></li> <li><code>LEFT OUTER JOIN</code></li> <li><code>LEFT JOIN</code></li> <li><code>RIGHT OUTER JOIN</code></li> <li><code>RIGHT JOIN</code></li> <li><code>FULL OUTER JOIN</code></li> <li><code>FULL JOIN</code></li> <li><code>OFFSET</code></li> <li><code>LIMIT</code></li> <li><code>WHERE</code></li> </ul> <b>Supported functions:</b> <ul> <li><code>AVG()</code></li> <li><code>SUM()</code></li> <li><code>COUNT()</code></li> <li><code>MIN()</code></li> <li><code>MAX()</code></li> <li><code>REDACTION()</code></li> </ul> + */ + @JsonProperty("query") + public Optional getQuery() { + return query; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof QueryServiceExecuteQueryBody && equalTo((QueryServiceExecuteQueryBody) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(QueryServiceExecuteQueryBody other) { + return query.equals(other.query); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.query); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional query = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(QueryServiceExecuteQueryBody other) { + query(other.getQuery()); + return this; + } + + /** + *

The SQL query to execute.<br><br><b>Supported commands:</b> <ul> <li><code>SELECT</code></li> </ul> <b>Supported operators:</b> <ul> <li><code>></code></li> <li><code><</code></li> <li><code>=</code></li> <li><code>AND</code></li> <li><code>OR</code></li> <li><code>NOT</code></li> <li><code>LIKE</code></li> <li><code>ILIKE</code></li> <li><code>NULL</code></li> <li><code>NOT NULL</code></li> </ul> <b>Supported keywords:</b> <ul> <li><code>FROM</code></li> <li><code>JOIN</code></li> <li><code>INNER JOIN</code></li> <li><code>LEFT OUTER JOIN</code></li> <li><code>LEFT JOIN</code></li> <li><code>RIGHT OUTER JOIN</code></li> <li><code>RIGHT JOIN</code></li> <li><code>FULL OUTER JOIN</code></li> <li><code>FULL JOIN</code></li> <li><code>OFFSET</code></li> <li><code>LIMIT</code></li> <li><code>WHERE</code></li> </ul> <b>Supported functions:</b> <ul> <li><code>AVG()</code></li> <li><code>SUM()</code></li> <li><code>COUNT()</code></li> <li><code>MIN()</code></li> <li><code>MAX()</code></li> <li><code>REDACTION()</code></li> </ul>

+ */ + @JsonSetter(value = "query", nulls = Nulls.SKIP) + public Builder query(Optional query) { + this.query = query; + return this; + } + + public Builder query(String query) { + this.query = Optional.ofNullable(query); + return this; + } + + public QueryServiceExecuteQueryBody build() { + return new QueryServiceExecuteQueryBody(query, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRawRecordsClient.java b/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRawRecordsClient.java new file mode 100644 index 00000000..757ee8e4 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRawRecordsClient.java @@ -0,0 +1,956 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.records.requests.FileServiceUploadFileRequest; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkDeleteRecordBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkGetRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceGetRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.types.V1BatchOperationResponse; +import com.skyflow.generated.rest.types.V1BulkDeleteRecordResponse; +import com.skyflow.generated.rest.types.V1BulkGetRecordResponse; +import com.skyflow.generated.rest.types.V1DeleteFileResponse; +import com.skyflow.generated.rest.types.V1DeleteRecordResponse; +import com.skyflow.generated.rest.types.V1FieldRecords; +import com.skyflow.generated.rest.types.V1GetFileScanStatusResponse; +import com.skyflow.generated.rest.types.V1InsertRecordResponse; +import com.skyflow.generated.rest.types.V1UpdateRecordResponse; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawRecordsClient { + protected final ClientOptions clientOptions; + + public AsyncRawRecordsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Performs multiple record operations in a single transaction. + */ + public CompletableFuture> recordServiceBatchOperation( + String vaultId) { + return recordServiceBatchOperation( + vaultId, RecordServiceBatchOperationBody.builder().build()); + } + + /** + * Performs multiple record operations in a single transaction. + */ + public CompletableFuture> recordServiceBatchOperation( + String vaultId, RecordServiceBatchOperationBody request) { + return recordServiceBatchOperation(vaultId, request, null); + } + + /** + * Performs multiple record operations in a single transaction. + */ + public CompletableFuture> recordServiceBatchOperation( + String vaultId, RecordServiceBatchOperationBody request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), V1BatchOperationResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Gets the specified records from a table. + */ + public CompletableFuture> recordServiceBulkGetRecord( + String vaultId, String objectName) { + return recordServiceBulkGetRecord( + vaultId, objectName, RecordServiceBulkGetRecordRequest.builder().build()); + } + + /** + * Gets the specified records from a table. + */ + public CompletableFuture> recordServiceBulkGetRecord( + String vaultId, String objectName, RecordServiceBulkGetRecordRequest request) { + return recordServiceBulkGetRecord(vaultId, objectName, request, null); + } + + /** + * Gets the specified records from a table. + */ + public CompletableFuture> recordServiceBulkGetRecord( + String vaultId, + String objectName, + RecordServiceBulkGetRecordRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName); + if (request.getRedaction().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "redaction", request.getRedaction().get(), false); + } + if (request.getTokenization().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "tokenization", request.getTokenization().get(), false); + } + if (request.getOffset().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "offset", request.getOffset().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getDownloadUrl().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "downloadURL", request.getDownloadUrl().get(), false); + } + if (request.getColumnName().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "column_name", request.getColumnName().get(), false); + } + if (request.getOrderBy().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "order_by", request.getOrderBy().get(), false); + } + if (request.getSkyflowIds().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "skyflow_ids", request.getSkyflowIds().get(), true); + } + if (request.getFields().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "fields", request.getFields().get(), true); + } + if (request.getColumnValues().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "column_values", request.getColumnValues().get(), true); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), V1BulkGetRecordResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + */ + public CompletableFuture> recordServiceInsertRecord( + String vaultId, String objectName) { + return recordServiceInsertRecord( + vaultId, objectName, RecordServiceInsertRecordBody.builder().build()); + } + + /** + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + */ + public CompletableFuture> recordServiceInsertRecord( + String vaultId, String objectName, RecordServiceInsertRecordBody request) { + return recordServiceInsertRecord(vaultId, objectName, request, null); + } + + /** + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + */ + public CompletableFuture> recordServiceInsertRecord( + String vaultId, String objectName, RecordServiceInsertRecordBody request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), V1InsertRecordResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Deletes the specified records from a table. + */ + public CompletableFuture> recordServiceBulkDeleteRecord( + String vaultId, String objectName) { + return recordServiceBulkDeleteRecord( + vaultId, objectName, RecordServiceBulkDeleteRecordBody.builder().build()); + } + + /** + * Deletes the specified records from a table. + */ + public CompletableFuture> recordServiceBulkDeleteRecord( + String vaultId, String objectName, RecordServiceBulkDeleteRecordBody request) { + return recordServiceBulkDeleteRecord(vaultId, objectName, request, null); + } + + /** + * Deletes the specified records from a table. + */ + public CompletableFuture> recordServiceBulkDeleteRecord( + String vaultId, + String objectName, + RecordServiceBulkDeleteRecordBody request, + RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), V1BulkDeleteRecordResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Returns the specified record from a table. + */ + public CompletableFuture> recordServiceGetRecord( + String vaultId, String objectName, String id) { + return recordServiceGetRecord( + vaultId, objectName, id, RecordServiceGetRecordRequest.builder().build()); + } + + /** + * Returns the specified record from a table. + */ + public CompletableFuture> recordServiceGetRecord( + String vaultId, String objectName, String id, RecordServiceGetRecordRequest request) { + return recordServiceGetRecord(vaultId, objectName, id, request, null); + } + + /** + * Returns the specified record from a table. + */ + public CompletableFuture> recordServiceGetRecord( + String vaultId, + String objectName, + String id, + RecordServiceGetRecordRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName) + .addPathSegment(id); + if (request.getRedaction().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "redaction", request.getRedaction().get(), false); + } + if (request.getTokenization().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "tokenization", request.getTokenization().get(), false); + } + if (request.getDownloadUrl().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "downloadURL", request.getDownloadUrl().get(), false); + } + if (request.getFields().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "fields", request.getFields().get(), true); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1FieldRecords.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public CompletableFuture> recordServiceUpdateRecord( + String vaultId, String objectName, String id) { + return recordServiceUpdateRecord( + vaultId, objectName, id, RecordServiceUpdateRecordBody.builder().build()); + } + + /** + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public CompletableFuture> recordServiceUpdateRecord( + String vaultId, String objectName, String id, RecordServiceUpdateRecordBody request) { + return recordServiceUpdateRecord(vaultId, objectName, id, request, null); + } + + /** + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public CompletableFuture> recordServiceUpdateRecord( + String vaultId, + String objectName, + String id, + RecordServiceUpdateRecordBody request, + RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName) + .addPathSegment(id) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), V1UpdateRecordResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + */ + public CompletableFuture> recordServiceDeleteRecord( + String vaultId, String objectName, String id) { + return recordServiceDeleteRecord(vaultId, objectName, id, null); + } + + /** + * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + */ + public CompletableFuture> recordServiceDeleteRecord( + String vaultId, String objectName, String id, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName) + .addPathSegment(id) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), V1DeleteRecordResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Uploads a file to the specified record. + */ + public CompletableFuture> fileServiceUploadFile( + String vaultId, String objectName, String id, Optional fileColumnName) { + return fileServiceUploadFile( + vaultId, + objectName, + id, + fileColumnName, + FileServiceUploadFileRequest.builder().build()); + } + + /** + * Uploads a file to the specified record. + */ + public CompletableFuture> fileServiceUploadFile( + String vaultId, + String objectName, + String id, + Optional fileColumnName, + FileServiceUploadFileRequest request) { + return fileServiceUploadFile(vaultId, objectName, id, fileColumnName, request, null); + } + + /** + * Uploads a file to the specified record. + */ + public CompletableFuture> fileServiceUploadFile( + String vaultId, + String objectName, + String id, + Optional fileColumnName, + FileServiceUploadFileRequest request, + RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName) + .addPathSegment(id) + .addPathSegments("files") + .build(); + MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM); + try { + if (fileColumnName.isPresent()) { + String fileColumnNameMimeType = + Files.probeContentType(fileColumnName.get().toPath()); + MediaType fileColumnNameMimeTypeMediaType = + fileColumnNameMimeType != null ? MediaType.parse(fileColumnNameMimeType) : null; + body.addFormDataPart( + "fileColumnName", + fileColumnName.get().getName(), + RequestBody.create(fileColumnName.get(), fileColumnNameMimeTypeMediaType)); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", body.build()) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), V1UpdateRecordResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Deletes a file from the specified record. + */ + public CompletableFuture> fileServiceDeleteFile( + String vaultId, String tableName, String id, String columnName) { + return fileServiceDeleteFile(vaultId, tableName, id, columnName, null); + } + + /** + * Deletes a file from the specified record. + */ + public CompletableFuture> fileServiceDeleteFile( + String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(tableName) + .addPathSegment(id) + .addPathSegments("files") + .addPathSegment(columnName) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DeleteFileResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Returns the anti-virus scan status of a file. + */ + public CompletableFuture> fileServiceGetFileScanStatus( + String vaultId, String tableName, String id, String columnName) { + return fileServiceGetFileScanStatus(vaultId, tableName, id, columnName, null); + } + + /** + * Returns the anti-virus scan status of a file. + */ + public CompletableFuture> fileServiceGetFileScanStatus( + String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(tableName) + .addPathSegment(id) + .addPathSegments("files") + .addPathSegment(columnName) + .addPathSegments("scan-status") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), V1GetFileScanStatusResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRecordsClient.java b/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRecordsClient.java new file mode 100644 index 00000000..baf98c1d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRecordsClient.java @@ -0,0 +1,317 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.records.requests.FileServiceUploadFileRequest; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkDeleteRecordBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkGetRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceGetRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.types.V1BatchOperationResponse; +import com.skyflow.generated.rest.types.V1BulkDeleteRecordResponse; +import com.skyflow.generated.rest.types.V1BulkGetRecordResponse; +import com.skyflow.generated.rest.types.V1DeleteFileResponse; +import com.skyflow.generated.rest.types.V1DeleteRecordResponse; +import com.skyflow.generated.rest.types.V1FieldRecords; +import com.skyflow.generated.rest.types.V1GetFileScanStatusResponse; +import com.skyflow.generated.rest.types.V1InsertRecordResponse; +import com.skyflow.generated.rest.types.V1UpdateRecordResponse; +import java.io.File; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +public class AsyncRecordsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawRecordsClient rawClient; + + public AsyncRecordsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawRecordsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawRecordsClient withRawResponse() { + return this.rawClient; + } + + /** + * Performs multiple record operations in a single transaction. + */ + public CompletableFuture recordServiceBatchOperation(String vaultId) { + return this.rawClient.recordServiceBatchOperation(vaultId).thenApply(response -> response.body()); + } + + /** + * Performs multiple record operations in a single transaction. + */ + public CompletableFuture recordServiceBatchOperation( + String vaultId, RecordServiceBatchOperationBody request) { + return this.rawClient.recordServiceBatchOperation(vaultId, request).thenApply(response -> response.body()); + } + + /** + * Performs multiple record operations in a single transaction. + */ + public CompletableFuture recordServiceBatchOperation( + String vaultId, RecordServiceBatchOperationBody request, RequestOptions requestOptions) { + return this.rawClient + .recordServiceBatchOperation(vaultId, request, requestOptions) + .thenApply(response -> response.body()); + } + + /** + * Gets the specified records from a table. + */ + public CompletableFuture recordServiceBulkGetRecord(String vaultId, String objectName) { + return this.rawClient.recordServiceBulkGetRecord(vaultId, objectName).thenApply(response -> response.body()); + } + + /** + * Gets the specified records from a table. + */ + public CompletableFuture recordServiceBulkGetRecord( + String vaultId, String objectName, RecordServiceBulkGetRecordRequest request) { + return this.rawClient + .recordServiceBulkGetRecord(vaultId, objectName, request) + .thenApply(response -> response.body()); + } + + /** + * Gets the specified records from a table. + */ + public CompletableFuture recordServiceBulkGetRecord( + String vaultId, + String objectName, + RecordServiceBulkGetRecordRequest request, + RequestOptions requestOptions) { + return this.rawClient + .recordServiceBulkGetRecord(vaultId, objectName, request, requestOptions) + .thenApply(response -> response.body()); + } + + /** + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + */ + public CompletableFuture recordServiceInsertRecord(String vaultId, String objectName) { + return this.rawClient.recordServiceInsertRecord(vaultId, objectName).thenApply(response -> response.body()); + } + + /** + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + */ + public CompletableFuture recordServiceInsertRecord( + String vaultId, String objectName, RecordServiceInsertRecordBody request) { + return this.rawClient + .recordServiceInsertRecord(vaultId, objectName, request) + .thenApply(response -> response.body()); + } + + /** + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + */ + public CompletableFuture recordServiceInsertRecord( + String vaultId, String objectName, RecordServiceInsertRecordBody request, RequestOptions requestOptions) { + return this.rawClient + .recordServiceInsertRecord(vaultId, objectName, request, requestOptions) + .thenApply(response -> response.body()); + } + + /** + * Deletes the specified records from a table. + */ + public CompletableFuture recordServiceBulkDeleteRecord( + String vaultId, String objectName) { + return this.rawClient.recordServiceBulkDeleteRecord(vaultId, objectName).thenApply(response -> response.body()); + } + + /** + * Deletes the specified records from a table. + */ + public CompletableFuture recordServiceBulkDeleteRecord( + String vaultId, String objectName, RecordServiceBulkDeleteRecordBody request) { + return this.rawClient + .recordServiceBulkDeleteRecord(vaultId, objectName, request) + .thenApply(response -> response.body()); + } + + /** + * Deletes the specified records from a table. + */ + public CompletableFuture recordServiceBulkDeleteRecord( + String vaultId, + String objectName, + RecordServiceBulkDeleteRecordBody request, + RequestOptions requestOptions) { + return this.rawClient + .recordServiceBulkDeleteRecord(vaultId, objectName, request, requestOptions) + .thenApply(response -> response.body()); + } + + /** + * Returns the specified record from a table. + */ + public CompletableFuture recordServiceGetRecord(String vaultId, String objectName, String id) { + return this.rawClient.recordServiceGetRecord(vaultId, objectName, id).thenApply(response -> response.body()); + } + + /** + * Returns the specified record from a table. + */ + public CompletableFuture recordServiceGetRecord( + String vaultId, String objectName, String id, RecordServiceGetRecordRequest request) { + return this.rawClient + .recordServiceGetRecord(vaultId, objectName, id, request) + .thenApply(response -> response.body()); + } + + /** + * Returns the specified record from a table. + */ + public CompletableFuture recordServiceGetRecord( + String vaultId, + String objectName, + String id, + RecordServiceGetRecordRequest request, + RequestOptions requestOptions) { + return this.rawClient + .recordServiceGetRecord(vaultId, objectName, id, request, requestOptions) + .thenApply(response -> response.body()); + } + + /** + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public CompletableFuture recordServiceUpdateRecord( + String vaultId, String objectName, String id) { + return this.rawClient.recordServiceUpdateRecord(vaultId, objectName, id).thenApply(response -> response.body()); + } + + /** + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public CompletableFuture recordServiceUpdateRecord( + String vaultId, String objectName, String id, RecordServiceUpdateRecordBody request) { + return this.rawClient + .recordServiceUpdateRecord(vaultId, objectName, id, request) + .thenApply(response -> response.body()); + } + + /** + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public CompletableFuture recordServiceUpdateRecord( + String vaultId, + String objectName, + String id, + RecordServiceUpdateRecordBody request, + RequestOptions requestOptions) { + return this.rawClient + .recordServiceUpdateRecord(vaultId, objectName, id, request, requestOptions) + .thenApply(response -> response.body()); + } + + /** + * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + */ + public CompletableFuture recordServiceDeleteRecord( + String vaultId, String objectName, String id) { + return this.rawClient.recordServiceDeleteRecord(vaultId, objectName, id).thenApply(response -> response.body()); + } + + /** + * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + */ + public CompletableFuture recordServiceDeleteRecord( + String vaultId, String objectName, String id, RequestOptions requestOptions) { + return this.rawClient + .recordServiceDeleteRecord(vaultId, objectName, id, requestOptions) + .thenApply(response -> response.body()); + } + + /** + * Uploads a file to the specified record. + */ + public CompletableFuture fileServiceUploadFile( + String vaultId, String objectName, String id, Optional fileColumnName) { + return this.rawClient + .fileServiceUploadFile(vaultId, objectName, id, fileColumnName) + .thenApply(response -> response.body()); + } + + /** + * Uploads a file to the specified record. + */ + public CompletableFuture fileServiceUploadFile( + String vaultId, + String objectName, + String id, + Optional fileColumnName, + FileServiceUploadFileRequest request) { + return this.rawClient + .fileServiceUploadFile(vaultId, objectName, id, fileColumnName, request) + .thenApply(response -> response.body()); + } + + /** + * Uploads a file to the specified record. + */ + public CompletableFuture fileServiceUploadFile( + String vaultId, + String objectName, + String id, + Optional fileColumnName, + FileServiceUploadFileRequest request, + RequestOptions requestOptions) { + return this.rawClient + .fileServiceUploadFile(vaultId, objectName, id, fileColumnName, request, requestOptions) + .thenApply(response -> response.body()); + } + + /** + * Deletes a file from the specified record. + */ + public CompletableFuture fileServiceDeleteFile( + String vaultId, String tableName, String id, String columnName) { + return this.rawClient + .fileServiceDeleteFile(vaultId, tableName, id, columnName) + .thenApply(response -> response.body()); + } + + /** + * Deletes a file from the specified record. + */ + public CompletableFuture fileServiceDeleteFile( + String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { + return this.rawClient + .fileServiceDeleteFile(vaultId, tableName, id, columnName, requestOptions) + .thenApply(response -> response.body()); + } + + /** + * Returns the anti-virus scan status of a file. + */ + public CompletableFuture fileServiceGetFileScanStatus( + String vaultId, String tableName, String id, String columnName) { + return this.rawClient + .fileServiceGetFileScanStatus(vaultId, tableName, id, columnName) + .thenApply(response -> response.body()); + } + + /** + * Returns the anti-virus scan status of a file. + */ + public CompletableFuture fileServiceGetFileScanStatus( + String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { + return this.rawClient + .fileServiceGetFileScanStatus(vaultId, tableName, id, columnName, requestOptions) + .thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/RawRecordsClient.java b/src/main/java/com/skyflow/generated/rest/resources/records/RawRecordsClient.java new file mode 100644 index 00000000..593f5e3d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/RawRecordsClient.java @@ -0,0 +1,800 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.records.requests.FileServiceUploadFileRequest; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkDeleteRecordBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkGetRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceGetRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.types.V1BatchOperationResponse; +import com.skyflow.generated.rest.types.V1BulkDeleteRecordResponse; +import com.skyflow.generated.rest.types.V1BulkGetRecordResponse; +import com.skyflow.generated.rest.types.V1DeleteFileResponse; +import com.skyflow.generated.rest.types.V1DeleteRecordResponse; +import com.skyflow.generated.rest.types.V1FieldRecords; +import com.skyflow.generated.rest.types.V1GetFileScanStatusResponse; +import com.skyflow.generated.rest.types.V1InsertRecordResponse; +import com.skyflow.generated.rest.types.V1UpdateRecordResponse; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Optional; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawRecordsClient { + protected final ClientOptions clientOptions; + + public RawRecordsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Performs multiple record operations in a single transaction. + */ + public ApiClientHttpResponse recordServiceBatchOperation(String vaultId) { + return recordServiceBatchOperation( + vaultId, RecordServiceBatchOperationBody.builder().build()); + } + + /** + * Performs multiple record operations in a single transaction. + */ + public ApiClientHttpResponse recordServiceBatchOperation( + String vaultId, RecordServiceBatchOperationBody request) { + return recordServiceBatchOperation(vaultId, request, null); + } + + /** + * Performs multiple record operations in a single transaction. + */ + public ApiClientHttpResponse recordServiceBatchOperation( + String vaultId, RecordServiceBatchOperationBody request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1BatchOperationResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Gets the specified records from a table. + */ + public ApiClientHttpResponse recordServiceBulkGetRecord( + String vaultId, String objectName) { + return recordServiceBulkGetRecord( + vaultId, objectName, RecordServiceBulkGetRecordRequest.builder().build()); + } + + /** + * Gets the specified records from a table. + */ + public ApiClientHttpResponse recordServiceBulkGetRecord( + String vaultId, String objectName, RecordServiceBulkGetRecordRequest request) { + return recordServiceBulkGetRecord(vaultId, objectName, request, null); + } + + /** + * Gets the specified records from a table. + */ + public ApiClientHttpResponse recordServiceBulkGetRecord( + String vaultId, + String objectName, + RecordServiceBulkGetRecordRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName); + if (request.getRedaction().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "redaction", request.getRedaction().get(), false); + } + if (request.getTokenization().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "tokenization", request.getTokenization().get(), false); + } + if (request.getOffset().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "offset", request.getOffset().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getDownloadUrl().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "downloadURL", request.getDownloadUrl().get(), false); + } + if (request.getColumnName().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "column_name", request.getColumnName().get(), false); + } + if (request.getOrderBy().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "order_by", request.getOrderBy().get(), false); + } + if (request.getSkyflowIds().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "skyflow_ids", request.getSkyflowIds().get(), true); + } + if (request.getFields().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "fields", request.getFields().get(), true); + } + if (request.getColumnValues().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "column_values", request.getColumnValues().get(), true); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1BulkGetRecordResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + */ + public ApiClientHttpResponse recordServiceInsertRecord(String vaultId, String objectName) { + return recordServiceInsertRecord( + vaultId, objectName, RecordServiceInsertRecordBody.builder().build()); + } + + /** + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + */ + public ApiClientHttpResponse recordServiceInsertRecord( + String vaultId, String objectName, RecordServiceInsertRecordBody request) { + return recordServiceInsertRecord(vaultId, objectName, request, null); + } + + /** + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + */ + public ApiClientHttpResponse recordServiceInsertRecord( + String vaultId, String objectName, RecordServiceInsertRecordBody request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1InsertRecordResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Deletes the specified records from a table. + */ + public ApiClientHttpResponse recordServiceBulkDeleteRecord( + String vaultId, String objectName) { + return recordServiceBulkDeleteRecord( + vaultId, objectName, RecordServiceBulkDeleteRecordBody.builder().build()); + } + + /** + * Deletes the specified records from a table. + */ + public ApiClientHttpResponse recordServiceBulkDeleteRecord( + String vaultId, String objectName, RecordServiceBulkDeleteRecordBody request) { + return recordServiceBulkDeleteRecord(vaultId, objectName, request, null); + } + + /** + * Deletes the specified records from a table. + */ + public ApiClientHttpResponse recordServiceBulkDeleteRecord( + String vaultId, + String objectName, + RecordServiceBulkDeleteRecordBody request, + RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1BulkDeleteRecordResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Returns the specified record from a table. + */ + public ApiClientHttpResponse recordServiceGetRecord(String vaultId, String objectName, String id) { + return recordServiceGetRecord( + vaultId, objectName, id, RecordServiceGetRecordRequest.builder().build()); + } + + /** + * Returns the specified record from a table. + */ + public ApiClientHttpResponse recordServiceGetRecord( + String vaultId, String objectName, String id, RecordServiceGetRecordRequest request) { + return recordServiceGetRecord(vaultId, objectName, id, request, null); + } + + /** + * Returns the specified record from a table. + */ + public ApiClientHttpResponse recordServiceGetRecord( + String vaultId, + String objectName, + String id, + RecordServiceGetRecordRequest request, + RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName) + .addPathSegment(id); + if (request.getRedaction().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "redaction", request.getRedaction().get(), false); + } + if (request.getTokenization().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "tokenization", request.getTokenization().get(), false); + } + if (request.getDownloadUrl().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "downloadURL", request.getDownloadUrl().get(), false); + } + if (request.getFields().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "fields", request.getFields().get(), true); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1FieldRecords.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public ApiClientHttpResponse recordServiceUpdateRecord( + String vaultId, String objectName, String id) { + return recordServiceUpdateRecord( + vaultId, objectName, id, RecordServiceUpdateRecordBody.builder().build()); + } + + /** + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public ApiClientHttpResponse recordServiceUpdateRecord( + String vaultId, String objectName, String id, RecordServiceUpdateRecordBody request) { + return recordServiceUpdateRecord(vaultId, objectName, id, request, null); + } + + /** + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public ApiClientHttpResponse recordServiceUpdateRecord( + String vaultId, + String objectName, + String id, + RecordServiceUpdateRecordBody request, + RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName) + .addPathSegment(id) + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("PUT", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1UpdateRecordResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + */ + public ApiClientHttpResponse recordServiceDeleteRecord( + String vaultId, String objectName, String id) { + return recordServiceDeleteRecord(vaultId, objectName, id, null); + } + + /** + * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + */ + public ApiClientHttpResponse recordServiceDeleteRecord( + String vaultId, String objectName, String id, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName) + .addPathSegment(id) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DeleteRecordResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Uploads a file to the specified record. + */ + public ApiClientHttpResponse fileServiceUploadFile( + String vaultId, String objectName, String id, Optional fileColumnName) { + return fileServiceUploadFile( + vaultId, + objectName, + id, + fileColumnName, + FileServiceUploadFileRequest.builder().build()); + } + + /** + * Uploads a file to the specified record. + */ + public ApiClientHttpResponse fileServiceUploadFile( + String vaultId, + String objectName, + String id, + Optional fileColumnName, + FileServiceUploadFileRequest request) { + return fileServiceUploadFile(vaultId, objectName, id, fileColumnName, request, null); + } + + /** + * Uploads a file to the specified record. + */ + public ApiClientHttpResponse fileServiceUploadFile( + String vaultId, + String objectName, + String id, + Optional fileColumnName, + FileServiceUploadFileRequest request, + RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(objectName) + .addPathSegment(id) + .addPathSegments("files") + .build(); + MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM); + try { + if (fileColumnName.isPresent()) { + String fileColumnNameMimeType = + Files.probeContentType(fileColumnName.get().toPath()); + MediaType fileColumnNameMimeTypeMediaType = + fileColumnNameMimeType != null ? MediaType.parse(fileColumnNameMimeType) : null; + body.addFormDataPart( + "fileColumnName", + fileColumnName.get().getName(), + RequestBody.create(fileColumnName.get(), fileColumnNameMimeTypeMediaType)); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", body.build()) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1UpdateRecordResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Deletes a file from the specified record. + */ + public ApiClientHttpResponse fileServiceDeleteFile( + String vaultId, String tableName, String id, String columnName) { + return fileServiceDeleteFile(vaultId, tableName, id, columnName, null); + } + + /** + * Deletes a file from the specified record. + */ + public ApiClientHttpResponse fileServiceDeleteFile( + String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(tableName) + .addPathSegment(id) + .addPathSegments("files") + .addPathSegment(columnName) + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("DELETE", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DeleteFileResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Returns the anti-virus scan status of a file. + */ + public ApiClientHttpResponse fileServiceGetFileScanStatus( + String vaultId, String tableName, String id, String columnName) { + return fileServiceGetFileScanStatus(vaultId, tableName, id, columnName, null); + } + + /** + * Returns the anti-virus scan status of a file. + */ + public ApiClientHttpResponse fileServiceGetFileScanStatus( + String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegment(tableName) + .addPathSegment(id) + .addPathSegments("files") + .addPathSegment(columnName) + .addPathSegments("scan-status") + .build(); + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1GetFileScanStatusResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/RecordsClient.java b/src/main/java/com/skyflow/generated/rest/resources/records/RecordsClient.java new file mode 100644 index 00000000..fee9d49b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/RecordsClient.java @@ -0,0 +1,312 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.records.requests.FileServiceUploadFileRequest; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkDeleteRecordBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkGetRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceGetRecordRequest; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.types.V1BatchOperationResponse; +import com.skyflow.generated.rest.types.V1BulkDeleteRecordResponse; +import com.skyflow.generated.rest.types.V1BulkGetRecordResponse; +import com.skyflow.generated.rest.types.V1DeleteFileResponse; +import com.skyflow.generated.rest.types.V1DeleteRecordResponse; +import com.skyflow.generated.rest.types.V1FieldRecords; +import com.skyflow.generated.rest.types.V1GetFileScanStatusResponse; +import com.skyflow.generated.rest.types.V1InsertRecordResponse; +import com.skyflow.generated.rest.types.V1UpdateRecordResponse; +import java.io.File; +import java.util.Optional; + +public class RecordsClient { + protected final ClientOptions clientOptions; + + private final RawRecordsClient rawClient; + + public RecordsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawRecordsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawRecordsClient withRawResponse() { + return this.rawClient; + } + + /** + * Performs multiple record operations in a single transaction. + */ + public V1BatchOperationResponse recordServiceBatchOperation(String vaultId) { + return this.rawClient.recordServiceBatchOperation(vaultId).body(); + } + + /** + * Performs multiple record operations in a single transaction. + */ + public V1BatchOperationResponse recordServiceBatchOperation( + String vaultId, RecordServiceBatchOperationBody request) { + return this.rawClient.recordServiceBatchOperation(vaultId, request).body(); + } + + /** + * Performs multiple record operations in a single transaction. + */ + public V1BatchOperationResponse recordServiceBatchOperation( + String vaultId, RecordServiceBatchOperationBody request, RequestOptions requestOptions) { + return this.rawClient + .recordServiceBatchOperation(vaultId, request, requestOptions) + .body(); + } + + /** + * Gets the specified records from a table. + */ + public V1BulkGetRecordResponse recordServiceBulkGetRecord(String vaultId, String objectName) { + return this.rawClient.recordServiceBulkGetRecord(vaultId, objectName).body(); + } + + /** + * Gets the specified records from a table. + */ + public V1BulkGetRecordResponse recordServiceBulkGetRecord( + String vaultId, String objectName, RecordServiceBulkGetRecordRequest request) { + return this.rawClient + .recordServiceBulkGetRecord(vaultId, objectName, request) + .body(); + } + + /** + * Gets the specified records from a table. + */ + public V1BulkGetRecordResponse recordServiceBulkGetRecord( + String vaultId, + String objectName, + RecordServiceBulkGetRecordRequest request, + RequestOptions requestOptions) { + return this.rawClient + .recordServiceBulkGetRecord(vaultId, objectName, request, requestOptions) + .body(); + } + + /** + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + */ + public V1InsertRecordResponse recordServiceInsertRecord(String vaultId, String objectName) { + return this.rawClient.recordServiceInsertRecord(vaultId, objectName).body(); + } + + /** + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + */ + public V1InsertRecordResponse recordServiceInsertRecord( + String vaultId, String objectName, RecordServiceInsertRecordBody request) { + return this.rawClient + .recordServiceInsertRecord(vaultId, objectName, request) + .body(); + } + + /** + * Inserts a record in the specified table.<br /><br />The time-to-live (TTL) for a transient field begins when the field value is set during record insertion.<br /><br />Columns that have a string data type and a uniqueness constraint accept strings up to 2500 characters. If an inserted string exceeds 2500 characters, the call returns a token insertion error. + */ + public V1InsertRecordResponse recordServiceInsertRecord( + String vaultId, String objectName, RecordServiceInsertRecordBody request, RequestOptions requestOptions) { + return this.rawClient + .recordServiceInsertRecord(vaultId, objectName, request, requestOptions) + .body(); + } + + /** + * Deletes the specified records from a table. + */ + public V1BulkDeleteRecordResponse recordServiceBulkDeleteRecord(String vaultId, String objectName) { + return this.rawClient.recordServiceBulkDeleteRecord(vaultId, objectName).body(); + } + + /** + * Deletes the specified records from a table. + */ + public V1BulkDeleteRecordResponse recordServiceBulkDeleteRecord( + String vaultId, String objectName, RecordServiceBulkDeleteRecordBody request) { + return this.rawClient + .recordServiceBulkDeleteRecord(vaultId, objectName, request) + .body(); + } + + /** + * Deletes the specified records from a table. + */ + public V1BulkDeleteRecordResponse recordServiceBulkDeleteRecord( + String vaultId, + String objectName, + RecordServiceBulkDeleteRecordBody request, + RequestOptions requestOptions) { + return this.rawClient + .recordServiceBulkDeleteRecord(vaultId, objectName, request, requestOptions) + .body(); + } + + /** + * Returns the specified record from a table. + */ + public V1FieldRecords recordServiceGetRecord(String vaultId, String objectName, String id) { + return this.rawClient.recordServiceGetRecord(vaultId, objectName, id).body(); + } + + /** + * Returns the specified record from a table. + */ + public V1FieldRecords recordServiceGetRecord( + String vaultId, String objectName, String id, RecordServiceGetRecordRequest request) { + return this.rawClient + .recordServiceGetRecord(vaultId, objectName, id, request) + .body(); + } + + /** + * Returns the specified record from a table. + */ + public V1FieldRecords recordServiceGetRecord( + String vaultId, + String objectName, + String id, + RecordServiceGetRecordRequest request, + RequestOptions requestOptions) { + return this.rawClient + .recordServiceGetRecord(vaultId, objectName, id, request, requestOptions) + .body(); + } + + /** + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public V1UpdateRecordResponse recordServiceUpdateRecord(String vaultId, String objectName, String id) { + return this.rawClient.recordServiceUpdateRecord(vaultId, objectName, id).body(); + } + + /** + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public V1UpdateRecordResponse recordServiceUpdateRecord( + String vaultId, String objectName, String id, RecordServiceUpdateRecordBody request) { + return this.rawClient + .recordServiceUpdateRecord(vaultId, objectName, id, request) + .body(); + } + + /** + * Updates the specified record in a table.<br /><br />When you update a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.<br /><br />The time-to-live (TTL) for a transient field resets when the field value is updated. + */ + public V1UpdateRecordResponse recordServiceUpdateRecord( + String vaultId, + String objectName, + String id, + RecordServiceUpdateRecordBody request, + RequestOptions requestOptions) { + return this.rawClient + .recordServiceUpdateRecord(vaultId, objectName, id, request, requestOptions) + .body(); + } + + /** + * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + */ + public V1DeleteRecordResponse recordServiceDeleteRecord(String vaultId, String objectName, String id) { + return this.rawClient.recordServiceDeleteRecord(vaultId, objectName, id).body(); + } + + /** + * Deletes the specified record from a table.<br /><br /><b>Note:</b> This method doesn't delete transient field tokens. Transient field values are available until they expire based on the fields' time-to-live (TTL) setting. + */ + public V1DeleteRecordResponse recordServiceDeleteRecord( + String vaultId, String objectName, String id, RequestOptions requestOptions) { + return this.rawClient + .recordServiceDeleteRecord(vaultId, objectName, id, requestOptions) + .body(); + } + + /** + * Uploads a file to the specified record. + */ + public V1UpdateRecordResponse fileServiceUploadFile( + String vaultId, String objectName, String id, Optional fileColumnName) { + return this.rawClient + .fileServiceUploadFile(vaultId, objectName, id, fileColumnName) + .body(); + } + + /** + * Uploads a file to the specified record. + */ + public V1UpdateRecordResponse fileServiceUploadFile( + String vaultId, + String objectName, + String id, + Optional fileColumnName, + FileServiceUploadFileRequest request) { + return this.rawClient + .fileServiceUploadFile(vaultId, objectName, id, fileColumnName, request) + .body(); + } + + /** + * Uploads a file to the specified record. + */ + public V1UpdateRecordResponse fileServiceUploadFile( + String vaultId, + String objectName, + String id, + Optional fileColumnName, + FileServiceUploadFileRequest request, + RequestOptions requestOptions) { + return this.rawClient + .fileServiceUploadFile(vaultId, objectName, id, fileColumnName, request, requestOptions) + .body(); + } + + /** + * Deletes a file from the specified record. + */ + public V1DeleteFileResponse fileServiceDeleteFile(String vaultId, String tableName, String id, String columnName) { + return this.rawClient + .fileServiceDeleteFile(vaultId, tableName, id, columnName) + .body(); + } + + /** + * Deletes a file from the specified record. + */ + public V1DeleteFileResponse fileServiceDeleteFile( + String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { + return this.rawClient + .fileServiceDeleteFile(vaultId, tableName, id, columnName, requestOptions) + .body(); + } + + /** + * Returns the anti-virus scan status of a file. + */ + public V1GetFileScanStatusResponse fileServiceGetFileScanStatus( + String vaultId, String tableName, String id, String columnName) { + return this.rawClient + .fileServiceGetFileScanStatus(vaultId, tableName, id, columnName) + .body(); + } + + /** + * Returns the anti-virus scan status of a file. + */ + public V1GetFileScanStatusResponse fileServiceGetFileScanStatus( + String vaultId, String tableName, String id, String columnName, RequestOptions requestOptions) { + return this.rawClient + .fileServiceGetFileScanStatus(vaultId, tableName, id, columnName, requestOptions) + .body(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/requests/FileServiceUploadFileRequest.java b/src/main/java/com/skyflow/generated/rest/resources/records/requests/FileServiceUploadFileRequest.java new file mode 100644 index 00000000..d1b64906 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/requests/FileServiceUploadFileRequest.java @@ -0,0 +1,59 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = FileServiceUploadFileRequest.Builder.class) +public final class FileServiceUploadFileRequest { + private final Map additionalProperties; + + private FileServiceUploadFileRequest(Map additionalProperties) { + this.additionalProperties = additionalProperties; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof FileServiceUploadFileRequest; + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(FileServiceUploadFileRequest other) { + return this; + } + + public FileServiceUploadFileRequest build() { + return new FileServiceUploadFileRequest(additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBatchOperationBody.java b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBatchOperationBody.java new file mode 100644 index 00000000..33b92483 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBatchOperationBody.java @@ -0,0 +1,160 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.V1BatchRecord; +import com.skyflow.generated.rest.types.V1Byot; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = RecordServiceBatchOperationBody.Builder.class) +public final class RecordServiceBatchOperationBody { + private final Optional> records; + + private final Optional continueOnError; + + private final Optional byot; + + private final Map additionalProperties; + + private RecordServiceBatchOperationBody( + Optional> records, + Optional continueOnError, + Optional byot, + Map additionalProperties) { + this.records = records; + this.continueOnError = continueOnError; + this.byot = byot; + this.additionalProperties = additionalProperties; + } + + /** + * @return Record operations to perform. + */ + @JsonProperty("records") + public Optional> getRecords() { + return records; + } + + /** + * @return Continue performing operations on partial errors. + */ + @JsonProperty("continueOnError") + public Optional getContinueOnError() { + return continueOnError; + } + + @JsonProperty("byot") + public Optional getByot() { + return byot; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof RecordServiceBatchOperationBody && equalTo((RecordServiceBatchOperationBody) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(RecordServiceBatchOperationBody other) { + return records.equals(other.records) + && continueOnError.equals(other.continueOnError) + && byot.equals(other.byot); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records, this.continueOnError, this.byot); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> records = Optional.empty(); + + private Optional continueOnError = Optional.empty(); + + private Optional byot = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(RecordServiceBatchOperationBody other) { + records(other.getRecords()); + continueOnError(other.getContinueOnError()); + byot(other.getByot()); + return this; + } + + /** + *

Record operations to perform.

+ */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(Optional> records) { + this.records = records; + return this; + } + + public Builder records(List records) { + this.records = Optional.ofNullable(records); + return this; + } + + /** + *

Continue performing operations on partial errors.

+ */ + @JsonSetter(value = "continueOnError", nulls = Nulls.SKIP) + public Builder continueOnError(Optional continueOnError) { + this.continueOnError = continueOnError; + return this; + } + + public Builder continueOnError(Boolean continueOnError) { + this.continueOnError = Optional.ofNullable(continueOnError); + return this; + } + + @JsonSetter(value = "byot", nulls = Nulls.SKIP) + public Builder byot(Optional byot) { + this.byot = byot; + return this; + } + + public Builder byot(V1Byot byot) { + this.byot = Optional.ofNullable(byot); + return this; + } + + public RecordServiceBatchOperationBody build() { + return new RecordServiceBatchOperationBody(records, continueOnError, byot, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkDeleteRecordBody.java b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkDeleteRecordBody.java new file mode 100644 index 00000000..b2c991f9 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkDeleteRecordBody.java @@ -0,0 +1,103 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = RecordServiceBulkDeleteRecordBody.Builder.class) +public final class RecordServiceBulkDeleteRecordBody { + private final Optional> skyflowIds; + + private final Map additionalProperties; + + private RecordServiceBulkDeleteRecordBody( + Optional> skyflowIds, Map additionalProperties) { + this.skyflowIds = skyflowIds; + this.additionalProperties = additionalProperties; + } + + /** + * @return skyflow_id values of the records to delete. If * is specified, this operation deletes all records in the table. + */ + @JsonProperty("skyflow_ids") + public Optional> getSkyflowIds() { + return skyflowIds; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof RecordServiceBulkDeleteRecordBody && equalTo((RecordServiceBulkDeleteRecordBody) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(RecordServiceBulkDeleteRecordBody other) { + return skyflowIds.equals(other.skyflowIds); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.skyflowIds); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> skyflowIds = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(RecordServiceBulkDeleteRecordBody other) { + skyflowIds(other.getSkyflowIds()); + return this; + } + + /** + *

skyflow_id values of the records to delete. If * is specified, this operation deletes all records in the table.

+ */ + @JsonSetter(value = "skyflow_ids", nulls = Nulls.SKIP) + public Builder skyflowIds(Optional> skyflowIds) { + this.skyflowIds = skyflowIds; + return this; + } + + public Builder skyflowIds(List skyflowIds) { + this.skyflowIds = Optional.ofNullable(skyflowIds); + return this; + } + + public RecordServiceBulkDeleteRecordBody build() { + return new RecordServiceBulkDeleteRecordBody(skyflowIds, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkGetRecordRequest.java b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkGetRecordRequest.java new file mode 100644 index 00000000..f8cccf09 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBulkGetRecordRequest.java @@ -0,0 +1,413 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.records.types.RecordServiceBulkGetRecordRequestOrderBy; +import com.skyflow.generated.rest.resources.records.types.RecordServiceBulkGetRecordRequestRedaction; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = RecordServiceBulkGetRecordRequest.Builder.class) +public final class RecordServiceBulkGetRecordRequest { + private final Optional> skyflowIds; + + private final Optional> fields; + + private final Optional> columnValues; + + private final Optional redaction; + + private final Optional tokenization; + + private final Optional offset; + + private final Optional limit; + + private final Optional downloadUrl; + + private final Optional columnName; + + private final Optional orderBy; + + private final Map additionalProperties; + + private RecordServiceBulkGetRecordRequest( + Optional> skyflowIds, + Optional> fields, + Optional> columnValues, + Optional redaction, + Optional tokenization, + Optional offset, + Optional limit, + Optional downloadUrl, + Optional columnName, + Optional orderBy, + Map additionalProperties) { + this.skyflowIds = skyflowIds; + this.fields = fields; + this.columnValues = columnValues; + this.redaction = redaction; + this.tokenization = tokenization; + this.offset = offset; + this.limit = limit; + this.downloadUrl = downloadUrl; + this.columnName = columnName; + this.orderBy = orderBy; + this.additionalProperties = additionalProperties; + } + + /** + * @return skyflow_id values of the records to return, with one value per skyflow_ids URL parameter. For example, ?skyflow_ids=abc&skyflow_ids=123.<br /><br />If not specified, returns the first 25 records in the table. + */ + @JsonProperty("skyflow_ids") + public Optional> getSkyflowIds() { + return skyflowIds; + } + + /** + * @return Fields to return for the record, with one value per fields URL parameter. For example, ?fields=abc&fields=123.<br /><br />If not specified, returns all fields. + */ + @JsonProperty("fields") + public Optional> getFields() { + return fields; + } + + /** + * @return Column values of the records to return, with one value per column_values URL parameter. For example, ?column_values=abc&column_values=123.<br /><br />column_name is mandatory when providing column_values. If you use column name or column value, you cannot use skyflow_ids. Passing either of these parameters with skyflow_ids returns an error. + */ + @JsonProperty("column_values") + public Optional> getColumnValues() { + return columnValues; + } + + /** + * @return Redaction level to enforce for the returned records. Subject to policies assigned to the API caller. + */ + @JsonProperty("redaction") + public Optional getRedaction() { + return redaction; + } + + /** + * @return If true, this operation returns tokens for fields with tokenization enabled. Only applicable if skyflow_id values are specified. + */ + @JsonProperty("tokenization") + public Optional getTokenization() { + return tokenization; + } + + /** + * @return Record position at which to start receiving data. + */ + @JsonProperty("offset") + public Optional getOffset() { + return offset; + } + + /** + * @return Number of record to return. Maximum 25. + */ + @JsonProperty("limit") + public Optional getLimit() { + return limit; + } + + /** + * @return If true, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + */ + @JsonProperty("downloadURL") + public Optional getDownloadUrl() { + return downloadUrl; + } + + /** + * @return Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use skyflow_ids. Passing either of these parameters with skyflow_ids returns an error. + */ + @JsonProperty("column_name") + public Optional getColumnName() { + return columnName; + } + + /** + * @return Order to return records, based on skyflow_id values. To disable, set to NONE. + */ + @JsonProperty("order_by") + public Optional getOrderBy() { + return orderBy; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof RecordServiceBulkGetRecordRequest && equalTo((RecordServiceBulkGetRecordRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(RecordServiceBulkGetRecordRequest other) { + return skyflowIds.equals(other.skyflowIds) + && fields.equals(other.fields) + && columnValues.equals(other.columnValues) + && redaction.equals(other.redaction) + && tokenization.equals(other.tokenization) + && offset.equals(other.offset) + && limit.equals(other.limit) + && downloadUrl.equals(other.downloadUrl) + && columnName.equals(other.columnName) + && orderBy.equals(other.orderBy); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.skyflowIds, + this.fields, + this.columnValues, + this.redaction, + this.tokenization, + this.offset, + this.limit, + this.downloadUrl, + this.columnName, + this.orderBy); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> skyflowIds = Optional.empty(); + + private Optional> fields = Optional.empty(); + + private Optional> columnValues = Optional.empty(); + + private Optional redaction = Optional.empty(); + + private Optional tokenization = Optional.empty(); + + private Optional offset = Optional.empty(); + + private Optional limit = Optional.empty(); + + private Optional downloadUrl = Optional.empty(); + + private Optional columnName = Optional.empty(); + + private Optional orderBy = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(RecordServiceBulkGetRecordRequest other) { + skyflowIds(other.getSkyflowIds()); + fields(other.getFields()); + columnValues(other.getColumnValues()); + redaction(other.getRedaction()); + tokenization(other.getTokenization()); + offset(other.getOffset()); + limit(other.getLimit()); + downloadUrl(other.getDownloadUrl()); + columnName(other.getColumnName()); + orderBy(other.getOrderBy()); + return this; + } + + /** + *

skyflow_id values of the records to return, with one value per skyflow_ids URL parameter. For example, ?skyflow_ids=abc&skyflow_ids=123.<br /><br />If not specified, returns the first 25 records in the table.

+ */ + @JsonSetter(value = "skyflow_ids", nulls = Nulls.SKIP) + public Builder skyflowIds(Optional> skyflowIds) { + this.skyflowIds = skyflowIds; + return this; + } + + public Builder skyflowIds(List skyflowIds) { + this.skyflowIds = Optional.ofNullable(skyflowIds); + return this; + } + + public Builder skyflowIds(String skyflowIds) { + this.skyflowIds = Optional.of(Collections.singletonList(skyflowIds)); + return this; + } + + /** + *

Fields to return for the record, with one value per fields URL parameter. For example, ?fields=abc&fields=123.<br /><br />If not specified, returns all fields.

+ */ + @JsonSetter(value = "fields", nulls = Nulls.SKIP) + public Builder fields(Optional> fields) { + this.fields = fields; + return this; + } + + public Builder fields(List fields) { + this.fields = Optional.ofNullable(fields); + return this; + } + + public Builder fields(String fields) { + this.fields = Optional.of(Collections.singletonList(fields)); + return this; + } + + /** + *

Column values of the records to return, with one value per column_values URL parameter. For example, ?column_values=abc&column_values=123.<br /><br />column_name is mandatory when providing column_values. If you use column name or column value, you cannot use skyflow_ids. Passing either of these parameters with skyflow_ids returns an error.

+ */ + @JsonSetter(value = "column_values", nulls = Nulls.SKIP) + public Builder columnValues(Optional> columnValues) { + this.columnValues = columnValues; + return this; + } + + public Builder columnValues(List columnValues) { + this.columnValues = Optional.ofNullable(columnValues); + return this; + } + + public Builder columnValues(String columnValues) { + this.columnValues = Optional.of(Collections.singletonList(columnValues)); + return this; + } + + /** + *

Redaction level to enforce for the returned records. Subject to policies assigned to the API caller.

+ */ + @JsonSetter(value = "redaction", nulls = Nulls.SKIP) + public Builder redaction(Optional redaction) { + this.redaction = redaction; + return this; + } + + public Builder redaction(RecordServiceBulkGetRecordRequestRedaction redaction) { + this.redaction = Optional.ofNullable(redaction); + return this; + } + + /** + *

If true, this operation returns tokens for fields with tokenization enabled. Only applicable if skyflow_id values are specified.

+ */ + @JsonSetter(value = "tokenization", nulls = Nulls.SKIP) + public Builder tokenization(Optional tokenization) { + this.tokenization = tokenization; + return this; + } + + public Builder tokenization(Boolean tokenization) { + this.tokenization = Optional.ofNullable(tokenization); + return this; + } + + /** + *

Record position at which to start receiving data.

+ */ + @JsonSetter(value = "offset", nulls = Nulls.SKIP) + public Builder offset(Optional offset) { + this.offset = offset; + return this; + } + + public Builder offset(String offset) { + this.offset = Optional.ofNullable(offset); + return this; + } + + /** + *

Number of record to return. Maximum 25.

+ */ + @JsonSetter(value = "limit", nulls = Nulls.SKIP) + public Builder limit(Optional limit) { + this.limit = limit; + return this; + } + + public Builder limit(String limit) { + this.limit = Optional.ofNullable(limit); + return this; + } + + /** + *

If true, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean.

+ */ + @JsonSetter(value = "downloadURL", nulls = Nulls.SKIP) + public Builder downloadUrl(Optional downloadUrl) { + this.downloadUrl = downloadUrl; + return this; + } + + public Builder downloadUrl(Boolean downloadUrl) { + this.downloadUrl = Optional.ofNullable(downloadUrl); + return this; + } + + /** + *

Name of the column. It must be configured as unique in the schema. If you provide both column name or column value, you cannot use skyflow_ids. Passing either of these parameters with skyflow_ids returns an error.

+ */ + @JsonSetter(value = "column_name", nulls = Nulls.SKIP) + public Builder columnName(Optional columnName) { + this.columnName = columnName; + return this; + } + + public Builder columnName(String columnName) { + this.columnName = Optional.ofNullable(columnName); + return this; + } + + /** + *

Order to return records, based on skyflow_id values. To disable, set to NONE.

+ */ + @JsonSetter(value = "order_by", nulls = Nulls.SKIP) + public Builder orderBy(Optional orderBy) { + this.orderBy = orderBy; + return this; + } + + public Builder orderBy(RecordServiceBulkGetRecordRequestOrderBy orderBy) { + this.orderBy = Optional.ofNullable(orderBy); + return this; + } + + public RecordServiceBulkGetRecordRequest build() { + return new RecordServiceBulkGetRecordRequest( + skyflowIds, + fields, + columnValues, + redaction, + tokenization, + offset, + limit, + downloadUrl, + columnName, + orderBy, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceGetRecordRequest.java b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceGetRecordRequest.java new file mode 100644 index 00000000..0fa5319d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceGetRecordRequest.java @@ -0,0 +1,202 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.records.types.RecordServiceGetRecordRequestRedaction; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = RecordServiceGetRecordRequest.Builder.class) +public final class RecordServiceGetRecordRequest { + private final Optional> fields; + + private final Optional redaction; + + private final Optional tokenization; + + private final Optional downloadUrl; + + private final Map additionalProperties; + + private RecordServiceGetRecordRequest( + Optional> fields, + Optional redaction, + Optional tokenization, + Optional downloadUrl, + Map additionalProperties) { + this.fields = fields; + this.redaction = redaction; + this.tokenization = tokenization; + this.downloadUrl = downloadUrl; + this.additionalProperties = additionalProperties; + } + + /** + * @return Fields to return for the record, with one value per fields URL parameter. For example, ?fields=abc&fields=123.<br /><br />If not specified, returns all fields. + */ + @JsonProperty("fields") + public Optional> getFields() { + return fields; + } + + /** + * @return Redaction level to enforce for the returned record. Subject to policies assigned to the API caller. + */ + @JsonProperty("redaction") + public Optional getRedaction() { + return redaction; + } + + /** + * @return If true, this operation returns tokens for fields with tokenization enabled. Only applicable if skyflow_id values are specified. + */ + @JsonProperty("tokenization") + public Optional getTokenization() { + return tokenization; + } + + /** + * @return If true, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + */ + @JsonProperty("downloadURL") + public Optional getDownloadUrl() { + return downloadUrl; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof RecordServiceGetRecordRequest && equalTo((RecordServiceGetRecordRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(RecordServiceGetRecordRequest other) { + return fields.equals(other.fields) + && redaction.equals(other.redaction) + && tokenization.equals(other.tokenization) + && downloadUrl.equals(other.downloadUrl); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.fields, this.redaction, this.tokenization, this.downloadUrl); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> fields = Optional.empty(); + + private Optional redaction = Optional.empty(); + + private Optional tokenization = Optional.empty(); + + private Optional downloadUrl = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(RecordServiceGetRecordRequest other) { + fields(other.getFields()); + redaction(other.getRedaction()); + tokenization(other.getTokenization()); + downloadUrl(other.getDownloadUrl()); + return this; + } + + /** + *

Fields to return for the record, with one value per fields URL parameter. For example, ?fields=abc&fields=123.<br /><br />If not specified, returns all fields.

+ */ + @JsonSetter(value = "fields", nulls = Nulls.SKIP) + public Builder fields(Optional> fields) { + this.fields = fields; + return this; + } + + public Builder fields(List fields) { + this.fields = Optional.ofNullable(fields); + return this; + } + + public Builder fields(String fields) { + this.fields = Optional.of(Collections.singletonList(fields)); + return this; + } + + /** + *

Redaction level to enforce for the returned record. Subject to policies assigned to the API caller.

+ */ + @JsonSetter(value = "redaction", nulls = Nulls.SKIP) + public Builder redaction(Optional redaction) { + this.redaction = redaction; + return this; + } + + public Builder redaction(RecordServiceGetRecordRequestRedaction redaction) { + this.redaction = Optional.ofNullable(redaction); + return this; + } + + /** + *

If true, this operation returns tokens for fields with tokenization enabled. Only applicable if skyflow_id values are specified.

+ */ + @JsonSetter(value = "tokenization", nulls = Nulls.SKIP) + public Builder tokenization(Optional tokenization) { + this.tokenization = tokenization; + return this; + } + + public Builder tokenization(Boolean tokenization) { + this.tokenization = Optional.ofNullable(tokenization); + return this; + } + + /** + *

If true, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean.

+ */ + @JsonSetter(value = "downloadURL", nulls = Nulls.SKIP) + public Builder downloadUrl(Optional downloadUrl) { + this.downloadUrl = downloadUrl; + return this; + } + + public Builder downloadUrl(Boolean downloadUrl) { + this.downloadUrl = Optional.ofNullable(downloadUrl); + return this; + } + + public RecordServiceGetRecordRequest build() { + return new RecordServiceGetRecordRequest( + fields, redaction, tokenization, downloadUrl, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceInsertRecordBody.java b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceInsertRecordBody.java new file mode 100644 index 00000000..4ac78692 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceInsertRecordBody.java @@ -0,0 +1,221 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.V1Byot; +import com.skyflow.generated.rest.types.V1FieldRecords; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = RecordServiceInsertRecordBody.Builder.class) +public final class RecordServiceInsertRecordBody { + private final Optional> records; + + private final Optional tokenization; + + private final Optional upsert; + + private final Optional homogeneous; + + private final Optional byot; + + private final Map additionalProperties; + + private RecordServiceInsertRecordBody( + Optional> records, + Optional tokenization, + Optional upsert, + Optional homogeneous, + Optional byot, + Map additionalProperties) { + this.records = records; + this.tokenization = tokenization; + this.upsert = upsert; + this.homogeneous = homogeneous; + this.byot = byot; + this.additionalProperties = additionalProperties; + } + + /** + * @return Record values and tokens. + */ + @JsonProperty("records") + public Optional> getRecords() { + return records; + } + + /** + * @return If true, this operation returns tokens for fields with tokenization enabled. + */ + @JsonProperty("tokenization") + public Optional getTokenization() { + return tokenization; + } + + /** + * @return Name of a unique column in the table. Uses upsert operations to check if a record exists based on the unique column's value. If a matching record exists, the record updates with the values you provide. If a matching record doesn't exist, the upsert operation inserts a new record.<br /><br />When you upsert a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed. + */ + @JsonProperty("upsert") + public Optional getUpsert() { + return upsert; + } + + /** + * @return If true, this operation mandates that all the records have the same fields. This parameter does not work with upsert. + */ + @JsonProperty("homogeneous") + public Optional getHomogeneous() { + return homogeneous; + } + + @JsonProperty("byot") + public Optional getByot() { + return byot; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof RecordServiceInsertRecordBody && equalTo((RecordServiceInsertRecordBody) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(RecordServiceInsertRecordBody other) { + return records.equals(other.records) + && tokenization.equals(other.tokenization) + && upsert.equals(other.upsert) + && homogeneous.equals(other.homogeneous) + && byot.equals(other.byot); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records, this.tokenization, this.upsert, this.homogeneous, this.byot); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> records = Optional.empty(); + + private Optional tokenization = Optional.empty(); + + private Optional upsert = Optional.empty(); + + private Optional homogeneous = Optional.empty(); + + private Optional byot = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(RecordServiceInsertRecordBody other) { + records(other.getRecords()); + tokenization(other.getTokenization()); + upsert(other.getUpsert()); + homogeneous(other.getHomogeneous()); + byot(other.getByot()); + return this; + } + + /** + *

Record values and tokens.

+ */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(Optional> records) { + this.records = records; + return this; + } + + public Builder records(List records) { + this.records = Optional.ofNullable(records); + return this; + } + + /** + *

If true, this operation returns tokens for fields with tokenization enabled.

+ */ + @JsonSetter(value = "tokenization", nulls = Nulls.SKIP) + public Builder tokenization(Optional tokenization) { + this.tokenization = tokenization; + return this; + } + + public Builder tokenization(Boolean tokenization) { + this.tokenization = Optional.ofNullable(tokenization); + return this; + } + + /** + *

Name of a unique column in the table. Uses upsert operations to check if a record exists based on the unique column's value. If a matching record exists, the record updates with the values you provide. If a matching record doesn't exist, the upsert operation inserts a new record.<br /><br />When you upsert a field, include the entire contents you want the field to store. For JSON fields, include all nested fields and values. If a nested field isn't included, it's removed.

+ */ + @JsonSetter(value = "upsert", nulls = Nulls.SKIP) + public Builder upsert(Optional upsert) { + this.upsert = upsert; + return this; + } + + public Builder upsert(String upsert) { + this.upsert = Optional.ofNullable(upsert); + return this; + } + + /** + *

If true, this operation mandates that all the records have the same fields. This parameter does not work with upsert.

+ */ + @JsonSetter(value = "homogeneous", nulls = Nulls.SKIP) + public Builder homogeneous(Optional homogeneous) { + this.homogeneous = homogeneous; + return this; + } + + public Builder homogeneous(Boolean homogeneous) { + this.homogeneous = Optional.ofNullable(homogeneous); + return this; + } + + @JsonSetter(value = "byot", nulls = Nulls.SKIP) + public Builder byot(Optional byot) { + this.byot = byot; + return this; + } + + public Builder byot(V1Byot byot) { + this.byot = Optional.ofNullable(byot); + return this; + } + + public RecordServiceInsertRecordBody build() { + return new RecordServiceInsertRecordBody( + records, tokenization, upsert, homogeneous, byot, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceUpdateRecordBody.java b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceUpdateRecordBody.java new file mode 100644 index 00000000..19e0ae23 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceUpdateRecordBody.java @@ -0,0 +1,151 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.V1Byot; +import com.skyflow.generated.rest.types.V1FieldRecords; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = RecordServiceUpdateRecordBody.Builder.class) +public final class RecordServiceUpdateRecordBody { + private final Optional record; + + private final Optional tokenization; + + private final Optional byot; + + private final Map additionalProperties; + + private RecordServiceUpdateRecordBody( + Optional record, + Optional tokenization, + Optional byot, + Map additionalProperties) { + this.record = record; + this.tokenization = tokenization; + this.byot = byot; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("record") + public Optional getRecord() { + return record; + } + + /** + * @return If true, this operation returns tokens for fields with tokenization enabled. + */ + @JsonProperty("tokenization") + public Optional getTokenization() { + return tokenization; + } + + @JsonProperty("byot") + public Optional getByot() { + return byot; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof RecordServiceUpdateRecordBody && equalTo((RecordServiceUpdateRecordBody) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(RecordServiceUpdateRecordBody other) { + return record.equals(other.record) && tokenization.equals(other.tokenization) && byot.equals(other.byot); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.record, this.tokenization, this.byot); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional record = Optional.empty(); + + private Optional tokenization = Optional.empty(); + + private Optional byot = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(RecordServiceUpdateRecordBody other) { + record(other.getRecord()); + tokenization(other.getTokenization()); + byot(other.getByot()); + return this; + } + + @JsonSetter(value = "record", nulls = Nulls.SKIP) + public Builder record(Optional record) { + this.record = record; + return this; + } + + public Builder record(V1FieldRecords record) { + this.record = Optional.ofNullable(record); + return this; + } + + /** + *

If true, this operation returns tokens for fields with tokenization enabled.

+ */ + @JsonSetter(value = "tokenization", nulls = Nulls.SKIP) + public Builder tokenization(Optional tokenization) { + this.tokenization = tokenization; + return this; + } + + public Builder tokenization(Boolean tokenization) { + this.tokenization = Optional.ofNullable(tokenization); + return this; + } + + @JsonSetter(value = "byot", nulls = Nulls.SKIP) + public Builder byot(Optional byot) { + this.byot = byot; + return this; + } + + public Builder byot(V1Byot byot) { + this.byot = Optional.ofNullable(byot); + return this; + } + + public RecordServiceUpdateRecordBody build() { + return new RecordServiceUpdateRecordBody(record, tokenization, byot, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestOrderBy.java b/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestOrderBy.java new file mode 100644 index 00000000..2563652f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestOrderBy.java @@ -0,0 +1,26 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum RecordServiceBulkGetRecordRequestOrderBy { + ASCENDING("ASCENDING"), + + DESCENDING("DESCENDING"), + + NONE("NONE"); + + private final String value; + + RecordServiceBulkGetRecordRequestOrderBy(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestRedaction.java b/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestRedaction.java new file mode 100644 index 00000000..b20f2541 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceBulkGetRecordRequestRedaction.java @@ -0,0 +1,28 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum RecordServiceBulkGetRecordRequestRedaction { + DEFAULT("DEFAULT"), + + REDACTED("REDACTED"), + + MASKED("MASKED"), + + PLAIN_TEXT("PLAIN_TEXT"); + + private final String value; + + RecordServiceBulkGetRecordRequestRedaction(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceGetRecordRequestRedaction.java b/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceGetRecordRequestRedaction.java new file mode 100644 index 00000000..468e3edd --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/types/RecordServiceGetRecordRequestRedaction.java @@ -0,0 +1,28 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum RecordServiceGetRecordRequestRedaction { + DEFAULT("DEFAULT"), + + REDACTED("REDACTED"), + + MASKED("MASKED"), + + PLAIN_TEXT("PLAIN_TEXT"); + + private final String value; + + RecordServiceGetRecordRequestRedaction(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/strings/AsyncRawStringsClient.java b/src/main/java/com/skyflow/generated/rest/resources/strings/AsyncRawStringsClient.java new file mode 100644 index 00000000..0dc804b2 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/strings/AsyncRawStringsClient.java @@ -0,0 +1,217 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.strings; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.InternalServerError; +import com.skyflow.generated.rest.errors.UnauthorizedError; +import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; +import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; +import com.skyflow.generated.rest.types.DeidentifyStringResponse; +import com.skyflow.generated.rest.types.ErrorResponse; +import com.skyflow.generated.rest.types.ReidentifyStringResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawStringsClient { + protected final ClientOptions clientOptions; + + public AsyncRawStringsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * De-identifies sensitive data from a string. + */ + public CompletableFuture> deidentifyString( + DeidentifyStringRequest request) { + return deidentifyString(request, null); + } + + /** + * De-identifies sensitive data from a string. + */ + public CompletableFuture> deidentifyString( + DeidentifyStringRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/string") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), DeidentifyStringResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Re-identifies tokens in a string. + */ + public CompletableFuture> reidentifyString( + ReidentifyStringRequest request) { + return reidentifyString(request, null); + } + + /** + * Re-identifies tokens in a string. + */ + public CompletableFuture> reidentifyString( + ReidentifyStringRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/reidentify/string") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), ReidentifyStringResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/strings/AsyncStringsClient.java b/src/main/java/com/skyflow/generated/rest/resources/strings/AsyncStringsClient.java new file mode 100644 index 00000000..86e5cd0d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/strings/AsyncStringsClient.java @@ -0,0 +1,60 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.strings; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; +import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; +import com.skyflow.generated.rest.types.DeidentifyStringResponse; +import com.skyflow.generated.rest.types.ReidentifyStringResponse; +import java.util.concurrent.CompletableFuture; + +public class AsyncStringsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawStringsClient rawClient; + + public AsyncStringsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawStringsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawStringsClient withRawResponse() { + return this.rawClient; + } + + /** + * De-identifies sensitive data from a string. + */ + public CompletableFuture deidentifyString(DeidentifyStringRequest request) { + return this.rawClient.deidentifyString(request).thenApply(response -> response.body()); + } + + /** + * De-identifies sensitive data from a string. + */ + public CompletableFuture deidentifyString( + DeidentifyStringRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyString(request, requestOptions).thenApply(response -> response.body()); + } + + /** + * Re-identifies tokens in a string. + */ + public CompletableFuture reidentifyString(ReidentifyStringRequest request) { + return this.rawClient.reidentifyString(request).thenApply(response -> response.body()); + } + + /** + * Re-identifies tokens in a string. + */ + public CompletableFuture reidentifyString( + ReidentifyStringRequest request, RequestOptions requestOptions) { + return this.rawClient.reidentifyString(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/strings/RawStringsClient.java b/src/main/java/com/skyflow/generated/rest/resources/strings/RawStringsClient.java new file mode 100644 index 00000000..0e1fbad0 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/strings/RawStringsClient.java @@ -0,0 +1,171 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.strings; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.InternalServerError; +import com.skyflow.generated.rest.errors.UnauthorizedError; +import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; +import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; +import com.skyflow.generated.rest.types.DeidentifyStringResponse; +import com.skyflow.generated.rest.types.ErrorResponse; +import com.skyflow.generated.rest.types.ReidentifyStringResponse; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawStringsClient { + protected final ClientOptions clientOptions; + + public RawStringsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * De-identifies sensitive data from a string. + */ + public ApiClientHttpResponse deidentifyString(DeidentifyStringRequest request) { + return deidentifyString(request, null); + } + + /** + * De-identifies sensitive data from a string. + */ + public ApiClientHttpResponse deidentifyString( + DeidentifyStringRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/deidentify/string") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), DeidentifyStringResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Re-identifies tokens in a string. + */ + public ApiClientHttpResponse reidentifyString(ReidentifyStringRequest request) { + return reidentifyString(request, null); + } + + /** + * Re-identifies tokens in a string. + */ + public ApiClientHttpResponse reidentifyString( + ReidentifyStringRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/reidentify/string") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ReidentifyStringResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/strings/StringsClient.java b/src/main/java/com/skyflow/generated/rest/resources/strings/StringsClient.java new file mode 100644 index 00000000..153efe07 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/strings/StringsClient.java @@ -0,0 +1,57 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.strings; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; +import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; +import com.skyflow.generated.rest.types.DeidentifyStringResponse; +import com.skyflow.generated.rest.types.ReidentifyStringResponse; + +public class StringsClient { + protected final ClientOptions clientOptions; + + private final RawStringsClient rawClient; + + public StringsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawStringsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawStringsClient withRawResponse() { + return this.rawClient; + } + + /** + * De-identifies sensitive data from a string. + */ + public DeidentifyStringResponse deidentifyString(DeidentifyStringRequest request) { + return this.rawClient.deidentifyString(request).body(); + } + + /** + * De-identifies sensitive data from a string. + */ + public DeidentifyStringResponse deidentifyString(DeidentifyStringRequest request, RequestOptions requestOptions) { + return this.rawClient.deidentifyString(request, requestOptions).body(); + } + + /** + * Re-identifies tokens in a string. + */ + public ReidentifyStringResponse reidentifyString(ReidentifyStringRequest request) { + return this.rawClient.reidentifyString(request).body(); + } + + /** + * Re-identifies tokens in a string. + */ + public ReidentifyStringResponse reidentifyString(ReidentifyStringRequest request, RequestOptions requestOptions) { + return this.rawClient.reidentifyString(request, requestOptions).body(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/strings/requests/DeidentifyStringRequest.java b/src/main/java/com/skyflow/generated/rest/resources/strings/requests/DeidentifyStringRequest.java new file mode 100644 index 00000000..4a74fcba --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/strings/requests/DeidentifyStringRequest.java @@ -0,0 +1,309 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.strings.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.EntityType; +import com.skyflow.generated.rest.types.TokenType; +import com.skyflow.generated.rest.types.Transformations; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyStringRequest.Builder.class) +public final class DeidentifyStringRequest { + private final String vaultId; + + private final String text; + + private final Optional> entityTypes; + + private final Optional tokenType; + + private final Optional> allowRegex; + + private final Optional> restrictRegex; + + private final Optional transformations; + + private final Map additionalProperties; + + private DeidentifyStringRequest( + String vaultId, + String text, + Optional> entityTypes, + Optional tokenType, + Optional> allowRegex, + Optional> restrictRegex, + Optional transformations, + Map additionalProperties) { + this.vaultId = vaultId; + this.text = text; + this.entityTypes = entityTypes; + this.tokenType = tokenType; + this.allowRegex = allowRegex; + this.restrictRegex = restrictRegex; + this.transformations = transformations; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return String to de-identify. + */ + @JsonProperty("text") + public String getText() { + return text; + } + + @JsonProperty("entity_types") + public Optional> getEntityTypes() { + return entityTypes; + } + + @JsonProperty("token_type") + public Optional getTokenType() { + return tokenType; + } + + @JsonProperty("allow_regex") + public Optional> getAllowRegex() { + return allowRegex; + } + + @JsonProperty("restrict_regex") + public Optional> getRestrictRegex() { + return restrictRegex; + } + + @JsonProperty("transformations") + public Optional getTransformations() { + return transformations; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyStringRequest && equalTo((DeidentifyStringRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyStringRequest other) { + return vaultId.equals(other.vaultId) + && text.equals(other.text) + && entityTypes.equals(other.entityTypes) + && tokenType.equals(other.tokenType) + && allowRegex.equals(other.allowRegex) + && restrictRegex.equals(other.restrictRegex) + && transformations.equals(other.transformations); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.vaultId, + this.text, + this.entityTypes, + this.tokenType, + this.allowRegex, + this.restrictRegex, + this.transformations); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + TextStage vaultId(@NotNull String vaultId); + + Builder from(DeidentifyStringRequest other); + } + + public interface TextStage { + /** + * String to de-identify. + */ + _FinalStage text(@NotNull String text); + } + + public interface _FinalStage { + DeidentifyStringRequest build(); + + _FinalStage entityTypes(Optional> entityTypes); + + _FinalStage entityTypes(List entityTypes); + + _FinalStage tokenType(Optional tokenType); + + _FinalStage tokenType(TokenType tokenType); + + _FinalStage allowRegex(Optional> allowRegex); + + _FinalStage allowRegex(List allowRegex); + + _FinalStage restrictRegex(Optional> restrictRegex); + + _FinalStage restrictRegex(List restrictRegex); + + _FinalStage transformations(Optional transformations); + + _FinalStage transformations(Transformations transformations); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, TextStage, _FinalStage { + private String vaultId; + + private String text; + + private Optional transformations = Optional.empty(); + + private Optional> restrictRegex = Optional.empty(); + + private Optional> allowRegex = Optional.empty(); + + private Optional tokenType = Optional.empty(); + + private Optional> entityTypes = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyStringRequest other) { + vaultId(other.getVaultId()); + text(other.getText()); + entityTypes(other.getEntityTypes()); + tokenType(other.getTokenType()); + allowRegex(other.getAllowRegex()); + restrictRegex(other.getRestrictRegex()); + transformations(other.getTransformations()); + return this; + } + + @java.lang.Override + @JsonSetter("vault_id") + public TextStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + * String to de-identify.

String to de-identify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("text") + public _FinalStage text(@NotNull String text) { + this.text = Objects.requireNonNull(text, "text must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage transformations(Transformations transformations) { + this.transformations = Optional.ofNullable(transformations); + return this; + } + + @java.lang.Override + @JsonSetter(value = "transformations", nulls = Nulls.SKIP) + public _FinalStage transformations(Optional transformations) { + this.transformations = transformations; + return this; + } + + @java.lang.Override + public _FinalStage restrictRegex(List restrictRegex) { + this.restrictRegex = Optional.ofNullable(restrictRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) + public _FinalStage restrictRegex(Optional> restrictRegex) { + this.restrictRegex = restrictRegex; + return this; + } + + @java.lang.Override + public _FinalStage allowRegex(List allowRegex) { + this.allowRegex = Optional.ofNullable(allowRegex); + return this; + } + + @java.lang.Override + @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) + public _FinalStage allowRegex(Optional> allowRegex) { + this.allowRegex = allowRegex; + return this; + } + + @java.lang.Override + public _FinalStage tokenType(TokenType tokenType) { + this.tokenType = Optional.ofNullable(tokenType); + return this; + } + + @java.lang.Override + @JsonSetter(value = "token_type", nulls = Nulls.SKIP) + public _FinalStage tokenType(Optional tokenType) { + this.tokenType = tokenType; + return this; + } + + @java.lang.Override + public _FinalStage entityTypes(List entityTypes) { + this.entityTypes = Optional.ofNullable(entityTypes); + return this; + } + + @java.lang.Override + @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) + public _FinalStage entityTypes(Optional> entityTypes) { + this.entityTypes = entityTypes; + return this; + } + + @java.lang.Override + public DeidentifyStringRequest build() { + return new DeidentifyStringRequest( + vaultId, + text, + entityTypes, + tokenType, + allowRegex, + restrictRegex, + transformations, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/strings/requests/ReidentifyStringRequest.java b/src/main/java/com/skyflow/generated/rest/resources/strings/requests/ReidentifyStringRequest.java new file mode 100644 index 00000000..e61cb5a2 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/strings/requests/ReidentifyStringRequest.java @@ -0,0 +1,192 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.strings.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.strings.types.ReidentifyStringRequestFormat; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyStringRequest.Builder.class) +public final class ReidentifyStringRequest { + private final String text; + + private final String vaultId; + + private final Optional format; + + private final Map additionalProperties; + + private ReidentifyStringRequest( + String text, + String vaultId, + Optional format, + Map additionalProperties) { + this.text = text; + this.vaultId = vaultId; + this.format = format; + this.additionalProperties = additionalProperties; + } + + /** + * @return String to re-identify. + */ + @JsonProperty("text") + public String getText() { + return text; + } + + /** + * @return ID of the vault where the entities are stored. + */ + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return Mapping of perferred data formatting options to entity types. Returned values are dependent on the configuration of the vault storing the data and the permissions of the user or account making the request. + */ + @JsonProperty("format") + public Optional getFormat() { + return format; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyStringRequest && equalTo((ReidentifyStringRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyStringRequest other) { + return text.equals(other.text) && vaultId.equals(other.vaultId) && format.equals(other.format); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.text, this.vaultId, this.format); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TextStage builder() { + return new Builder(); + } + + public interface TextStage { + /** + * String to re-identify. + */ + VaultIdStage text(@NotNull String text); + + Builder from(ReidentifyStringRequest other); + } + + public interface VaultIdStage { + /** + * ID of the vault where the entities are stored. + */ + _FinalStage vaultId(@NotNull String vaultId); + } + + public interface _FinalStage { + ReidentifyStringRequest build(); + + /** + *

Mapping of perferred data formatting options to entity types. Returned values are dependent on the configuration of the vault storing the data and the permissions of the user or account making the request.

+ */ + _FinalStage format(Optional format); + + _FinalStage format(ReidentifyStringRequestFormat format); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TextStage, VaultIdStage, _FinalStage { + private String text; + + private String vaultId; + + private Optional format = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ReidentifyStringRequest other) { + text(other.getText()); + vaultId(other.getVaultId()); + format(other.getFormat()); + return this; + } + + /** + * String to re-identify.

String to re-identify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("text") + public VaultIdStage text(@NotNull String text) { + this.text = Objects.requireNonNull(text, "text must not be null"); + return this; + } + + /** + * ID of the vault where the entities are stored.

ID of the vault where the entities are stored.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("vault_id") + public _FinalStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + *

Mapping of perferred data formatting options to entity types. Returned values are dependent on the configuration of the vault storing the data and the permissions of the user or account making the request.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage format(ReidentifyStringRequestFormat format) { + this.format = Optional.ofNullable(format); + return this; + } + + /** + *

Mapping of perferred data formatting options to entity types. Returned values are dependent on the configuration of the vault storing the data and the permissions of the user or account making the request.

+ */ + @java.lang.Override + @JsonSetter(value = "format", nulls = Nulls.SKIP) + public _FinalStage format(Optional format) { + this.format = format; + return this; + } + + @java.lang.Override + public ReidentifyStringRequest build() { + return new ReidentifyStringRequest(text, vaultId, format, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/strings/types/ReidentifyStringRequestFormat.java b/src/main/java/com/skyflow/generated/rest/resources/strings/types/ReidentifyStringRequestFormat.java new file mode 100644 index 00000000..68c5209f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/strings/types/ReidentifyStringRequestFormat.java @@ -0,0 +1,163 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.strings.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.EntityType; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyStringRequestFormat.Builder.class) +public final class ReidentifyStringRequestFormat { + private final Optional> redacted; + + private final Optional> masked; + + private final Optional> plaintext; + + private final Map additionalProperties; + + private ReidentifyStringRequestFormat( + Optional> redacted, + Optional> masked, + Optional> plaintext, + Map additionalProperties) { + this.redacted = redacted; + this.masked = masked; + this.plaintext = plaintext; + this.additionalProperties = additionalProperties; + } + + /** + * @return Entity types to fully redact. + */ + @JsonProperty("redacted") + public Optional> getRedacted() { + return redacted; + } + + /** + * @return Entity types to mask. + */ + @JsonProperty("masked") + public Optional> getMasked() { + return masked; + } + + /** + * @return Entity types to return in plaintext. + */ + @JsonProperty("plaintext") + public Optional> getPlaintext() { + return plaintext; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyStringRequestFormat && equalTo((ReidentifyStringRequestFormat) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyStringRequestFormat other) { + return redacted.equals(other.redacted) && masked.equals(other.masked) && plaintext.equals(other.plaintext); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.redacted, this.masked, this.plaintext); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> redacted = Optional.empty(); + + private Optional> masked = Optional.empty(); + + private Optional> plaintext = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(ReidentifyStringRequestFormat other) { + redacted(other.getRedacted()); + masked(other.getMasked()); + plaintext(other.getPlaintext()); + return this; + } + + /** + *

Entity types to fully redact.

+ */ + @JsonSetter(value = "redacted", nulls = Nulls.SKIP) + public Builder redacted(Optional> redacted) { + this.redacted = redacted; + return this; + } + + public Builder redacted(List redacted) { + this.redacted = Optional.ofNullable(redacted); + return this; + } + + /** + *

Entity types to mask.

+ */ + @JsonSetter(value = "masked", nulls = Nulls.SKIP) + public Builder masked(Optional> masked) { + this.masked = masked; + return this; + } + + public Builder masked(List masked) { + this.masked = Optional.ofNullable(masked); + return this; + } + + /** + *

Entity types to return in plaintext.

+ */ + @JsonSetter(value = "plaintext", nulls = Nulls.SKIP) + public Builder plaintext(Optional> plaintext) { + this.plaintext = plaintext; + return this; + } + + public Builder plaintext(List plaintext) { + this.plaintext = Optional.ofNullable(plaintext); + return this; + } + + public ReidentifyStringRequestFormat build() { + return new ReidentifyStringRequestFormat(redacted, masked, plaintext, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncRawTokensClient.java b/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncRawTokensClient.java new file mode 100644 index 00000000..fbf69580 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncRawTokensClient.java @@ -0,0 +1,206 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.tokens; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; +import com.skyflow.generated.rest.types.V1DetokenizeResponse; +import com.skyflow.generated.rest.types.V1TokenizeResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawTokensClient { + protected final ClientOptions clientOptions; + + public AsyncRawTokensClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Returns records that correspond to the specified tokens. + */ + public CompletableFuture> recordServiceDetokenize(String vaultId) { + return recordServiceDetokenize(vaultId, V1DetokenizePayload.builder().build()); + } + + /** + * Returns records that correspond to the specified tokens. + */ + public CompletableFuture> recordServiceDetokenize( + String vaultId, V1DetokenizePayload request) { + return recordServiceDetokenize(vaultId, request, null); + } + + /** + * Returns records that correspond to the specified tokens. + */ + public CompletableFuture> recordServiceDetokenize( + String vaultId, V1DetokenizePayload request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegments("detokenize") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetokenizeResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } + + /** + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + */ + public CompletableFuture> recordServiceTokenize(String vaultId) { + return recordServiceTokenize(vaultId, V1TokenizePayload.builder().build()); + } + + /** + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + */ + public CompletableFuture> recordServiceTokenize( + String vaultId, V1TokenizePayload request) { + return recordServiceTokenize(vaultId, request, null); + } + + /** + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + */ + public CompletableFuture> recordServiceTokenize( + String vaultId, V1TokenizePayload request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegments("tokenize") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1TokenizeResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncTokensClient.java b/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncTokensClient.java new file mode 100644 index 00000000..26d5ea05 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/tokens/AsyncTokensClient.java @@ -0,0 +1,79 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.tokens; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; +import com.skyflow.generated.rest.types.V1DetokenizeResponse; +import com.skyflow.generated.rest.types.V1TokenizeResponse; +import java.util.concurrent.CompletableFuture; + +public class AsyncTokensClient { + protected final ClientOptions clientOptions; + + private final AsyncRawTokensClient rawClient; + + public AsyncTokensClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawTokensClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawTokensClient withRawResponse() { + return this.rawClient; + } + + /** + * Returns records that correspond to the specified tokens. + */ + public CompletableFuture recordServiceDetokenize(String vaultId) { + return this.rawClient.recordServiceDetokenize(vaultId).thenApply(response -> response.body()); + } + + /** + * Returns records that correspond to the specified tokens. + */ + public CompletableFuture recordServiceDetokenize( + String vaultId, V1DetokenizePayload request) { + return this.rawClient.recordServiceDetokenize(vaultId, request).thenApply(response -> response.body()); + } + + /** + * Returns records that correspond to the specified tokens. + */ + public CompletableFuture recordServiceDetokenize( + String vaultId, V1DetokenizePayload request, RequestOptions requestOptions) { + return this.rawClient + .recordServiceDetokenize(vaultId, request, requestOptions) + .thenApply(response -> response.body()); + } + + /** + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + */ + public CompletableFuture recordServiceTokenize(String vaultId) { + return this.rawClient.recordServiceTokenize(vaultId).thenApply(response -> response.body()); + } + + /** + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + */ + public CompletableFuture recordServiceTokenize(String vaultId, V1TokenizePayload request) { + return this.rawClient.recordServiceTokenize(vaultId, request).thenApply(response -> response.body()); + } + + /** + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + */ + public CompletableFuture recordServiceTokenize( + String vaultId, V1TokenizePayload request, RequestOptions requestOptions) { + return this.rawClient + .recordServiceTokenize(vaultId, request, requestOptions) + .thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/tokens/RawTokensClient.java b/src/main/java/com/skyflow/generated/rest/resources/tokens/RawTokensClient.java new file mode 100644 index 00000000..5ed17d28 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/tokens/RawTokensClient.java @@ -0,0 +1,172 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.tokens; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; +import com.skyflow.generated.rest.types.V1DetokenizeResponse; +import com.skyflow.generated.rest.types.V1TokenizeResponse; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawTokensClient { + protected final ClientOptions clientOptions; + + public RawTokensClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Returns records that correspond to the specified tokens. + */ + public ApiClientHttpResponse recordServiceDetokenize(String vaultId) { + return recordServiceDetokenize(vaultId, V1DetokenizePayload.builder().build()); + } + + /** + * Returns records that correspond to the specified tokens. + */ + public ApiClientHttpResponse recordServiceDetokenize( + String vaultId, V1DetokenizePayload request) { + return recordServiceDetokenize(vaultId, request, null); + } + + /** + * Returns records that correspond to the specified tokens. + */ + public ApiClientHttpResponse recordServiceDetokenize( + String vaultId, V1DetokenizePayload request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegments("detokenize") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetokenizeResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } + + /** + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + */ + public ApiClientHttpResponse recordServiceTokenize(String vaultId) { + return recordServiceTokenize(vaultId, V1TokenizePayload.builder().build()); + } + + /** + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + */ + public ApiClientHttpResponse recordServiceTokenize(String vaultId, V1TokenizePayload request) { + return recordServiceTokenize(vaultId, request, null); + } + + /** + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + */ + public ApiClientHttpResponse recordServiceTokenize( + String vaultId, V1TokenizePayload request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/vaults") + .addPathSegment(vaultId) + .addPathSegments("tokenize") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1TokenizeResponse.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/tokens/TokensClient.java b/src/main/java/com/skyflow/generated/rest/resources/tokens/TokensClient.java new file mode 100644 index 00000000..8b0e7e40 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/tokens/TokensClient.java @@ -0,0 +1,77 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.tokens; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; +import com.skyflow.generated.rest.types.V1DetokenizeResponse; +import com.skyflow.generated.rest.types.V1TokenizeResponse; + +public class TokensClient { + protected final ClientOptions clientOptions; + + private final RawTokensClient rawClient; + + public TokensClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawTokensClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawTokensClient withRawResponse() { + return this.rawClient; + } + + /** + * Returns records that correspond to the specified tokens. + */ + public V1DetokenizeResponse recordServiceDetokenize(String vaultId) { + return this.rawClient.recordServiceDetokenize(vaultId).body(); + } + + /** + * Returns records that correspond to the specified tokens. + */ + public V1DetokenizeResponse recordServiceDetokenize(String vaultId, V1DetokenizePayload request) { + return this.rawClient.recordServiceDetokenize(vaultId, request).body(); + } + + /** + * Returns records that correspond to the specified tokens. + */ + public V1DetokenizeResponse recordServiceDetokenize( + String vaultId, V1DetokenizePayload request, RequestOptions requestOptions) { + return this.rawClient + .recordServiceDetokenize(vaultId, request, requestOptions) + .body(); + } + + /** + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + */ + public V1TokenizeResponse recordServiceTokenize(String vaultId) { + return this.rawClient.recordServiceTokenize(vaultId).body(); + } + + /** + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + */ + public V1TokenizeResponse recordServiceTokenize(String vaultId, V1TokenizePayload request) { + return this.rawClient.recordServiceTokenize(vaultId, request).body(); + } + + /** + * Returns tokens that correspond to the specified records. Only applicable for fields with deterministic tokenization.<br /><br /><b>Note:</b> This endpoint doesn't insert records—it returns tokens for existing values. To insert records and tokenize that new record's values, see <a href='#RecordService_InsertRecord'>Insert Record</a> and the tokenization parameter. + */ + public V1TokenizeResponse recordServiceTokenize( + String vaultId, V1TokenizePayload request, RequestOptions requestOptions) { + return this.rawClient + .recordServiceTokenize(vaultId, request, requestOptions) + .body(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/V1DetokenizePayload.java b/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/V1DetokenizePayload.java new file mode 100644 index 00000000..1d3cb407 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/V1DetokenizePayload.java @@ -0,0 +1,166 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.tokens.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.V1DetokenizeRecordRequest; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1DetokenizePayload.Builder.class) +public final class V1DetokenizePayload { + private final Optional> detokenizationParameters; + + private final Optional downloadUrl; + + private final Optional continueOnError; + + private final Map additionalProperties; + + private V1DetokenizePayload( + Optional> detokenizationParameters, + Optional downloadUrl, + Optional continueOnError, + Map additionalProperties) { + this.detokenizationParameters = detokenizationParameters; + this.downloadUrl = downloadUrl; + this.continueOnError = continueOnError; + this.additionalProperties = additionalProperties; + } + + /** + * @return Detokenization details. + */ + @JsonProperty("detokenizationParameters") + public Optional> getDetokenizationParameters() { + return detokenizationParameters; + } + + /** + * @return If true, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + */ + @JsonProperty("downloadURL") + public Optional getDownloadUrl() { + return downloadUrl; + } + + /** + * @return If true, the detokenization request continues even if an error occurs. + */ + @JsonProperty("continueOnError") + public Optional getContinueOnError() { + return continueOnError; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1DetokenizePayload && equalTo((V1DetokenizePayload) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1DetokenizePayload other) { + return detokenizationParameters.equals(other.detokenizationParameters) + && downloadUrl.equals(other.downloadUrl) + && continueOnError.equals(other.continueOnError); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.detokenizationParameters, this.downloadUrl, this.continueOnError); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> detokenizationParameters = Optional.empty(); + + private Optional downloadUrl = Optional.empty(); + + private Optional continueOnError = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1DetokenizePayload other) { + detokenizationParameters(other.getDetokenizationParameters()); + downloadUrl(other.getDownloadUrl()); + continueOnError(other.getContinueOnError()); + return this; + } + + /** + *

Detokenization details.

+ */ + @JsonSetter(value = "detokenizationParameters", nulls = Nulls.SKIP) + public Builder detokenizationParameters(Optional> detokenizationParameters) { + this.detokenizationParameters = detokenizationParameters; + return this; + } + + public Builder detokenizationParameters(List detokenizationParameters) { + this.detokenizationParameters = Optional.ofNullable(detokenizationParameters); + return this; + } + + /** + *

If true, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean.

+ */ + @JsonSetter(value = "downloadURL", nulls = Nulls.SKIP) + public Builder downloadUrl(Optional downloadUrl) { + this.downloadUrl = downloadUrl; + return this; + } + + public Builder downloadUrl(Boolean downloadUrl) { + this.downloadUrl = Optional.ofNullable(downloadUrl); + return this; + } + + /** + *

If true, the detokenization request continues even if an error occurs.

+ */ + @JsonSetter(value = "continueOnError", nulls = Nulls.SKIP) + public Builder continueOnError(Optional continueOnError) { + this.continueOnError = continueOnError; + return this; + } + + public Builder continueOnError(Boolean continueOnError) { + this.continueOnError = Optional.ofNullable(continueOnError); + return this; + } + + public V1DetokenizePayload build() { + return new V1DetokenizePayload( + detokenizationParameters, downloadUrl, continueOnError, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/V1TokenizePayload.java b/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/V1TokenizePayload.java new file mode 100644 index 00000000..30bdde6a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/tokens/requests/V1TokenizePayload.java @@ -0,0 +1,104 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.tokens.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.V1TokenizeRecordRequest; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1TokenizePayload.Builder.class) +public final class V1TokenizePayload { + private final Optional> tokenizationParameters; + + private final Map additionalProperties; + + private V1TokenizePayload( + Optional> tokenizationParameters, Map additionalProperties) { + this.tokenizationParameters = tokenizationParameters; + this.additionalProperties = additionalProperties; + } + + /** + * @return Tokenization details. + */ + @JsonProperty("tokenizationParameters") + public Optional> getTokenizationParameters() { + return tokenizationParameters; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1TokenizePayload && equalTo((V1TokenizePayload) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1TokenizePayload other) { + return tokenizationParameters.equals(other.tokenizationParameters); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.tokenizationParameters); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> tokenizationParameters = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1TokenizePayload other) { + tokenizationParameters(other.getTokenizationParameters()); + return this; + } + + /** + *

Tokenization details.

+ */ + @JsonSetter(value = "tokenizationParameters", nulls = Nulls.SKIP) + public Builder tokenizationParameters(Optional> tokenizationParameters) { + this.tokenizationParameters = tokenizationParameters; + return this; + } + + public Builder tokenizationParameters(List tokenizationParameters) { + this.tokenizationParameters = Optional.ofNullable(tokenizationParameters); + return this; + } + + public V1TokenizePayload build() { + return new V1TokenizePayload(tokenizationParameters, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsColumnMapping.java b/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsColumnMapping.java new file mode 100644 index 00000000..0f5d1fc2 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsColumnMapping.java @@ -0,0 +1,194 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = AdvancedOptionsColumnMapping.Builder.class) +public final class AdvancedOptionsColumnMapping { + private final String sessionId; + + private final String default_; + + private final Optional> entityColumnMap; + + private final Map additionalProperties; + + private AdvancedOptionsColumnMapping( + String sessionId, + String default_, + Optional> entityColumnMap, + Map additionalProperties) { + this.sessionId = sessionId; + this.default_ = default_; + this.entityColumnMap = entityColumnMap; + this.additionalProperties = additionalProperties; + } + + /** + * @return Table name of the vault. + */ + @JsonProperty("session_id") + public String getSessionId() { + return sessionId; + } + + /** + * @return Name of column to store data in when no explicit mapping exists. + */ + @JsonProperty("default") + public String getDefault() { + return default_; + } + + /** + * @return Column mapping for different entities. + */ + @JsonProperty("entity_column_map") + public Optional> getEntityColumnMap() { + return entityColumnMap; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof AdvancedOptionsColumnMapping && equalTo((AdvancedOptionsColumnMapping) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(AdvancedOptionsColumnMapping other) { + return sessionId.equals(other.sessionId) + && default_.equals(other.default_) + && entityColumnMap.equals(other.entityColumnMap); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.sessionId, this.default_, this.entityColumnMap); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static SessionIdStage builder() { + return new Builder(); + } + + public interface SessionIdStage { + /** + * Table name of the vault. + */ + DefaultStage sessionId(@NotNull String sessionId); + + Builder from(AdvancedOptionsColumnMapping other); + } + + public interface DefaultStage { + /** + * Name of column to store data in when no explicit mapping exists. + */ + _FinalStage default_(@NotNull String default_); + } + + public interface _FinalStage { + AdvancedOptionsColumnMapping build(); + + /** + *

Column mapping for different entities.

+ */ + _FinalStage entityColumnMap(Optional> entityColumnMap); + + _FinalStage entityColumnMap(List entityColumnMap); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements SessionIdStage, DefaultStage, _FinalStage { + private String sessionId; + + private String default_; + + private Optional> entityColumnMap = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(AdvancedOptionsColumnMapping other) { + sessionId(other.getSessionId()); + default_(other.getDefault()); + entityColumnMap(other.getEntityColumnMap()); + return this; + } + + /** + * Table name of the vault.

Table name of the vault.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("session_id") + public DefaultStage sessionId(@NotNull String sessionId) { + this.sessionId = Objects.requireNonNull(sessionId, "sessionId must not be null"); + return this; + } + + /** + * Name of column to store data in when no explicit mapping exists.

Name of column to store data in when no explicit mapping exists.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("default") + public _FinalStage default_(@NotNull String default_) { + this.default_ = Objects.requireNonNull(default_, "default_ must not be null"); + return this; + } + + /** + *

Column mapping for different entities.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage entityColumnMap(List entityColumnMap) { + this.entityColumnMap = Optional.ofNullable(entityColumnMap); + return this; + } + + /** + *

Column mapping for different entities.

+ */ + @java.lang.Override + @JsonSetter(value = "entity_column_map", nulls = Nulls.SKIP) + public _FinalStage entityColumnMap(Optional> entityColumnMap) { + this.entityColumnMap = entityColumnMap; + return this; + } + + @java.lang.Override + public AdvancedOptionsColumnMapping build() { + return new AdvancedOptionsColumnMapping(sessionId, default_, entityColumnMap, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsEntityColumnMap.java b/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsEntityColumnMap.java new file mode 100644 index 00000000..3df03da3 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsEntityColumnMap.java @@ -0,0 +1,126 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = AdvancedOptionsEntityColumnMap.Builder.class) +public final class AdvancedOptionsEntityColumnMap { + private final Optional entityType; + + private final Optional columnName; + + private final Map additionalProperties; + + private AdvancedOptionsEntityColumnMap( + Optional entityType, + Optional columnName, + Map additionalProperties) { + this.entityType = entityType; + this.columnName = columnName; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("entity_type") + public Optional getEntityType() { + return entityType; + } + + /** + * @return Column name where the entity has to be stored. + */ + @JsonProperty("column_name") + public Optional getColumnName() { + return columnName; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof AdvancedOptionsEntityColumnMap && equalTo((AdvancedOptionsEntityColumnMap) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(AdvancedOptionsEntityColumnMap other) { + return entityType.equals(other.entityType) && columnName.equals(other.columnName); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.entityType, this.columnName); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional entityType = Optional.empty(); + + private Optional columnName = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(AdvancedOptionsEntityColumnMap other) { + entityType(other.getEntityType()); + columnName(other.getColumnName()); + return this; + } + + @JsonSetter(value = "entity_type", nulls = Nulls.SKIP) + public Builder entityType(Optional entityType) { + this.entityType = entityType; + return this; + } + + public Builder entityType(DetectDataEntities entityType) { + this.entityType = Optional.ofNullable(entityType); + return this; + } + + /** + *

Column name where the entity has to be stored.

+ */ + @JsonSetter(value = "column_name", nulls = Nulls.SKIP) + public Builder columnName(Optional columnName) { + this.columnName = columnName; + return this; + } + + public Builder columnName(String columnName) { + this.columnName = Optional.ofNullable(columnName); + return this; + } + + public AdvancedOptionsEntityColumnMap build() { + return new AdvancedOptionsEntityColumnMap(entityType, columnName, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsVaultSchema.java b/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsVaultSchema.java new file mode 100644 index 00000000..dcacb09f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsVaultSchema.java @@ -0,0 +1,135 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = AdvancedOptionsVaultSchema.Builder.class) +public final class AdvancedOptionsVaultSchema { + private final String tableName; + + private final AdvancedOptionsColumnMapping mapping; + + private final Map additionalProperties; + + private AdvancedOptionsVaultSchema( + String tableName, AdvancedOptionsColumnMapping mapping, Map additionalProperties) { + this.tableName = tableName; + this.mapping = mapping; + this.additionalProperties = additionalProperties; + } + + /** + * @return Table name of the vault. + */ + @JsonProperty("table_name") + public String getTableName() { + return tableName; + } + + @JsonProperty("mapping") + public AdvancedOptionsColumnMapping getMapping() { + return mapping; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof AdvancedOptionsVaultSchema && equalTo((AdvancedOptionsVaultSchema) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(AdvancedOptionsVaultSchema other) { + return tableName.equals(other.tableName) && mapping.equals(other.mapping); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.tableName, this.mapping); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TableNameStage builder() { + return new Builder(); + } + + public interface TableNameStage { + /** + * Table name of the vault. + */ + MappingStage tableName(@NotNull String tableName); + + Builder from(AdvancedOptionsVaultSchema other); + } + + public interface MappingStage { + _FinalStage mapping(@NotNull AdvancedOptionsColumnMapping mapping); + } + + public interface _FinalStage { + AdvancedOptionsVaultSchema build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TableNameStage, MappingStage, _FinalStage { + private String tableName; + + private AdvancedOptionsColumnMapping mapping; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(AdvancedOptionsVaultSchema other) { + tableName(other.getTableName()); + mapping(other.getMapping()); + return this; + } + + /** + * Table name of the vault.

Table name of the vault.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("table_name") + public MappingStage tableName(@NotNull String tableName) { + this.tableName = Objects.requireNonNull(tableName, "tableName must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("mapping") + public _FinalStage mapping(@NotNull AdvancedOptionsColumnMapping mapping) { + this.mapping = Objects.requireNonNull(mapping, "mapping must not be null"); + return this; + } + + @java.lang.Override + public AdvancedOptionsVaultSchema build() { + return new AdvancedOptionsVaultSchema(tableName, mapping, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/AudioConfigTranscriptionType.java b/src/main/java/com/skyflow/generated/rest/types/AudioConfigTranscriptionType.java new file mode 100644 index 00000000..e9052d16 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/AudioConfigTranscriptionType.java @@ -0,0 +1,40 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum AudioConfigTranscriptionType { + NONE("none"), + + SKYFLOW_TRANSCRIPTION("skyflow_transcription"), + + AWS_TRANSCRIPTION("aws_transcription"), + + AWS_TRANSCRIPTION_DIARIZE("aws_transcription_diarize"), + + AWS_MEDICAL_TRANSCRIPTION("aws_medical_transcription"), + + AWS_MEDICAL_TRANSCRIPTION_DIARIZE("aws_medical_transcription_diarize"), + + AWS_TRANSCRIPTION_DIARIZE_JSON("aws_transcription_diarize_json"), + + DEEPGRAM_TRANSCRIPTION_DIARIZE("deepgram_transcription_diarize"), + + DEEPGRAM_TRANSCRIPTION_JSON("deepgram_transcription_json"), + + DEEPGRAM_WRAPPER("deepgram_wrapper"); + + private final String value; + + AudioConfigTranscriptionType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/AuditEventAuditResourceType.java b/src/main/java/com/skyflow/generated/rest/types/AuditEventAuditResourceType.java new file mode 100644 index 00000000..4264996a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/AuditEventAuditResourceType.java @@ -0,0 +1,80 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum AuditEventAuditResourceType { + NONE_API("NONE_API"), + + ACCOUNT("ACCOUNT"), + + AUDIT("AUDIT"), + + BASE_DATA_TYPE("BASE_DATA_TYPE"), + + FIELD_TEMPLATE("FIELD_TEMPLATE"), + + FILE("FILE"), + + KEY("KEY"), + + POLICY("POLICY"), + + PROTO_PARSE("PROTO_PARSE"), + + RECORD("RECORD"), + + ROLE("ROLE"), + + RULE("RULE"), + + SECRET("SECRET"), + + SERVICE_ACCOUNT("SERVICE_ACCOUNT"), + + TOKEN("TOKEN"), + + USER("USER"), + + VAULT("VAULT"), + + VAULT_TEMPLATE("VAULT_TEMPLATE"), + + WORKSPACE("WORKSPACE"), + + TABLE("TABLE"), + + POLICY_TEMPLATE("POLICY_TEMPLATE"), + + MEMBER("MEMBER"), + + TAG("TAG"), + + CONNECTION("CONNECTION"), + + MIGRATION("MIGRATION"), + + SCHEDULED_JOB("SCHEDULED_JOB"), + + JOB("JOB"), + + COLUMN_NAME("COLUMN_NAME"), + + NETWORK_TOKEN("NETWORK_TOKEN"), + + SUBSCRIPTION("SUBSCRIPTION"); + + private final String value; + + AuditEventAuditResourceType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/AuditEventContext.java b/src/main/java/com/skyflow/generated/rest/types/AuditEventContext.java new file mode 100644 index 00000000..2a5c104a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/AuditEventContext.java @@ -0,0 +1,440 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = AuditEventContext.Builder.class) +public final class AuditEventContext { + private final Optional changeId; + + private final Optional requestId; + + private final Optional traceId; + + private final Optional sessionId; + + private final Optional actor; + + private final Optional actorType; + + private final Optional accessType; + + private final Optional ipAddress; + + private final Optional origin; + + private final Optional authMode; + + private final Optional jwtId; + + private final Optional bearerTokenContextId; + + private final Map additionalProperties; + + private AuditEventContext( + Optional changeId, + Optional requestId, + Optional traceId, + Optional sessionId, + Optional actor, + Optional actorType, + Optional accessType, + Optional ipAddress, + Optional origin, + Optional authMode, + Optional jwtId, + Optional bearerTokenContextId, + Map additionalProperties) { + this.changeId = changeId; + this.requestId = requestId; + this.traceId = traceId; + this.sessionId = sessionId; + this.actor = actor; + this.actorType = actorType; + this.accessType = accessType; + this.ipAddress = ipAddress; + this.origin = origin; + this.authMode = authMode; + this.jwtId = jwtId; + this.bearerTokenContextId = bearerTokenContextId; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID for the audit event. + */ + @JsonProperty("changeID") + public Optional getChangeId() { + return changeId; + } + + /** + * @return ID for the request that caused the event. + */ + @JsonProperty("requestID") + public Optional getRequestId() { + return requestId; + } + + /** + * @return ID for the request set by the service that received the request. + */ + @JsonProperty("traceID") + public Optional getTraceId() { + return traceId; + } + + /** + * @return ID for the session in which the request was sent. + */ + @JsonProperty("sessionID") + public Optional getSessionId() { + return sessionId; + } + + /** + * @return Member who sent the request. Depending on actorType, this may be a user ID or a service account ID. + */ + @JsonProperty("actor") + public Optional getActor() { + return actor; + } + + @JsonProperty("actorType") + public Optional getActorType() { + return actorType; + } + + @JsonProperty("accessType") + public Optional getAccessType() { + return accessType; + } + + /** + * @return IP Address of the client that made the request. + */ + @JsonProperty("ipAddress") + public Optional getIpAddress() { + return ipAddress; + } + + /** + * @return HTTP Origin request header (including scheme, hostname, and port) of the request. + */ + @JsonProperty("origin") + public Optional getOrigin() { + return origin; + } + + @JsonProperty("authMode") + public Optional getAuthMode() { + return authMode; + } + + /** + * @return ID of the JWT token. + */ + @JsonProperty("jwtID") + public Optional getJwtId() { + return jwtId; + } + + /** + * @return Embedded User Context. + */ + @JsonProperty("bearerTokenContextID") + public Optional getBearerTokenContextId() { + return bearerTokenContextId; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof AuditEventContext && equalTo((AuditEventContext) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(AuditEventContext other) { + return changeId.equals(other.changeId) + && requestId.equals(other.requestId) + && traceId.equals(other.traceId) + && sessionId.equals(other.sessionId) + && actor.equals(other.actor) + && actorType.equals(other.actorType) + && accessType.equals(other.accessType) + && ipAddress.equals(other.ipAddress) + && origin.equals(other.origin) + && authMode.equals(other.authMode) + && jwtId.equals(other.jwtId) + && bearerTokenContextId.equals(other.bearerTokenContextId); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.changeId, + this.requestId, + this.traceId, + this.sessionId, + this.actor, + this.actorType, + this.accessType, + this.ipAddress, + this.origin, + this.authMode, + this.jwtId, + this.bearerTokenContextId); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional changeId = Optional.empty(); + + private Optional requestId = Optional.empty(); + + private Optional traceId = Optional.empty(); + + private Optional sessionId = Optional.empty(); + + private Optional actor = Optional.empty(); + + private Optional actorType = Optional.empty(); + + private Optional accessType = Optional.empty(); + + private Optional ipAddress = Optional.empty(); + + private Optional origin = Optional.empty(); + + private Optional authMode = Optional.empty(); + + private Optional jwtId = Optional.empty(); + + private Optional bearerTokenContextId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(AuditEventContext other) { + changeId(other.getChangeId()); + requestId(other.getRequestId()); + traceId(other.getTraceId()); + sessionId(other.getSessionId()); + actor(other.getActor()); + actorType(other.getActorType()); + accessType(other.getAccessType()); + ipAddress(other.getIpAddress()); + origin(other.getOrigin()); + authMode(other.getAuthMode()); + jwtId(other.getJwtId()); + bearerTokenContextId(other.getBearerTokenContextId()); + return this; + } + + /** + *

ID for the audit event.

+ */ + @JsonSetter(value = "changeID", nulls = Nulls.SKIP) + public Builder changeId(Optional changeId) { + this.changeId = changeId; + return this; + } + + public Builder changeId(String changeId) { + this.changeId = Optional.ofNullable(changeId); + return this; + } + + /** + *

ID for the request that caused the event.

+ */ + @JsonSetter(value = "requestID", nulls = Nulls.SKIP) + public Builder requestId(Optional requestId) { + this.requestId = requestId; + return this; + } + + public Builder requestId(String requestId) { + this.requestId = Optional.ofNullable(requestId); + return this; + } + + /** + *

ID for the request set by the service that received the request.

+ */ + @JsonSetter(value = "traceID", nulls = Nulls.SKIP) + public Builder traceId(Optional traceId) { + this.traceId = traceId; + return this; + } + + public Builder traceId(String traceId) { + this.traceId = Optional.ofNullable(traceId); + return this; + } + + /** + *

ID for the session in which the request was sent.

+ */ + @JsonSetter(value = "sessionID", nulls = Nulls.SKIP) + public Builder sessionId(Optional sessionId) { + this.sessionId = sessionId; + return this; + } + + public Builder sessionId(String sessionId) { + this.sessionId = Optional.ofNullable(sessionId); + return this; + } + + /** + *

Member who sent the request. Depending on actorType, this may be a user ID or a service account ID.

+ */ + @JsonSetter(value = "actor", nulls = Nulls.SKIP) + public Builder actor(Optional actor) { + this.actor = actor; + return this; + } + + public Builder actor(String actor) { + this.actor = Optional.ofNullable(actor); + return this; + } + + @JsonSetter(value = "actorType", nulls = Nulls.SKIP) + public Builder actorType(Optional actorType) { + this.actorType = actorType; + return this; + } + + public Builder actorType(V1MemberType actorType) { + this.actorType = Optional.ofNullable(actorType); + return this; + } + + @JsonSetter(value = "accessType", nulls = Nulls.SKIP) + public Builder accessType(Optional accessType) { + this.accessType = accessType; + return this; + } + + public Builder accessType(ContextAccessType accessType) { + this.accessType = Optional.ofNullable(accessType); + return this; + } + + /** + *

IP Address of the client that made the request.

+ */ + @JsonSetter(value = "ipAddress", nulls = Nulls.SKIP) + public Builder ipAddress(Optional ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + public Builder ipAddress(String ipAddress) { + this.ipAddress = Optional.ofNullable(ipAddress); + return this; + } + + /** + *

HTTP Origin request header (including scheme, hostname, and port) of the request.

+ */ + @JsonSetter(value = "origin", nulls = Nulls.SKIP) + public Builder origin(Optional origin) { + this.origin = origin; + return this; + } + + public Builder origin(String origin) { + this.origin = Optional.ofNullable(origin); + return this; + } + + @JsonSetter(value = "authMode", nulls = Nulls.SKIP) + public Builder authMode(Optional authMode) { + this.authMode = authMode; + return this; + } + + public Builder authMode(ContextAuthMode authMode) { + this.authMode = Optional.ofNullable(authMode); + return this; + } + + /** + *

ID of the JWT token.

+ */ + @JsonSetter(value = "jwtID", nulls = Nulls.SKIP) + public Builder jwtId(Optional jwtId) { + this.jwtId = jwtId; + return this; + } + + public Builder jwtId(String jwtId) { + this.jwtId = Optional.ofNullable(jwtId); + return this; + } + + /** + *

Embedded User Context.

+ */ + @JsonSetter(value = "bearerTokenContextID", nulls = Nulls.SKIP) + public Builder bearerTokenContextId(Optional bearerTokenContextId) { + this.bearerTokenContextId = bearerTokenContextId; + return this; + } + + public Builder bearerTokenContextId(String bearerTokenContextId) { + this.bearerTokenContextId = Optional.ofNullable(bearerTokenContextId); + return this; + } + + public AuditEventContext build() { + return new AuditEventContext( + changeId, + requestId, + traceId, + sessionId, + actor, + actorType, + accessType, + ipAddress, + origin, + authMode, + jwtId, + bearerTokenContextId, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/AuditEventData.java b/src/main/java/com/skyflow/generated/rest/types/AuditEventData.java new file mode 100644 index 00000000..45d15be1 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/AuditEventData.java @@ -0,0 +1,101 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = AuditEventData.Builder.class) +public final class AuditEventData { + private final Optional content; + + private final Map additionalProperties; + + private AuditEventData(Optional content, Map additionalProperties) { + this.content = content; + this.additionalProperties = additionalProperties; + } + + /** + * @return The entire body of the data requested or the query fired. + */ + @JsonProperty("content") + public Optional getContent() { + return content; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof AuditEventData && equalTo((AuditEventData) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(AuditEventData other) { + return content.equals(other.content); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.content); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional content = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(AuditEventData other) { + content(other.getContent()); + return this; + } + + /** + *

The entire body of the data requested or the query fired.

+ */ + @JsonSetter(value = "content", nulls = Nulls.SKIP) + public Builder content(Optional content) { + this.content = content; + return this; + } + + public Builder content(String content) { + this.content = Optional.ofNullable(content); + return this; + } + + public AuditEventData build() { + return new AuditEventData(content, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/AuditEventHttpInfo.java b/src/main/java/com/skyflow/generated/rest/types/AuditEventHttpInfo.java new file mode 100644 index 00000000..91126cc0 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/AuditEventHttpInfo.java @@ -0,0 +1,130 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = AuditEventHttpInfo.Builder.class) +public final class AuditEventHttpInfo { + private final Optional uri; + + private final Optional method; + + private final Map additionalProperties; + + private AuditEventHttpInfo( + Optional uri, Optional method, Map additionalProperties) { + this.uri = uri; + this.method = method; + this.additionalProperties = additionalProperties; + } + + /** + * @return The http URI that is used. + */ + @JsonProperty("URI") + public Optional getUri() { + return uri; + } + + /** + * @return http method used. + */ + @JsonProperty("method") + public Optional getMethod() { + return method; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof AuditEventHttpInfo && equalTo((AuditEventHttpInfo) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(AuditEventHttpInfo other) { + return uri.equals(other.uri) && method.equals(other.method); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.uri, this.method); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional uri = Optional.empty(); + + private Optional method = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(AuditEventHttpInfo other) { + uri(other.getUri()); + method(other.getMethod()); + return this; + } + + /** + *

The http URI that is used.

+ */ + @JsonSetter(value = "URI", nulls = Nulls.SKIP) + public Builder uri(Optional uri) { + this.uri = uri; + return this; + } + + public Builder uri(String uri) { + this.uri = Optional.ofNullable(uri); + return this; + } + + /** + *

http method used.

+ */ + @JsonSetter(value = "method", nulls = Nulls.SKIP) + public Builder method(Optional method) { + this.method = method; + return this; + } + + public Builder method(String method) { + this.method = Optional.ofNullable(method); + return this; + } + + public AuditEventHttpInfo build() { + return new AuditEventHttpInfo(uri, method, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/BatchRecordMethod.java b/src/main/java/com/skyflow/generated/rest/types/BatchRecordMethod.java new file mode 100644 index 00000000..c50f618d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/BatchRecordMethod.java @@ -0,0 +1,30 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum BatchRecordMethod { + NONE("NONE"), + + POST("POST"), + + PUT("PUT"), + + GET("GET"), + + DELETE("DELETE"); + + private final String value; + + BatchRecordMethod(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/ContextAccessType.java b/src/main/java/com/skyflow/generated/rest/types/ContextAccessType.java new file mode 100644 index 00000000..b1b6072c --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ContextAccessType.java @@ -0,0 +1,26 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum ContextAccessType { + ACCESS_NONE("ACCESS_NONE"), + + API("API"), + + SQL("SQL"); + + private final String value; + + ContextAccessType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/ContextAuthMode.java b/src/main/java/com/skyflow/generated/rest/types/ContextAuthMode.java new file mode 100644 index 00000000..349ca23a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ContextAuthMode.java @@ -0,0 +1,28 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum ContextAuthMode { + AUTH_NONE("AUTH_NONE"), + + OKTA_JWT("OKTA_JWT"), + + SERVICE_ACCOUNT_JWT("SERVICE_ACCOUNT_JWT"), + + PAT_JWT("PAT_JWT"); + + private final String value; + + ContextAuthMode(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DeidentifyFileOutput.java b/src/main/java/com/skyflow/generated/rest/types/DeidentifyFileOutput.java new file mode 100644 index 00000000..59839994 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DeidentifyFileOutput.java @@ -0,0 +1,164 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyFileOutput.Builder.class) +public final class DeidentifyFileOutput { + private final Optional processedFile; + + private final Optional processedFileType; + + private final Optional processedFileExtension; + + private final Map additionalProperties; + + private DeidentifyFileOutput( + Optional processedFile, + Optional processedFileType, + Optional processedFileExtension, + Map additionalProperties) { + this.processedFile = processedFile; + this.processedFileType = processedFileType; + this.processedFileExtension = processedFileExtension; + this.additionalProperties = additionalProperties; + } + + /** + * @return URL or base64-encoded data of the output. + */ + @JsonProperty("processed_file") + public Optional getProcessedFile() { + return processedFile; + } + + /** + * @return Type of the processed file. + */ + @JsonProperty("processed_file_type") + public Optional getProcessedFileType() { + return processedFileType; + } + + /** + * @return Extension of the processed file. + */ + @JsonProperty("processed_file_extension") + public Optional getProcessedFileExtension() { + return processedFileExtension; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyFileOutput && equalTo((DeidentifyFileOutput) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyFileOutput other) { + return processedFile.equals(other.processedFile) + && processedFileType.equals(other.processedFileType) + && processedFileExtension.equals(other.processedFileExtension); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.processedFile, this.processedFileType, this.processedFileExtension); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional processedFile = Optional.empty(); + + private Optional processedFileType = Optional.empty(); + + private Optional processedFileExtension = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DeidentifyFileOutput other) { + processedFile(other.getProcessedFile()); + processedFileType(other.getProcessedFileType()); + processedFileExtension(other.getProcessedFileExtension()); + return this; + } + + /** + *

URL or base64-encoded data of the output.

+ */ + @JsonSetter(value = "processed_file", nulls = Nulls.SKIP) + public Builder processedFile(Optional processedFile) { + this.processedFile = processedFile; + return this; + } + + public Builder processedFile(String processedFile) { + this.processedFile = Optional.ofNullable(processedFile); + return this; + } + + /** + *

Type of the processed file.

+ */ + @JsonSetter(value = "processed_file_type", nulls = Nulls.SKIP) + public Builder processedFileType(Optional processedFileType) { + this.processedFileType = processedFileType; + return this; + } + + public Builder processedFileType(DeidentifyFileOutputProcessedFileType processedFileType) { + this.processedFileType = Optional.ofNullable(processedFileType); + return this; + } + + /** + *

Extension of the processed file.

+ */ + @JsonSetter(value = "processed_file_extension", nulls = Nulls.SKIP) + public Builder processedFileExtension(Optional processedFileExtension) { + this.processedFileExtension = processedFileExtension; + return this; + } + + public Builder processedFileExtension(String processedFileExtension) { + this.processedFileExtension = Optional.ofNullable(processedFileExtension); + return this; + } + + public DeidentifyFileOutput build() { + return new DeidentifyFileOutput( + processedFile, processedFileType, processedFileExtension, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DeidentifyFileOutputProcessedFileType.java b/src/main/java/com/skyflow/generated/rest/types/DeidentifyFileOutputProcessedFileType.java new file mode 100644 index 00000000..c560dc9e --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DeidentifyFileOutputProcessedFileType.java @@ -0,0 +1,40 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DeidentifyFileOutputProcessedFileType { + ENTITIES("entities"), + + PLAINTEXT_TRANSCRIPTION("plaintext_transcription"), + + REDACTED_AUDIO("redacted_audio"), + + REDACTED_DIARIZED_TRANSCRIPTION("redacted_diarized_transcription"), + + REDACTED_FILE("redacted_file"), + + REDACTED_IMAGE("redacted_image"), + + REDACTED_MEDICAL_DIARIZED_TRANSCRIPTION("redacted_medical_diarized_transcription"), + + REDACTED_MEDICAL_TRANSCRIPTION("redacted_medical_transcription"), + + REDACTED_TEXT("redacted_text"), + + REDACTED_TRANSCRIPTION("redacted_transcription"); + + private final String value; + + DeidentifyFileOutputProcessedFileType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DeidentifyFileResponse.java b/src/main/java/com/skyflow/generated/rest/types/DeidentifyFileResponse.java new file mode 100644 index 00000000..460058dc --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DeidentifyFileResponse.java @@ -0,0 +1,112 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyFileResponse.Builder.class) +public final class DeidentifyFileResponse { + private final String runId; + + private final Map additionalProperties; + + private DeidentifyFileResponse(String runId, Map additionalProperties) { + this.runId = runId; + this.additionalProperties = additionalProperties; + } + + /** + * @return Status URL for the detect run. + */ + @JsonProperty("run_id") + public String getRunId() { + return runId; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyFileResponse && equalTo((DeidentifyFileResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyFileResponse other) { + return runId.equals(other.runId); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.runId); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static RunIdStage builder() { + return new Builder(); + } + + public interface RunIdStage { + /** + * Status URL for the detect run. + */ + _FinalStage runId(@NotNull String runId); + + Builder from(DeidentifyFileResponse other); + } + + public interface _FinalStage { + DeidentifyFileResponse build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements RunIdStage, _FinalStage { + private String runId; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyFileResponse other) { + runId(other.getRunId()); + return this; + } + + /** + * Status URL for the detect run.

Status URL for the detect run.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("run_id") + public _FinalStage runId(@NotNull String runId) { + this.runId = Objects.requireNonNull(runId, "runId must not be null"); + return this; + } + + @java.lang.Override + public DeidentifyFileResponse build() { + return new DeidentifyFileResponse(runId, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponse.java b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponse.java new file mode 100644 index 00000000..9f73e9ad --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponse.java @@ -0,0 +1,521 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyStatusResponse.Builder.class) +public final class DeidentifyStatusResponse { + private final DeidentifyStatusResponseStatus status; + + private final List output; + + private final DeidentifyStatusResponseOutputType outputType; + + private final String message; + + private final Optional wordCount; + + private final Optional characterCount; + + private final Optional size; + + private final Optional duration; + + private final Optional pages; + + private final Optional slides; + + private final Map additionalProperties; + + private DeidentifyStatusResponse( + DeidentifyStatusResponseStatus status, + List output, + DeidentifyStatusResponseOutputType outputType, + String message, + Optional wordCount, + Optional characterCount, + Optional size, + Optional duration, + Optional pages, + Optional slides, + Map additionalProperties) { + this.status = status; + this.output = output; + this.outputType = outputType; + this.message = message; + this.wordCount = wordCount; + this.characterCount = characterCount; + this.size = size; + this.duration = duration; + this.pages = pages; + this.slides = slides; + this.additionalProperties = additionalProperties; + } + + /** + * @return Status of the detect run. + */ + @JsonProperty("status") + public DeidentifyStatusResponseStatus getStatus() { + return status; + } + + /** + * @return How the input file was specified. + */ + @JsonProperty("output") + public List getOutput() { + return output; + } + + /** + * @return How the output file is specified. + */ + @JsonProperty("output_type") + public DeidentifyStatusResponseOutputType getOutputType() { + return outputType; + } + + /** + * @return Status details about the detect run. + */ + @JsonProperty("message") + public String getMessage() { + return message; + } + + /** + * @return Number of words in the processed text. + */ + @JsonProperty("word_count") + public Optional getWordCount() { + return wordCount; + } + + /** + * @return Number of characters in the processed text. + */ + @JsonProperty("character_count") + public Optional getCharacterCount() { + return characterCount; + } + + /** + * @return Size of the processed text in kilobytes (KB). + */ + @JsonProperty("size") + public Optional getSize() { + return size; + } + + /** + * @return Duration of the processed audio in seconds. + */ + @JsonProperty("duration") + public Optional getDuration() { + return duration; + } + + /** + * @return Number of pages in the processed PDF. + */ + @JsonProperty("pages") + public Optional getPages() { + return pages; + } + + /** + * @return Number of slides in the processed presentation. + */ + @JsonProperty("slides") + public Optional getSlides() { + return slides; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyStatusResponse && equalTo((DeidentifyStatusResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyStatusResponse other) { + return status.equals(other.status) + && output.equals(other.output) + && outputType.equals(other.outputType) + && message.equals(other.message) + && wordCount.equals(other.wordCount) + && characterCount.equals(other.characterCount) + && size.equals(other.size) + && duration.equals(other.duration) + && pages.equals(other.pages) + && slides.equals(other.slides); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.status, + this.output, + this.outputType, + this.message, + this.wordCount, + this.characterCount, + this.size, + this.duration, + this.pages, + this.slides); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static StatusStage builder() { + return new Builder(); + } + + public interface StatusStage { + /** + * Status of the detect run. + */ + OutputTypeStage status(@NotNull DeidentifyStatusResponseStatus status); + + Builder from(DeidentifyStatusResponse other); + } + + public interface OutputTypeStage { + /** + * How the output file is specified. + */ + MessageStage outputType(@NotNull DeidentifyStatusResponseOutputType outputType); + } + + public interface MessageStage { + /** + * Status details about the detect run. + */ + _FinalStage message(@NotNull String message); + } + + public interface _FinalStage { + DeidentifyStatusResponse build(); + + /** + *

How the input file was specified.

+ */ + _FinalStage output(List output); + + _FinalStage addOutput(DeidentifyFileOutput output); + + _FinalStage addAllOutput(List output); + + /** + *

Number of words in the processed text.

+ */ + _FinalStage wordCount(Optional wordCount); + + _FinalStage wordCount(Integer wordCount); + + /** + *

Number of characters in the processed text.

+ */ + _FinalStage characterCount(Optional characterCount); + + _FinalStage characterCount(Integer characterCount); + + /** + *

Size of the processed text in kilobytes (KB).

+ */ + _FinalStage size(Optional size); + + _FinalStage size(Integer size); + + /** + *

Duration of the processed audio in seconds.

+ */ + _FinalStage duration(Optional duration); + + _FinalStage duration(Integer duration); + + /** + *

Number of pages in the processed PDF.

+ */ + _FinalStage pages(Optional pages); + + _FinalStage pages(Integer pages); + + /** + *

Number of slides in the processed presentation.

+ */ + _FinalStage slides(Optional slides); + + _FinalStage slides(Integer slides); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements StatusStage, OutputTypeStage, MessageStage, _FinalStage { + private DeidentifyStatusResponseStatus status; + + private DeidentifyStatusResponseOutputType outputType; + + private String message; + + private Optional slides = Optional.empty(); + + private Optional pages = Optional.empty(); + + private Optional duration = Optional.empty(); + + private Optional size = Optional.empty(); + + private Optional characterCount = Optional.empty(); + + private Optional wordCount = Optional.empty(); + + private List output = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyStatusResponse other) { + status(other.getStatus()); + output(other.getOutput()); + outputType(other.getOutputType()); + message(other.getMessage()); + wordCount(other.getWordCount()); + characterCount(other.getCharacterCount()); + size(other.getSize()); + duration(other.getDuration()); + pages(other.getPages()); + slides(other.getSlides()); + return this; + } + + /** + * Status of the detect run.

Status of the detect run.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("status") + public OutputTypeStage status(@NotNull DeidentifyStatusResponseStatus status) { + this.status = Objects.requireNonNull(status, "status must not be null"); + return this; + } + + /** + * How the output file is specified.

How the output file is specified.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("output_type") + public MessageStage outputType(@NotNull DeidentifyStatusResponseOutputType outputType) { + this.outputType = Objects.requireNonNull(outputType, "outputType must not be null"); + return this; + } + + /** + * Status details about the detect run.

Status details about the detect run.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("message") + public _FinalStage message(@NotNull String message) { + this.message = Objects.requireNonNull(message, "message must not be null"); + return this; + } + + /** + *

Number of slides in the processed presentation.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage slides(Integer slides) { + this.slides = Optional.ofNullable(slides); + return this; + } + + /** + *

Number of slides in the processed presentation.

+ */ + @java.lang.Override + @JsonSetter(value = "slides", nulls = Nulls.SKIP) + public _FinalStage slides(Optional slides) { + this.slides = slides; + return this; + } + + /** + *

Number of pages in the processed PDF.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage pages(Integer pages) { + this.pages = Optional.ofNullable(pages); + return this; + } + + /** + *

Number of pages in the processed PDF.

+ */ + @java.lang.Override + @JsonSetter(value = "pages", nulls = Nulls.SKIP) + public _FinalStage pages(Optional pages) { + this.pages = pages; + return this; + } + + /** + *

Duration of the processed audio in seconds.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage duration(Integer duration) { + this.duration = Optional.ofNullable(duration); + return this; + } + + /** + *

Duration of the processed audio in seconds.

+ */ + @java.lang.Override + @JsonSetter(value = "duration", nulls = Nulls.SKIP) + public _FinalStage duration(Optional duration) { + this.duration = duration; + return this; + } + + /** + *

Size of the processed text in kilobytes (KB).

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage size(Integer size) { + this.size = Optional.ofNullable(size); + return this; + } + + /** + *

Size of the processed text in kilobytes (KB).

+ */ + @java.lang.Override + @JsonSetter(value = "size", nulls = Nulls.SKIP) + public _FinalStage size(Optional size) { + this.size = size; + return this; + } + + /** + *

Number of characters in the processed text.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage characterCount(Integer characterCount) { + this.characterCount = Optional.ofNullable(characterCount); + return this; + } + + /** + *

Number of characters in the processed text.

+ */ + @java.lang.Override + @JsonSetter(value = "character_count", nulls = Nulls.SKIP) + public _FinalStage characterCount(Optional characterCount) { + this.characterCount = characterCount; + return this; + } + + /** + *

Number of words in the processed text.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage wordCount(Integer wordCount) { + this.wordCount = Optional.ofNullable(wordCount); + return this; + } + + /** + *

Number of words in the processed text.

+ */ + @java.lang.Override + @JsonSetter(value = "word_count", nulls = Nulls.SKIP) + public _FinalStage wordCount(Optional wordCount) { + this.wordCount = wordCount; + return this; + } + + /** + *

How the input file was specified.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllOutput(List output) { + this.output.addAll(output); + return this; + } + + /** + *

How the input file was specified.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addOutput(DeidentifyFileOutput output) { + this.output.add(output); + return this; + } + + /** + *

How the input file was specified.

+ */ + @java.lang.Override + @JsonSetter(value = "output", nulls = Nulls.SKIP) + public _FinalStage output(List output) { + this.output.clear(); + this.output.addAll(output); + return this; + } + + @java.lang.Override + public DeidentifyStatusResponse build() { + return new DeidentifyStatusResponse( + status, + output, + outputType, + message, + wordCount, + characterCount, + size, + duration, + pages, + slides, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseOutputType.java b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseOutputType.java new file mode 100644 index 00000000..547bf414 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseOutputType.java @@ -0,0 +1,26 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DeidentifyStatusResponseOutputType { + BASE_64("BASE64"), + + EFS_PATH("EFS_PATH"), + + UNKNOWN("UNKNOWN"); + + private final String value; + + DeidentifyStatusResponseOutputType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseStatus.java b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseStatus.java new file mode 100644 index 00000000..4e51e5cf --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseStatus.java @@ -0,0 +1,26 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DeidentifyStatusResponseStatus { + FAILED("FAILED"), + + IN_PROGRESS("IN_PROGRESS"), + + SUCCESS("SUCCESS"); + + private final String value; + + DeidentifyStatusResponseStatus(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DeidentifyStringResponse.java b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStringResponse.java new file mode 100644 index 00000000..5b768610 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStringResponse.java @@ -0,0 +1,242 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DeidentifyStringResponse.Builder.class) +public final class DeidentifyStringResponse { + private final String processedText; + + private final List entities; + + private final int wordCount; + + private final int characterCount; + + private final Map additionalProperties; + + private DeidentifyStringResponse( + String processedText, + List entities, + int wordCount, + int characterCount, + Map additionalProperties) { + this.processedText = processedText; + this.entities = entities; + this.wordCount = wordCount; + this.characterCount = characterCount; + this.additionalProperties = additionalProperties; + } + + /** + * @return De-identified text. + */ + @JsonProperty("processed_text") + public String getProcessedText() { + return processedText; + } + + /** + * @return Detected entities. + */ + @JsonProperty("entities") + public List getEntities() { + return entities; + } + + /** + * @return Number of words from the input text. + */ + @JsonProperty("word_count") + public int getWordCount() { + return wordCount; + } + + /** + * @return Number of characters from the input text. + */ + @JsonProperty("character_count") + public int getCharacterCount() { + return characterCount; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DeidentifyStringResponse && equalTo((DeidentifyStringResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DeidentifyStringResponse other) { + return processedText.equals(other.processedText) + && entities.equals(other.entities) + && wordCount == other.wordCount + && characterCount == other.characterCount; + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.processedText, this.entities, this.wordCount, this.characterCount); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static ProcessedTextStage builder() { + return new Builder(); + } + + public interface ProcessedTextStage { + /** + * De-identified text. + */ + WordCountStage processedText(@NotNull String processedText); + + Builder from(DeidentifyStringResponse other); + } + + public interface WordCountStage { + /** + * Number of words from the input text. + */ + CharacterCountStage wordCount(int wordCount); + } + + public interface CharacterCountStage { + /** + * Number of characters from the input text. + */ + _FinalStage characterCount(int characterCount); + } + + public interface _FinalStage { + DeidentifyStringResponse build(); + + /** + *

Detected entities.

+ */ + _FinalStage entities(List entities); + + _FinalStage addEntities(DetectedEntity entities); + + _FinalStage addAllEntities(List entities); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements ProcessedTextStage, WordCountStage, CharacterCountStage, _FinalStage { + private String processedText; + + private int wordCount; + + private int characterCount; + + private List entities = new ArrayList<>(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(DeidentifyStringResponse other) { + processedText(other.getProcessedText()); + entities(other.getEntities()); + wordCount(other.getWordCount()); + characterCount(other.getCharacterCount()); + return this; + } + + /** + * De-identified text.

De-identified text.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("processed_text") + public WordCountStage processedText(@NotNull String processedText) { + this.processedText = Objects.requireNonNull(processedText, "processedText must not be null"); + return this; + } + + /** + * Number of words from the input text.

Number of words from the input text.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("word_count") + public CharacterCountStage wordCount(int wordCount) { + this.wordCount = wordCount; + return this; + } + + /** + * Number of characters from the input text.

Number of characters from the input text.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("character_count") + public _FinalStage characterCount(int characterCount) { + this.characterCount = characterCount; + return this; + } + + /** + *

Detected entities.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addAllEntities(List entities) { + this.entities.addAll(entities); + return this; + } + + /** + *

Detected entities.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage addEntities(DetectedEntity entities) { + this.entities.add(entities); + return this; + } + + /** + *

Detected entities.

+ */ + @java.lang.Override + @JsonSetter(value = "entities", nulls = Nulls.SKIP) + public _FinalStage entities(List entities) { + this.entities.clear(); + this.entities.addAll(entities); + return this; + } + + @java.lang.Override + public DeidentifyStringResponse build() { + return new DeidentifyStringResponse( + processedText, entities, wordCount, characterCount, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DetectDataAccuracy.java b/src/main/java/com/skyflow/generated/rest/types/DetectDataAccuracy.java new file mode 100644 index 00000000..64afed64 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DetectDataAccuracy.java @@ -0,0 +1,36 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DetectDataAccuracy { + UNKNOWN("unknown"), + + STANDARD("standard"), + + STANDARD_PLUS("standard_plus"), + + STANDARD_PLUS_MULTILINGUAL("standard_plus_multilingual"), + + STANDARD_PLUS_AUTOMATIC("standard_plus_automatic"), + + HIGH("high"), + + HIGH_MULTILINGUAL("high_multilingual"), + + HIGH_AUTOMATIC("high_automatic"); + + private final String value; + + DetectDataAccuracy(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DetectDataEntities.java b/src/main/java/com/skyflow/generated/rest/types/DetectDataEntities.java new file mode 100644 index 00000000..d655bb64 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DetectDataEntities.java @@ -0,0 +1,146 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DetectDataEntities { + AGE("age"), + + BANK_ACCOUNT("bank_account"), + + CREDIT_CARD("credit_card"), + + CREDIT_CARD_EXPIRATION("credit_card_expiration"), + + CVV("cvv"), + + DATE("date"), + + DATE_INTERVAL("date_interval"), + + DOB("dob"), + + DRIVER_LICENSE("driver_license"), + + EMAIL_ADDRESS("email_address"), + + HEALTHCARE_NUMBER("healthcare_number"), + + IP_ADDRESS("ip_address"), + + LOCATION("location"), + + NAME("name"), + + NUMERICAL_PII("numerical_pii"), + + PHONE_NUMBER("phone_number"), + + SSN("ssn"), + + URL("url"), + + VEHICLE_ID("vehicle_id"), + + MEDICAL_CODE("medical_code"), + + NAME_FAMILY("name_family"), + + NAME_GIVEN("name_given"), + + ACCOUNT_NUMBER("account_number"), + + EVENT("event"), + + FILENAME("filename"), + + GENDER_SEXUALITY("gender_sexuality"), + + LANGUAGE("language"), + + LOCATION_ADDRESS("location_address"), + + LOCATION_CITY("location_city"), + + LOCATION_COORDINATE("location_coordinate"), + + LOCATION_COUNTRY("location_country"), + + LOCATION_STATE("location_state"), + + LOCATION_ZIP("location_zip"), + + MARITAL_STATUS("marital_status"), + + MONEY("money"), + + NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), + + OCCUPATION("occupation"), + + ORGANIZATION("organization"), + + ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), + + ORIGIN("origin"), + + PASSPORT_NUMBER("passport_number"), + + PASSWORD("password"), + + PHYSICAL_ATTRIBUTE("physical_attribute"), + + POLITICAL_AFFILIATION("political_affiliation"), + + RELIGION("religion"), + + TIME("time"), + + USERNAME("username"), + + ZODIAC_SIGN("zodiac_sign"), + + BLOOD_TYPE("blood_type"), + + CONDITION("condition"), + + DOSE("dose"), + + DRUG("drug"), + + INJURY("injury"), + + MEDICAL_PROCESS("medical_process"), + + STATISTICS("statistics"), + + ROUTING_NUMBER("routing_number"), + + CORPORATE_ACTION("corporate_action"), + + FINANCIAL_METRIC("financial_metric"), + + PRODUCT("product"), + + TREND("trend"), + + DURATION("duration"), + + LOCATION_ADDRESS_STREET("location_address_street"), + + ALL("all"); + + private final String value; + + DetectDataEntities(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DetectFileRequestDataType.java b/src/main/java/com/skyflow/generated/rest/types/DetectFileRequestDataType.java new file mode 100644 index 00000000..e039bc86 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DetectFileRequestDataType.java @@ -0,0 +1,24 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DetectFileRequestDataType { + UNKNOWN("UNKNOWN"), + + BASE_64("BASE64"); + + private final String value; + + DetectFileRequestDataType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DetectRequestDeidentifyOption.java b/src/main/java/com/skyflow/generated/rest/types/DetectRequestDeidentifyOption.java new file mode 100644 index 00000000..bdc82ccf --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DetectRequestDeidentifyOption.java @@ -0,0 +1,26 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DetectRequestDeidentifyOption { + UNKNOWN("UNKNOWN"), + + ENTITY_UNQ_COUNTER("ENTITY_UNQ_COUNTER"), + + ENTITY_ONLY("ENTITY_ONLY"); + + private final String value; + + DetectRequestDeidentifyOption(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DetectedEntity.java b/src/main/java/com/skyflow/generated/rest/types/DetectedEntity.java new file mode 100644 index 00000000..6de2200a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DetectedEntity.java @@ -0,0 +1,217 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetectedEntity.Builder.class) +public final class DetectedEntity { + private final Optional token; + + private final Optional value; + + private final Optional location; + + private final Optional entityType; + + private final Optional> entityScores; + + private final Map additionalProperties; + + private DetectedEntity( + Optional token, + Optional value, + Optional location, + Optional entityType, + Optional> entityScores, + Map additionalProperties) { + this.token = token; + this.value = value; + this.location = location; + this.entityType = entityType; + this.entityScores = entityScores; + this.additionalProperties = additionalProperties; + } + + /** + * @return Processed text of the entity. + */ + @JsonProperty("token") + public Optional getToken() { + return token; + } + + /** + * @return Original text of the entity. + */ + @JsonProperty("value") + public Optional getValue() { + return value; + } + + @JsonProperty("location") + public Optional getLocation() { + return location; + } + + /** + * @return Highest-rated label. + */ + @JsonProperty("entity_type") + public Optional getEntityType() { + return entityType; + } + + /** + * @return entity_scores and their scores. + */ + @JsonProperty("entity_scores") + public Optional> getEntityScores() { + return entityScores; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetectedEntity && equalTo((DetectedEntity) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetectedEntity other) { + return token.equals(other.token) + && value.equals(other.value) + && location.equals(other.location) + && entityType.equals(other.entityType) + && entityScores.equals(other.entityScores); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.token, this.value, this.location, this.entityType, this.entityScores); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional token = Optional.empty(); + + private Optional value = Optional.empty(); + + private Optional location = Optional.empty(); + + private Optional entityType = Optional.empty(); + + private Optional> entityScores = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DetectedEntity other) { + token(other.getToken()); + value(other.getValue()); + location(other.getLocation()); + entityType(other.getEntityType()); + entityScores(other.getEntityScores()); + return this; + } + + /** + *

Processed text of the entity.

+ */ + @JsonSetter(value = "token", nulls = Nulls.SKIP) + public Builder token(Optional token) { + this.token = token; + return this; + } + + public Builder token(String token) { + this.token = Optional.ofNullable(token); + return this; + } + + /** + *

Original text of the entity.

+ */ + @JsonSetter(value = "value", nulls = Nulls.SKIP) + public Builder value(Optional value) { + this.value = value; + return this; + } + + public Builder value(String value) { + this.value = Optional.ofNullable(value); + return this; + } + + @JsonSetter(value = "location", nulls = Nulls.SKIP) + public Builder location(Optional location) { + this.location = location; + return this; + } + + public Builder location(EntityLocation location) { + this.location = Optional.ofNullable(location); + return this; + } + + /** + *

Highest-rated label.

+ */ + @JsonSetter(value = "entity_type", nulls = Nulls.SKIP) + public Builder entityType(Optional entityType) { + this.entityType = entityType; + return this; + } + + public Builder entityType(String entityType) { + this.entityType = Optional.ofNullable(entityType); + return this; + } + + /** + *

entity_scores and their scores.

+ */ + @JsonSetter(value = "entity_scores", nulls = Nulls.SKIP) + public Builder entityScores(Optional> entityScores) { + this.entityScores = entityScores; + return this; + } + + public Builder entityScores(Map entityScores) { + this.entityScores = Optional.ofNullable(entityScores); + return this; + } + + public DetectedEntity build() { + return new DetectedEntity(token, value, location, entityType, entityScores, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordResponseValueType.java b/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordResponseValueType.java new file mode 100644 index 00000000..f192c14f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DetokenizeRecordResponseValueType.java @@ -0,0 +1,38 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum DetokenizeRecordResponseValueType { + NONE("NONE"), + + STRING("STRING"), + + INTEGER("INTEGER"), + + FLOAT("FLOAT"), + + BOOL("BOOL"), + + DATETIME("DATETIME"), + + JSON("JSON"), + + ARRAY("ARRAY"), + + DATE("DATE"); + + private final String value; + + DetokenizeRecordResponseValueType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/EntityLocation.java b/src/main/java/com/skyflow/generated/rest/types/EntityLocation.java new file mode 100644 index 00000000..6e711422 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/EntityLocation.java @@ -0,0 +1,194 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = EntityLocation.Builder.class) +public final class EntityLocation { + private final Optional startIndex; + + private final Optional endIndex; + + private final Optional startIndexProcessed; + + private final Optional endIndexProcessed; + + private final Map additionalProperties; + + private EntityLocation( + Optional startIndex, + Optional endIndex, + Optional startIndexProcessed, + Optional endIndexProcessed, + Map additionalProperties) { + this.startIndex = startIndex; + this.endIndex = endIndex; + this.startIndexProcessed = startIndexProcessed; + this.endIndexProcessed = endIndexProcessed; + this.additionalProperties = additionalProperties; + } + + /** + * @return Index of the first character of the string in the original text. + */ + @JsonProperty("start_index") + public Optional getStartIndex() { + return startIndex; + } + + /** + * @return Index of the last character of the string in the original text. + */ + @JsonProperty("end_index") + public Optional getEndIndex() { + return endIndex; + } + + /** + * @return Index of the first character of the string in the processed text. + */ + @JsonProperty("start_index_processed") + public Optional getStartIndexProcessed() { + return startIndexProcessed; + } + + /** + * @return Index of the last character of the string in the processed text. + */ + @JsonProperty("end_index_processed") + public Optional getEndIndexProcessed() { + return endIndexProcessed; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof EntityLocation && equalTo((EntityLocation) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(EntityLocation other) { + return startIndex.equals(other.startIndex) + && endIndex.equals(other.endIndex) + && startIndexProcessed.equals(other.startIndexProcessed) + && endIndexProcessed.equals(other.endIndexProcessed); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.startIndex, this.endIndex, this.startIndexProcessed, this.endIndexProcessed); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional startIndex = Optional.empty(); + + private Optional endIndex = Optional.empty(); + + private Optional startIndexProcessed = Optional.empty(); + + private Optional endIndexProcessed = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(EntityLocation other) { + startIndex(other.getStartIndex()); + endIndex(other.getEndIndex()); + startIndexProcessed(other.getStartIndexProcessed()); + endIndexProcessed(other.getEndIndexProcessed()); + return this; + } + + /** + *

Index of the first character of the string in the original text.

+ */ + @JsonSetter(value = "start_index", nulls = Nulls.SKIP) + public Builder startIndex(Optional startIndex) { + this.startIndex = startIndex; + return this; + } + + public Builder startIndex(Integer startIndex) { + this.startIndex = Optional.ofNullable(startIndex); + return this; + } + + /** + *

Index of the last character of the string in the original text.

+ */ + @JsonSetter(value = "end_index", nulls = Nulls.SKIP) + public Builder endIndex(Optional endIndex) { + this.endIndex = endIndex; + return this; + } + + public Builder endIndex(Integer endIndex) { + this.endIndex = Optional.ofNullable(endIndex); + return this; + } + + /** + *

Index of the first character of the string in the processed text.

+ */ + @JsonSetter(value = "start_index_processed", nulls = Nulls.SKIP) + public Builder startIndexProcessed(Optional startIndexProcessed) { + this.startIndexProcessed = startIndexProcessed; + return this; + } + + public Builder startIndexProcessed(Integer startIndexProcessed) { + this.startIndexProcessed = Optional.ofNullable(startIndexProcessed); + return this; + } + + /** + *

Index of the last character of the string in the processed text.

+ */ + @JsonSetter(value = "end_index_processed", nulls = Nulls.SKIP) + public Builder endIndexProcessed(Optional endIndexProcessed) { + this.endIndexProcessed = endIndexProcessed; + return this; + } + + public Builder endIndexProcessed(Integer endIndexProcessed) { + this.endIndexProcessed = Optional.ofNullable(endIndexProcessed); + return this; + } + + public EntityLocation build() { + return new EntityLocation( + startIndex, endIndex, startIndexProcessed, endIndexProcessed, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/EntityType.java b/src/main/java/com/skyflow/generated/rest/types/EntityType.java new file mode 100644 index 00000000..605282ed --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/EntityType.java @@ -0,0 +1,146 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum EntityType { + ACCOUNT_NUMBER("account_number"), + + AGE("age"), + + ALL("all"), + + BANK_ACCOUNT("bank_account"), + + BLOOD_TYPE("blood_type"), + + CONDITION("condition"), + + CORPORATE_ACTION("corporate_action"), + + CREDIT_CARD("credit_card"), + + CREDIT_CARD_EXPIRATION("credit_card_expiration"), + + CVV("cvv"), + + DATE("date"), + + DATE_INTERVAL("date_interval"), + + DOB("dob"), + + DOSE("dose"), + + DRIVER_LICENSE("driver_license"), + + DRUG("drug"), + + DURATION("duration"), + + EMAIL_ADDRESS("email_address"), + + EVENT("event"), + + FILENAME("filename"), + + FINANCIAL_METRIC("financial_metric"), + + GENDER_SEXUALITY("gender_sexuality"), + + HEALTHCARE_NUMBER("healthcare_number"), + + INJURY("injury"), + + IP_ADDRESS("ip_address"), + + LANGUAGE("language"), + + LOCATION("location"), + + LOCATION_ADDRESS("location_address"), + + LOCATION_ADDRESS_STREET("location_address_street"), + + LOCATION_CITY("location_city"), + + LOCATION_COORDINATE("location_coordinate"), + + LOCATION_COUNTRY("location_country"), + + LOCATION_STATE("location_state"), + + LOCATION_ZIP("location_zip"), + + MARITAL_STATUS("marital_status"), + + MEDICAL_CODE("medical_code"), + + MEDICAL_PROCESS("medical_process"), + + MONEY("money"), + + NAME("name"), + + NAME_FAMILY("name_family"), + + NAME_GIVEN("name_given"), + + NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), + + NUMERICAL_PII("numerical_pii"), + + OCCUPATION("occupation"), + + ORGANIZATION("organization"), + + ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), + + ORIGIN("origin"), + + PASSPORT_NUMBER("passport_number"), + + PASSWORD("password"), + + PHONE_NUMBER("phone_number"), + + PHYSICAL_ATTRIBUTE("physical_attribute"), + + POLITICAL_AFFILIATION("political_affiliation"), + + PRODUCT("product"), + + RELIGION("religion"), + + ROUTING_NUMBER("routing_number"), + + SSN("ssn"), + + STATISTICS("statistics"), + + TIME("time"), + + TREND("trend"), + + URL("url"), + + USERNAME("username"), + + VEHICLE_ID("vehicle_id"), + + ZODIAC_SIGN("zodiac_sign"); + + private final String value; + + EntityType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/ErrorResponse.java b/src/main/java/com/skyflow/generated/rest/types/ErrorResponse.java new file mode 100644 index 00000000..68778cb1 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ErrorResponse.java @@ -0,0 +1,102 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ErrorResponse.Builder.class) +public final class ErrorResponse { + private final ErrorResponseError error; + + private final Map additionalProperties; + + private ErrorResponse(ErrorResponseError error, Map additionalProperties) { + this.error = error; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("error") + public ErrorResponseError getError() { + return error; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ErrorResponse && equalTo((ErrorResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ErrorResponse other) { + return error.equals(other.error); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.error); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static ErrorStage builder() { + return new Builder(); + } + + public interface ErrorStage { + _FinalStage error(@NotNull ErrorResponseError error); + + Builder from(ErrorResponse other); + } + + public interface _FinalStage { + ErrorResponse build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements ErrorStage, _FinalStage { + private ErrorResponseError error; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ErrorResponse other) { + error(other.getError()); + return this; + } + + @java.lang.Override + @JsonSetter("error") + public _FinalStage error(@NotNull ErrorResponseError error) { + this.error = Objects.requireNonNull(error, "error must not be null"); + return this; + } + + @java.lang.Override + public ErrorResponse build() { + return new ErrorResponse(error, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/ErrorResponseError.java b/src/main/java/com/skyflow/generated/rest/types/ErrorResponseError.java new file mode 100644 index 00000000..5d0ee57d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ErrorResponseError.java @@ -0,0 +1,240 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ErrorResponseError.Builder.class) +public final class ErrorResponseError { + private final int grpcCode; + + private final int httpCode; + + private final String httpStatus; + + private final String message; + + private final Optional>> details; + + private final Map additionalProperties; + + private ErrorResponseError( + int grpcCode, + int httpCode, + String httpStatus, + String message, + Optional>> details, + Map additionalProperties) { + this.grpcCode = grpcCode; + this.httpCode = httpCode; + this.httpStatus = httpStatus; + this.message = message; + this.details = details; + this.additionalProperties = additionalProperties; + } + + /** + * @return gRPC status codes. See https://grpc.io/docs/guides/status-codes. + */ + @JsonProperty("grpc_code") + public int getGrpcCode() { + return grpcCode; + } + + /** + * @return HTTP status codes. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status. + */ + @JsonProperty("http_code") + public int getHttpCode() { + return httpCode; + } + + /** + * @return HTTP status message. + */ + @JsonProperty("http_status") + public String getHttpStatus() { + return httpStatus; + } + + @JsonProperty("message") + public String getMessage() { + return message; + } + + @JsonProperty("details") + public Optional>> getDetails() { + return details; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ErrorResponseError && equalTo((ErrorResponseError) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ErrorResponseError other) { + return grpcCode == other.grpcCode + && httpCode == other.httpCode + && httpStatus.equals(other.httpStatus) + && message.equals(other.message) + && details.equals(other.details); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.grpcCode, this.httpCode, this.httpStatus, this.message, this.details); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static GrpcCodeStage builder() { + return new Builder(); + } + + public interface GrpcCodeStage { + /** + * gRPC status codes. See https://grpc.io/docs/guides/status-codes. + */ + HttpCodeStage grpcCode(int grpcCode); + + Builder from(ErrorResponseError other); + } + + public interface HttpCodeStage { + /** + * HTTP status codes. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status. + */ + HttpStatusStage httpCode(int httpCode); + } + + public interface HttpStatusStage { + /** + * HTTP status message. + */ + MessageStage httpStatus(@NotNull String httpStatus); + } + + public interface MessageStage { + _FinalStage message(@NotNull String message); + } + + public interface _FinalStage { + ErrorResponseError build(); + + _FinalStage details(Optional>> details); + + _FinalStage details(List> details); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder + implements GrpcCodeStage, HttpCodeStage, HttpStatusStage, MessageStage, _FinalStage { + private int grpcCode; + + private int httpCode; + + private String httpStatus; + + private String message; + + private Optional>> details = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ErrorResponseError other) { + grpcCode(other.getGrpcCode()); + httpCode(other.getHttpCode()); + httpStatus(other.getHttpStatus()); + message(other.getMessage()); + details(other.getDetails()); + return this; + } + + /** + * gRPC status codes. See https://grpc.io/docs/guides/status-codes.

gRPC status codes. See https://grpc.io/docs/guides/status-codes.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("grpc_code") + public HttpCodeStage grpcCode(int grpcCode) { + this.grpcCode = grpcCode; + return this; + } + + /** + * HTTP status codes. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status.

HTTP status codes. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("http_code") + public HttpStatusStage httpCode(int httpCode) { + this.httpCode = httpCode; + return this; + } + + /** + * HTTP status message.

HTTP status message.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("http_status") + public MessageStage httpStatus(@NotNull String httpStatus) { + this.httpStatus = Objects.requireNonNull(httpStatus, "httpStatus must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("message") + public _FinalStage message(@NotNull String message) { + this.message = Objects.requireNonNull(message, "message must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage details(List> details) { + this.details = Optional.ofNullable(details); + return this; + } + + @java.lang.Override + @JsonSetter(value = "details", nulls = Nulls.SKIP) + public _FinalStage details(Optional>> details) { + this.details = details; + return this; + } + + @java.lang.Override + public ErrorResponseError build() { + return new ErrorResponseError(grpcCode, httpCode, httpStatus, message, details, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/GooglerpcStatus.java b/src/main/java/com/skyflow/generated/rest/types/GooglerpcStatus.java new file mode 100644 index 00000000..d0290573 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/GooglerpcStatus.java @@ -0,0 +1,144 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = GooglerpcStatus.Builder.class) +public final class GooglerpcStatus { + private final Optional code; + + private final Optional message; + + private final Optional> details; + + private final Map additionalProperties; + + private GooglerpcStatus( + Optional code, + Optional message, + Optional> details, + Map additionalProperties) { + this.code = code; + this.message = message; + this.details = details; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("code") + public Optional getCode() { + return code; + } + + @JsonProperty("message") + public Optional getMessage() { + return message; + } + + @JsonProperty("details") + public Optional> getDetails() { + return details; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GooglerpcStatus && equalTo((GooglerpcStatus) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GooglerpcStatus other) { + return code.equals(other.code) && message.equals(other.message) && details.equals(other.details); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.code, this.message, this.details); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional code = Optional.empty(); + + private Optional message = Optional.empty(); + + private Optional> details = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(GooglerpcStatus other) { + code(other.getCode()); + message(other.getMessage()); + details(other.getDetails()); + return this; + } + + @JsonSetter(value = "code", nulls = Nulls.SKIP) + public Builder code(Optional code) { + this.code = code; + return this; + } + + public Builder code(Integer code) { + this.code = Optional.ofNullable(code); + return this; + } + + @JsonSetter(value = "message", nulls = Nulls.SKIP) + public Builder message(Optional message) { + this.message = message; + return this; + } + + public Builder message(String message) { + this.message = Optional.ofNullable(message); + return this; + } + + @JsonSetter(value = "details", nulls = Nulls.SKIP) + public Builder details(Optional> details) { + this.details = details; + return this; + } + + public Builder details(List details) { + this.details = Optional.ofNullable(details); + return this; + } + + public GooglerpcStatus build() { + return new GooglerpcStatus(code, message, details, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/ProcessedFileOutputProcessedFileType.java b/src/main/java/com/skyflow/generated/rest/types/ProcessedFileOutputProcessedFileType.java new file mode 100644 index 00000000..0563503c --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ProcessedFileOutputProcessedFileType.java @@ -0,0 +1,40 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum ProcessedFileOutputProcessedFileType { + NONE("none"), + + REDACTED_AUDIO("redacted_audio"), + + REDACTED_IMAGE("redacted_image"), + + REDACTED_TRANSCRIPTION("redacted_transcription"), + + REDACTED_FILE("redacted_file"), + + REDACTED_TEXT("redacted_text"), + + ENTITIES("entities"), + + REDACTED_AWS_TRANSCRIPTION_DIARIZE_JSON("redacted_aws_transcription_diarize_json"), + + REDACTED_DEEPGRAM_TRANSCRIPTION_DIARIZE_JSON("redacted_deepgram_transcription_diarize_json"), + + PLAINTEXT_TRANSCRIBED("plaintext_transcribed"); + + private final String value; + + ProcessedFileOutputProcessedFileType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/ProtobufAny.java b/src/main/java/com/skyflow/generated/rest/types/ProtobufAny.java new file mode 100644 index 00000000..37555aae --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ProtobufAny.java @@ -0,0 +1,95 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ProtobufAny.Builder.class) +public final class ProtobufAny { + private final Optional type; + + private final Map additionalProperties; + + private ProtobufAny(Optional type, Map additionalProperties) { + this.type = type; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("@type") + public Optional getType() { + return type; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ProtobufAny && equalTo((ProtobufAny) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ProtobufAny other) { + return type.equals(other.type); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.type); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional type = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(ProtobufAny other) { + type(other.getType()); + return this; + } + + @JsonSetter(value = "@type", nulls = Nulls.SKIP) + public Builder type(Optional type) { + this.type = type; + return this; + } + + public Builder type(String type) { + this.type = Optional.ofNullable(type); + return this; + } + + public ProtobufAny build() { + return new ProtobufAny(type, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/RedactionEnumRedaction.java b/src/main/java/com/skyflow/generated/rest/types/RedactionEnumRedaction.java new file mode 100644 index 00000000..3e83052b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/RedactionEnumRedaction.java @@ -0,0 +1,28 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum RedactionEnumRedaction { + DEFAULT("DEFAULT"), + + REDACTED("REDACTED"), + + MASKED("MASKED"), + + PLAIN_TEXT("PLAIN_TEXT"); + + private final String value; + + RedactionEnumRedaction(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/ReidentifyStringResponse.java b/src/main/java/com/skyflow/generated/rest/types/ReidentifyStringResponse.java new file mode 100644 index 00000000..ba305e63 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ReidentifyStringResponse.java @@ -0,0 +1,101 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyStringResponse.Builder.class) +public final class ReidentifyStringResponse { + private final Optional text; + + private final Map additionalProperties; + + private ReidentifyStringResponse(Optional text, Map additionalProperties) { + this.text = text; + this.additionalProperties = additionalProperties; + } + + /** + * @return Re-identified text. + */ + @JsonProperty("text") + public Optional getText() { + return text; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyStringResponse && equalTo((ReidentifyStringResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyStringResponse other) { + return text.equals(other.text); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.text); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional text = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(ReidentifyStringResponse other) { + text(other.getText()); + return this; + } + + /** + *

Re-identified text.

+ */ + @JsonSetter(value = "text", nulls = Nulls.SKIP) + public Builder text(Optional text) { + this.text = text; + return this; + } + + public Builder text(String text) { + this.text = Optional.ofNullable(text); + return this; + } + + public ReidentifyStringResponse build() { + return new ReidentifyStringResponse(text, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/RequestActionType.java b/src/main/java/com/skyflow/generated/rest/types/RequestActionType.java new file mode 100644 index 00000000..436a1de8 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/RequestActionType.java @@ -0,0 +1,56 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum RequestActionType { + NONE("NONE"), + + ASSIGN("ASSIGN"), + + CREATE("CREATE"), + + DELETE("DELETE"), + + EXECUTE("EXECUTE"), + + LIST("LIST"), + + READ("READ"), + + UNASSIGN("UNASSIGN"), + + UPDATE("UPDATE"), + + VALIDATE("VALIDATE"), + + LOGIN("LOGIN"), + + ROTATE("ROTATE"), + + SCHEDULEROTATION("SCHEDULEROTATION"), + + SCHEDULEROTATIONALERT("SCHEDULEROTATIONALERT"), + + IMPORT("IMPORT"), + + GETIMPORTPARAMETERS("GETIMPORTPARAMETERS"), + + PING("PING"), + + GETCLOUDPROVIDER("GETCLOUDPROVIDER"); + + private final String value; + + RequestActionType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/TokenType.java b/src/main/java/com/skyflow/generated/rest/types/TokenType.java new file mode 100644 index 00000000..a50e861b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/TokenType.java @@ -0,0 +1,188 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = TokenType.Builder.class) +public final class TokenType { + private final Optional default_; + + private final Optional> vaultToken; + + private final Optional> entityUnqCounter; + + private final Optional> entityOnly; + + private final Map additionalProperties; + + private TokenType( + Optional default_, + Optional> vaultToken, + Optional> entityUnqCounter, + Optional> entityOnly, + Map additionalProperties) { + this.default_ = default_; + this.vaultToken = vaultToken; + this.entityUnqCounter = entityUnqCounter; + this.entityOnly = entityOnly; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("default") + public Optional getDefault() { + return default_; + } + + /** + * @return Entity types to replace with vault tokens. + */ + @JsonProperty("vault_token") + public Optional> getVaultToken() { + return vaultToken; + } + + /** + * @return Entity types to replace with entity tokens with unique counters. + */ + @JsonProperty("entity_unq_counter") + public Optional> getEntityUnqCounter() { + return entityUnqCounter; + } + + /** + * @return Entity types to replace with entity tokens. + */ + @JsonProperty("entity_only") + public Optional> getEntityOnly() { + return entityOnly; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof TokenType && equalTo((TokenType) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(TokenType other) { + return default_.equals(other.default_) + && vaultToken.equals(other.vaultToken) + && entityUnqCounter.equals(other.entityUnqCounter) + && entityOnly.equals(other.entityOnly); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.default_, this.vaultToken, this.entityUnqCounter, this.entityOnly); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional default_ = Optional.empty(); + + private Optional> vaultToken = Optional.empty(); + + private Optional> entityUnqCounter = Optional.empty(); + + private Optional> entityOnly = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(TokenType other) { + default_(other.getDefault()); + vaultToken(other.getVaultToken()); + entityUnqCounter(other.getEntityUnqCounter()); + entityOnly(other.getEntityOnly()); + return this; + } + + @JsonSetter(value = "default", nulls = Nulls.SKIP) + public Builder default_(Optional default_) { + this.default_ = default_; + return this; + } + + public Builder default_(TokenTypeDefault default_) { + this.default_ = Optional.ofNullable(default_); + return this; + } + + /** + *

Entity types to replace with vault tokens.

+ */ + @JsonSetter(value = "vault_token", nulls = Nulls.SKIP) + public Builder vaultToken(Optional> vaultToken) { + this.vaultToken = vaultToken; + return this; + } + + public Builder vaultToken(List vaultToken) { + this.vaultToken = Optional.ofNullable(vaultToken); + return this; + } + + /** + *

Entity types to replace with entity tokens with unique counters.

+ */ + @JsonSetter(value = "entity_unq_counter", nulls = Nulls.SKIP) + public Builder entityUnqCounter(Optional> entityUnqCounter) { + this.entityUnqCounter = entityUnqCounter; + return this; + } + + public Builder entityUnqCounter(List entityUnqCounter) { + this.entityUnqCounter = Optional.ofNullable(entityUnqCounter); + return this; + } + + /** + *

Entity types to replace with entity tokens.

+ */ + @JsonSetter(value = "entity_only", nulls = Nulls.SKIP) + public Builder entityOnly(Optional> entityOnly) { + this.entityOnly = entityOnly; + return this; + } + + public Builder entityOnly(List entityOnly) { + this.entityOnly = Optional.ofNullable(entityOnly); + return this; + } + + public TokenType build() { + return new TokenType(default_, vaultToken, entityUnqCounter, entityOnly, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/TokenTypeDefault.java b/src/main/java/com/skyflow/generated/rest/types/TokenTypeDefault.java new file mode 100644 index 00000000..14ab8f0f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/TokenTypeDefault.java @@ -0,0 +1,26 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum TokenTypeDefault { + ENTITY_ONLY("entity_only"), + + ENTITY_UNQ_COUNTER("entity_unq_counter"), + + VAULT_TOKEN("vault_token"); + + private final String value; + + TokenTypeDefault(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/TokenTypeWithoutVault.java b/src/main/java/com/skyflow/generated/rest/types/TokenTypeWithoutVault.java new file mode 100644 index 00000000..5f5938a0 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/TokenTypeWithoutVault.java @@ -0,0 +1,158 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = TokenTypeWithoutVault.Builder.class) +public final class TokenTypeWithoutVault { + private final Optional default_; + + private final Optional> entityUnqCounter; + + private final Optional> entityOnly; + + private final Map additionalProperties; + + private TokenTypeWithoutVault( + Optional default_, + Optional> entityUnqCounter, + Optional> entityOnly, + Map additionalProperties) { + this.default_ = default_; + this.entityUnqCounter = entityUnqCounter; + this.entityOnly = entityOnly; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("default") + public Optional getDefault() { + return default_; + } + + /** + * @return Entity types to replace with entity tokens with unique counters. + */ + @JsonProperty("entity_unq_counter") + public Optional> getEntityUnqCounter() { + return entityUnqCounter; + } + + /** + * @return Entity types to replace with entity tokens. + */ + @JsonProperty("entity_only") + public Optional> getEntityOnly() { + return entityOnly; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof TokenTypeWithoutVault && equalTo((TokenTypeWithoutVault) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(TokenTypeWithoutVault other) { + return default_.equals(other.default_) + && entityUnqCounter.equals(other.entityUnqCounter) + && entityOnly.equals(other.entityOnly); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.default_, this.entityUnqCounter, this.entityOnly); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional default_ = Optional.empty(); + + private Optional> entityUnqCounter = Optional.empty(); + + private Optional> entityOnly = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(TokenTypeWithoutVault other) { + default_(other.getDefault()); + entityUnqCounter(other.getEntityUnqCounter()); + entityOnly(other.getEntityOnly()); + return this; + } + + @JsonSetter(value = "default", nulls = Nulls.SKIP) + public Builder default_(Optional default_) { + this.default_ = default_; + return this; + } + + public Builder default_(TokenTypeWithoutVaultDefault default_) { + this.default_ = Optional.ofNullable(default_); + return this; + } + + /** + *

Entity types to replace with entity tokens with unique counters.

+ */ + @JsonSetter(value = "entity_unq_counter", nulls = Nulls.SKIP) + public Builder entityUnqCounter(Optional> entityUnqCounter) { + this.entityUnqCounter = entityUnqCounter; + return this; + } + + public Builder entityUnqCounter(List entityUnqCounter) { + this.entityUnqCounter = Optional.ofNullable(entityUnqCounter); + return this; + } + + /** + *

Entity types to replace with entity tokens.

+ */ + @JsonSetter(value = "entity_only", nulls = Nulls.SKIP) + public Builder entityOnly(Optional> entityOnly) { + this.entityOnly = entityOnly; + return this; + } + + public Builder entityOnly(List entityOnly) { + this.entityOnly = Optional.ofNullable(entityOnly); + return this; + } + + public TokenTypeWithoutVault build() { + return new TokenTypeWithoutVault(default_, entityUnqCounter, entityOnly, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/TokenTypeWithoutVaultDefault.java b/src/main/java/com/skyflow/generated/rest/types/TokenTypeWithoutVaultDefault.java new file mode 100644 index 00000000..45dba579 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/TokenTypeWithoutVaultDefault.java @@ -0,0 +1,24 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum TokenTypeWithoutVaultDefault { + ENTITY_ONLY("entity_only"), + + ENTITY_UNQ_COUNTER("entity_unq_counter"); + + private final String value; + + TokenTypeWithoutVaultDefault(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/Transformations.java b/src/main/java/com/skyflow/generated/rest/types/Transformations.java new file mode 100644 index 00000000..46022faa --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/Transformations.java @@ -0,0 +1,101 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = Transformations.Builder.class) +public final class Transformations { + private final Optional shiftDates; + + private final Map additionalProperties; + + private Transformations(Optional shiftDates, Map additionalProperties) { + this.shiftDates = shiftDates; + this.additionalProperties = additionalProperties; + } + + /** + * @return Shift dates by a specified number of days. + */ + @JsonProperty("shift_dates") + public Optional getShiftDates() { + return shiftDates; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof Transformations && equalTo((Transformations) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(Transformations other) { + return shiftDates.equals(other.shiftDates); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.shiftDates); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional shiftDates = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(Transformations other) { + shiftDates(other.getShiftDates()); + return this; + } + + /** + *

Shift dates by a specified number of days.

+ */ + @JsonSetter(value = "shift_dates", nulls = Nulls.SKIP) + public Builder shiftDates(Optional shiftDates) { + this.shiftDates = shiftDates; + return this; + } + + public Builder shiftDates(TransformationsShiftDates shiftDates) { + this.shiftDates = Optional.ofNullable(shiftDates); + return this; + } + + public Transformations build() { + return new Transformations(shiftDates, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/TransformationsShiftDates.java b/src/main/java/com/skyflow/generated/rest/types/TransformationsShiftDates.java new file mode 100644 index 00000000..1e11938b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/TransformationsShiftDates.java @@ -0,0 +1,162 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = TransformationsShiftDates.Builder.class) +public final class TransformationsShiftDates { + private final Optional maxDays; + + private final Optional minDays; + + private final Optional> entityTypes; + + private final Map additionalProperties; + + private TransformationsShiftDates( + Optional maxDays, + Optional minDays, + Optional> entityTypes, + Map additionalProperties) { + this.maxDays = maxDays; + this.minDays = minDays; + this.entityTypes = entityTypes; + this.additionalProperties = additionalProperties; + } + + /** + * @return Maximum number of days to shift the date by. + */ + @JsonProperty("max_days") + public Optional getMaxDays() { + return maxDays; + } + + /** + * @return Minimum number of days to shift the date by. + */ + @JsonProperty("min_days") + public Optional getMinDays() { + return minDays; + } + + /** + * @return Entity types to shift dates for. + */ + @JsonProperty("entity_types") + public Optional> getEntityTypes() { + return entityTypes; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof TransformationsShiftDates && equalTo((TransformationsShiftDates) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(TransformationsShiftDates other) { + return maxDays.equals(other.maxDays) && minDays.equals(other.minDays) && entityTypes.equals(other.entityTypes); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.maxDays, this.minDays, this.entityTypes); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional maxDays = Optional.empty(); + + private Optional minDays = Optional.empty(); + + private Optional> entityTypes = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(TransformationsShiftDates other) { + maxDays(other.getMaxDays()); + minDays(other.getMinDays()); + entityTypes(other.getEntityTypes()); + return this; + } + + /** + *

Maximum number of days to shift the date by.

+ */ + @JsonSetter(value = "max_days", nulls = Nulls.SKIP) + public Builder maxDays(Optional maxDays) { + this.maxDays = maxDays; + return this; + } + + public Builder maxDays(Integer maxDays) { + this.maxDays = Optional.ofNullable(maxDays); + return this; + } + + /** + *

Minimum number of days to shift the date by.

+ */ + @JsonSetter(value = "min_days", nulls = Nulls.SKIP) + public Builder minDays(Optional minDays) { + this.minDays = minDays; + return this; + } + + public Builder minDays(Integer minDays) { + this.minDays = Optional.ofNullable(minDays); + return this; + } + + /** + *

Entity types to shift dates for.

+ */ + @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) + public Builder entityTypes(Optional> entityTypes) { + this.entityTypes = entityTypes; + return this; + } + + public Builder entityTypes(List entityTypes) { + this.entityTypes = Optional.ofNullable(entityTypes); + return this; + } + + public TransformationsShiftDates build() { + return new TransformationsShiftDates(maxDays, minDays, entityTypes, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/TransformationsShiftDatesEntityTypesItem.java b/src/main/java/com/skyflow/generated/rest/types/TransformationsShiftDatesEntityTypesItem.java new file mode 100644 index 00000000..148cea23 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/TransformationsShiftDatesEntityTypesItem.java @@ -0,0 +1,26 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum TransformationsShiftDatesEntityTypesItem { + DATE("date"), + + DATE_INTERVAL("date_interval"), + + DOB("dob"); + + private final String value; + + TransformationsShiftDatesEntityTypesItem(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1AdvancedOptions.java b/src/main/java/com/skyflow/generated/rest/types/V1AdvancedOptions.java new file mode 100644 index 00000000..999153e4 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1AdvancedOptions.java @@ -0,0 +1,157 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1AdvancedOptions.Builder.class) +public final class V1AdvancedOptions { + private final Optional dateShift; + + private final Optional customClient; + + private final Optional schema; + + private final Map additionalProperties; + + private V1AdvancedOptions( + Optional dateShift, + Optional customClient, + Optional schema, + Map additionalProperties) { + this.dateShift = dateShift; + this.customClient = customClient; + this.schema = schema; + this.additionalProperties = additionalProperties; + } + + /** + * @return No. of days by which original date has to be shifted to. + */ + @JsonProperty("date_shift") + public Optional getDateShift() { + return dateShift; + } + + /** + * @return Custom client specific logic. + */ + @JsonProperty("custom_client") + public Optional getCustomClient() { + return customClient; + } + + @JsonProperty("schema") + public Optional getSchema() { + return schema; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1AdvancedOptions && equalTo((V1AdvancedOptions) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1AdvancedOptions other) { + return dateShift.equals(other.dateShift) + && customClient.equals(other.customClient) + && schema.equals(other.schema); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.dateShift, this.customClient, this.schema); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional dateShift = Optional.empty(); + + private Optional customClient = Optional.empty(); + + private Optional schema = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1AdvancedOptions other) { + dateShift(other.getDateShift()); + customClient(other.getCustomClient()); + schema(other.getSchema()); + return this; + } + + /** + *

No. of days by which original date has to be shifted to.

+ */ + @JsonSetter(value = "date_shift", nulls = Nulls.SKIP) + public Builder dateShift(Optional dateShift) { + this.dateShift = dateShift; + return this; + } + + public Builder dateShift(Integer dateShift) { + this.dateShift = Optional.ofNullable(dateShift); + return this; + } + + /** + *

Custom client specific logic.

+ */ + @JsonSetter(value = "custom_client", nulls = Nulls.SKIP) + public Builder customClient(Optional customClient) { + this.customClient = customClient; + return this; + } + + public Builder customClient(Boolean customClient) { + this.customClient = Optional.ofNullable(customClient); + return this; + } + + @JsonSetter(value = "schema", nulls = Nulls.SKIP) + public Builder schema(Optional schema) { + this.schema = schema; + return this; + } + + public Builder schema(AdvancedOptionsVaultSchema schema) { + this.schema = Optional.ofNullable(schema); + return this; + } + + public V1AdvancedOptions build() { + return new V1AdvancedOptions(dateShift, customClient, schema, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1AudioConfig.java b/src/main/java/com/skyflow/generated/rest/types/V1AudioConfig.java new file mode 100644 index 00000000..50e5508a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1AudioConfig.java @@ -0,0 +1,151 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1AudioConfig.Builder.class) +public final class V1AudioConfig { + private final Optional outputTranscription; + + private final Optional outputProcessedAudio; + + private final Optional options; + + private final Map additionalProperties; + + private V1AudioConfig( + Optional outputTranscription, + Optional outputProcessedAudio, + Optional options, + Map additionalProperties) { + this.outputTranscription = outputTranscription; + this.outputProcessedAudio = outputProcessedAudio; + this.options = options; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("output_transcription") + public Optional getOutputTranscription() { + return outputTranscription; + } + + /** + * @return If true, includes processed audio file in the response. + */ + @JsonProperty("output_processed_audio") + public Optional getOutputProcessedAudio() { + return outputProcessedAudio; + } + + @JsonProperty("options") + public Optional getOptions() { + return options; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1AudioConfig && equalTo((V1AudioConfig) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1AudioConfig other) { + return outputTranscription.equals(other.outputTranscription) + && outputProcessedAudio.equals(other.outputProcessedAudio) + && options.equals(other.options); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.outputTranscription, this.outputProcessedAudio, this.options); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional outputTranscription = Optional.empty(); + + private Optional outputProcessedAudio = Optional.empty(); + + private Optional options = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1AudioConfig other) { + outputTranscription(other.getOutputTranscription()); + outputProcessedAudio(other.getOutputProcessedAudio()); + options(other.getOptions()); + return this; + } + + @JsonSetter(value = "output_transcription", nulls = Nulls.SKIP) + public Builder outputTranscription(Optional outputTranscription) { + this.outputTranscription = outputTranscription; + return this; + } + + public Builder outputTranscription(AudioConfigTranscriptionType outputTranscription) { + this.outputTranscription = Optional.ofNullable(outputTranscription); + return this; + } + + /** + *

If true, includes processed audio file in the response.

+ */ + @JsonSetter(value = "output_processed_audio", nulls = Nulls.SKIP) + public Builder outputProcessedAudio(Optional outputProcessedAudio) { + this.outputProcessedAudio = outputProcessedAudio; + return this; + } + + public Builder outputProcessedAudio(Boolean outputProcessedAudio) { + this.outputProcessedAudio = Optional.ofNullable(outputProcessedAudio); + return this; + } + + @JsonSetter(value = "options", nulls = Nulls.SKIP) + public Builder options(Optional options) { + this.options = options; + return this; + } + + public Builder options(V1AudioOptions options) { + this.options = Optional.ofNullable(options); + return this; + } + + public V1AudioConfig build() { + return new V1AudioConfig(outputTranscription, outputProcessedAudio, options, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1AudioOptions.java b/src/main/java/com/skyflow/generated/rest/types/V1AudioOptions.java new file mode 100644 index 00000000..d71b77a0 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1AudioOptions.java @@ -0,0 +1,234 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1AudioOptions.Builder.class) +public final class V1AudioOptions { + private final Optional bleepStartPadding; + + private final Optional bleepEndPadding; + + private final Optional distortionSteps; + + private final Optional bleepFrequency; + + private final Optional bleepGain; + + private final Map additionalProperties; + + private V1AudioOptions( + Optional bleepStartPadding, + Optional bleepEndPadding, + Optional distortionSteps, + Optional bleepFrequency, + Optional bleepGain, + Map additionalProperties) { + this.bleepStartPadding = bleepStartPadding; + this.bleepEndPadding = bleepEndPadding; + this.distortionSteps = distortionSteps; + this.bleepFrequency = bleepFrequency; + this.bleepGain = bleepGain; + this.additionalProperties = additionalProperties; + } + + /** + * @return Padding added to the beginning of a bleep, in seconds. + */ + @JsonProperty("bleep_start_padding") + public Optional getBleepStartPadding() { + return bleepStartPadding; + } + + /** + * @return Padding added to the end of a bleep, in seconds. + */ + @JsonProperty("bleep_end_padding") + public Optional getBleepEndPadding() { + return bleepEndPadding; + } + + /** + * @return Specifies how the distortion will be made. Providing a number more than 0 will result in a higher tone and a coefficient less than 0 will result in a lower tone. + */ + @JsonProperty("distortion_steps") + public Optional getDistortionSteps() { + return distortionSteps; + } + + /** + * @return This parameter configures the frequency of the sine wave used for the bleep sound in an audio segment. + */ + @JsonProperty("bleep_frequency") + public Optional getBleepFrequency() { + return bleepFrequency; + } + + /** + * @return It controls the relative loudness of the bleep,positive values increase its loudness, and negative values decrease it. + */ + @JsonProperty("bleep_gain") + public Optional getBleepGain() { + return bleepGain; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1AudioOptions && equalTo((V1AudioOptions) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1AudioOptions other) { + return bleepStartPadding.equals(other.bleepStartPadding) + && bleepEndPadding.equals(other.bleepEndPadding) + && distortionSteps.equals(other.distortionSteps) + && bleepFrequency.equals(other.bleepFrequency) + && bleepGain.equals(other.bleepGain); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.bleepStartPadding, + this.bleepEndPadding, + this.distortionSteps, + this.bleepFrequency, + this.bleepGain); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional bleepStartPadding = Optional.empty(); + + private Optional bleepEndPadding = Optional.empty(); + + private Optional distortionSteps = Optional.empty(); + + private Optional bleepFrequency = Optional.empty(); + + private Optional bleepGain = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1AudioOptions other) { + bleepStartPadding(other.getBleepStartPadding()); + bleepEndPadding(other.getBleepEndPadding()); + distortionSteps(other.getDistortionSteps()); + bleepFrequency(other.getBleepFrequency()); + bleepGain(other.getBleepGain()); + return this; + } + + /** + *

Padding added to the beginning of a bleep, in seconds.

+ */ + @JsonSetter(value = "bleep_start_padding", nulls = Nulls.SKIP) + public Builder bleepStartPadding(Optional bleepStartPadding) { + this.bleepStartPadding = bleepStartPadding; + return this; + } + + public Builder bleepStartPadding(Float bleepStartPadding) { + this.bleepStartPadding = Optional.ofNullable(bleepStartPadding); + return this; + } + + /** + *

Padding added to the end of a bleep, in seconds.

+ */ + @JsonSetter(value = "bleep_end_padding", nulls = Nulls.SKIP) + public Builder bleepEndPadding(Optional bleepEndPadding) { + this.bleepEndPadding = bleepEndPadding; + return this; + } + + public Builder bleepEndPadding(Float bleepEndPadding) { + this.bleepEndPadding = Optional.ofNullable(bleepEndPadding); + return this; + } + + /** + *

Specifies how the distortion will be made. Providing a number more than 0 will result in a higher tone and a coefficient less than 0 will result in a lower tone.

+ */ + @JsonSetter(value = "distortion_steps", nulls = Nulls.SKIP) + public Builder distortionSteps(Optional distortionSteps) { + this.distortionSteps = distortionSteps; + return this; + } + + public Builder distortionSteps(Integer distortionSteps) { + this.distortionSteps = Optional.ofNullable(distortionSteps); + return this; + } + + /** + *

This parameter configures the frequency of the sine wave used for the bleep sound in an audio segment.

+ */ + @JsonSetter(value = "bleep_frequency", nulls = Nulls.SKIP) + public Builder bleepFrequency(Optional bleepFrequency) { + this.bleepFrequency = bleepFrequency; + return this; + } + + public Builder bleepFrequency(Integer bleepFrequency) { + this.bleepFrequency = Optional.ofNullable(bleepFrequency); + return this; + } + + /** + *

It controls the relative loudness of the bleep,positive values increase its loudness, and negative values decrease it.

+ */ + @JsonSetter(value = "bleep_gain", nulls = Nulls.SKIP) + public Builder bleepGain(Optional bleepGain) { + this.bleepGain = bleepGain; + return this; + } + + public Builder bleepGain(Integer bleepGain) { + this.bleepGain = Optional.ofNullable(bleepGain); + return this; + } + + public V1AudioOptions build() { + return new V1AudioOptions( + bleepStartPadding, + bleepEndPadding, + distortionSteps, + bleepFrequency, + bleepGain, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1AuditAfterOptions.java b/src/main/java/com/skyflow/generated/rest/types/V1AuditAfterOptions.java new file mode 100644 index 00000000..1453dd99 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1AuditAfterOptions.java @@ -0,0 +1,130 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1AuditAfterOptions.Builder.class) +public final class V1AuditAfterOptions { + private final Optional timestamp; + + private final Optional changeId; + + private final Map additionalProperties; + + private V1AuditAfterOptions( + Optional timestamp, Optional changeId, Map additionalProperties) { + this.timestamp = timestamp; + this.changeId = changeId; + this.additionalProperties = additionalProperties; + } + + /** + * @return Timestamp provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank. + */ + @JsonProperty("timestamp") + public Optional getTimestamp() { + return timestamp; + } + + /** + * @return Change ID provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank. + */ + @JsonProperty("changeID") + public Optional getChangeId() { + return changeId; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1AuditAfterOptions && equalTo((V1AuditAfterOptions) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1AuditAfterOptions other) { + return timestamp.equals(other.timestamp) && changeId.equals(other.changeId); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.timestamp, this.changeId); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional timestamp = Optional.empty(); + + private Optional changeId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1AuditAfterOptions other) { + timestamp(other.getTimestamp()); + changeId(other.getChangeId()); + return this; + } + + /** + *

Timestamp provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank.

+ */ + @JsonSetter(value = "timestamp", nulls = Nulls.SKIP) + public Builder timestamp(Optional timestamp) { + this.timestamp = timestamp; + return this; + } + + public Builder timestamp(String timestamp) { + this.timestamp = Optional.ofNullable(timestamp); + return this; + } + + /** + *

Change ID provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank.

+ */ + @JsonSetter(value = "changeID", nulls = Nulls.SKIP) + public Builder changeId(Optional changeId) { + this.changeId = changeId; + return this; + } + + public Builder changeId(String changeId) { + this.changeId = Optional.ofNullable(changeId); + return this; + } + + public V1AuditAfterOptions build() { + return new V1AuditAfterOptions(timestamp, changeId, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1AuditEventResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1AuditEventResponse.java new file mode 100644 index 00000000..2dd2ca4e --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1AuditEventResponse.java @@ -0,0 +1,187 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1AuditEventResponse.Builder.class) +public final class V1AuditEventResponse { + private final Optional code; + + private final Optional message; + + private final Optional data; + + private final Optional timestamp; + + private final Map additionalProperties; + + private V1AuditEventResponse( + Optional code, + Optional message, + Optional data, + Optional timestamp, + Map additionalProperties) { + this.code = code; + this.message = message; + this.data = data; + this.timestamp = timestamp; + this.additionalProperties = additionalProperties; + } + + /** + * @return The status of the overall operation. + */ + @JsonProperty("code") + public Optional getCode() { + return code; + } + + /** + * @return The status message for the overall operation. + */ + @JsonProperty("message") + public Optional getMessage() { + return message; + } + + @JsonProperty("data") + public Optional getData() { + return data; + } + + /** + * @return time when this response is generated, use extention method to set it. + */ + @JsonProperty("timestamp") + public Optional getTimestamp() { + return timestamp; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1AuditEventResponse && equalTo((V1AuditEventResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1AuditEventResponse other) { + return code.equals(other.code) + && message.equals(other.message) + && data.equals(other.data) + && timestamp.equals(other.timestamp); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.code, this.message, this.data, this.timestamp); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional code = Optional.empty(); + + private Optional message = Optional.empty(); + + private Optional data = Optional.empty(); + + private Optional timestamp = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1AuditEventResponse other) { + code(other.getCode()); + message(other.getMessage()); + data(other.getData()); + timestamp(other.getTimestamp()); + return this; + } + + /** + *

The status of the overall operation.

+ */ + @JsonSetter(value = "code", nulls = Nulls.SKIP) + public Builder code(Optional code) { + this.code = code; + return this; + } + + public Builder code(Integer code) { + this.code = Optional.ofNullable(code); + return this; + } + + /** + *

The status message for the overall operation.

+ */ + @JsonSetter(value = "message", nulls = Nulls.SKIP) + public Builder message(Optional message) { + this.message = message; + return this; + } + + public Builder message(String message) { + this.message = Optional.ofNullable(message); + return this; + } + + @JsonSetter(value = "data", nulls = Nulls.SKIP) + public Builder data(Optional data) { + this.data = data; + return this; + } + + public Builder data(AuditEventData data) { + this.data = Optional.ofNullable(data); + return this; + } + + /** + *

time when this response is generated, use extention method to set it.

+ */ + @JsonSetter(value = "timestamp", nulls = Nulls.SKIP) + public Builder timestamp(Optional timestamp) { + this.timestamp = timestamp; + return this; + } + + public Builder timestamp(String timestamp) { + this.timestamp = Optional.ofNullable(timestamp); + return this; + } + + public V1AuditEventResponse build() { + return new V1AuditEventResponse(code, message, data, timestamp, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1AuditResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1AuditResponse.java new file mode 100644 index 00000000..88496f03 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1AuditResponse.java @@ -0,0 +1,127 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1AuditResponse.Builder.class) +public final class V1AuditResponse { + private final Optional> event; + + private final Optional nextOps; + + private final Map additionalProperties; + + private V1AuditResponse( + Optional> event, + Optional nextOps, + Map additionalProperties) { + this.event = event; + this.nextOps = nextOps; + this.additionalProperties = additionalProperties; + } + + /** + * @return Events matching the query. + */ + @JsonProperty("event") + public Optional> getEvent() { + return event; + } + + @JsonProperty("nextOps") + public Optional getNextOps() { + return nextOps; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1AuditResponse && equalTo((V1AuditResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1AuditResponse other) { + return event.equals(other.event) && nextOps.equals(other.nextOps); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.event, this.nextOps); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> event = Optional.empty(); + + private Optional nextOps = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1AuditResponse other) { + event(other.getEvent()); + nextOps(other.getNextOps()); + return this; + } + + /** + *

Events matching the query.

+ */ + @JsonSetter(value = "event", nulls = Nulls.SKIP) + public Builder event(Optional> event) { + this.event = event; + return this; + } + + public Builder event(List event) { + this.event = Optional.ofNullable(event); + return this; + } + + @JsonSetter(value = "nextOps", nulls = Nulls.SKIP) + public Builder nextOps(Optional nextOps) { + this.nextOps = nextOps; + return this; + } + + public Builder nextOps(V1AuditAfterOptions nextOps) { + this.nextOps = Optional.ofNullable(nextOps); + return this; + } + + public V1AuditResponse build() { + return new V1AuditResponse(event, nextOps, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1AuditResponseEvent.java b/src/main/java/com/skyflow/generated/rest/types/V1AuditResponseEvent.java new file mode 100644 index 00000000..595b724c --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1AuditResponseEvent.java @@ -0,0 +1,238 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1AuditResponseEvent.Builder.class) +public final class V1AuditResponseEvent { + private final Optional context; + + private final Optional request; + + private final Optional response; + + private final Optional parentAccountId; + + private final Optional accountId; + + private final Optional> resourceIDs; + + private final Map additionalProperties; + + private V1AuditResponseEvent( + Optional context, + Optional request, + Optional response, + Optional parentAccountId, + Optional accountId, + Optional> resourceIDs, + Map additionalProperties) { + this.context = context; + this.request = request; + this.response = response; + this.parentAccountId = parentAccountId; + this.accountId = accountId; + this.resourceIDs = resourceIDs; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("context") + public Optional getContext() { + return context; + } + + @JsonProperty("request") + public Optional getRequest() { + return request; + } + + @JsonProperty("response") + public Optional getResponse() { + return response; + } + + /** + * @return Parent account ID of the account that made the request, if any. + */ + @JsonProperty("parentAccountID") + public Optional getParentAccountId() { + return parentAccountId; + } + + /** + * @return ID of the account that made the request. + */ + @JsonProperty("accountID") + public Optional getAccountId() { + return accountId; + } + + /** + * @return IDs for resources involved in the event. Presented in {resourceType}/{resourceID} format. For example, VAULT/cd1d815aa09b4cbfbb803bd20349f202. + */ + @JsonProperty("resourceIDs") + public Optional> getResourceIDs() { + return resourceIDs; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1AuditResponseEvent && equalTo((V1AuditResponseEvent) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1AuditResponseEvent other) { + return context.equals(other.context) + && request.equals(other.request) + && response.equals(other.response) + && parentAccountId.equals(other.parentAccountId) + && accountId.equals(other.accountId) + && resourceIDs.equals(other.resourceIDs); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.context, this.request, this.response, this.parentAccountId, this.accountId, this.resourceIDs); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional context = Optional.empty(); + + private Optional request = Optional.empty(); + + private Optional response = Optional.empty(); + + private Optional parentAccountId = Optional.empty(); + + private Optional accountId = Optional.empty(); + + private Optional> resourceIDs = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1AuditResponseEvent other) { + context(other.getContext()); + request(other.getRequest()); + response(other.getResponse()); + parentAccountId(other.getParentAccountId()); + accountId(other.getAccountId()); + resourceIDs(other.getResourceIDs()); + return this; + } + + @JsonSetter(value = "context", nulls = Nulls.SKIP) + public Builder context(Optional context) { + this.context = context; + return this; + } + + public Builder context(AuditEventContext context) { + this.context = Optional.ofNullable(context); + return this; + } + + @JsonSetter(value = "request", nulls = Nulls.SKIP) + public Builder request(Optional request) { + this.request = request; + return this; + } + + public Builder request(V1AuditResponseEventRequest request) { + this.request = Optional.ofNullable(request); + return this; + } + + @JsonSetter(value = "response", nulls = Nulls.SKIP) + public Builder response(Optional response) { + this.response = response; + return this; + } + + public Builder response(V1AuditEventResponse response) { + this.response = Optional.ofNullable(response); + return this; + } + + /** + *

Parent account ID of the account that made the request, if any.

+ */ + @JsonSetter(value = "parentAccountID", nulls = Nulls.SKIP) + public Builder parentAccountId(Optional parentAccountId) { + this.parentAccountId = parentAccountId; + return this; + } + + public Builder parentAccountId(String parentAccountId) { + this.parentAccountId = Optional.ofNullable(parentAccountId); + return this; + } + + /** + *

ID of the account that made the request.

+ */ + @JsonSetter(value = "accountID", nulls = Nulls.SKIP) + public Builder accountId(Optional accountId) { + this.accountId = accountId; + return this; + } + + public Builder accountId(String accountId) { + this.accountId = Optional.ofNullable(accountId); + return this; + } + + /** + *

IDs for resources involved in the event. Presented in {resourceType}/{resourceID} format. For example, VAULT/cd1d815aa09b4cbfbb803bd20349f202.

+ */ + @JsonSetter(value = "resourceIDs", nulls = Nulls.SKIP) + public Builder resourceIDs(Optional> resourceIDs) { + this.resourceIDs = resourceIDs; + return this; + } + + public Builder resourceIDs(List resourceIDs) { + this.resourceIDs = Optional.ofNullable(resourceIDs); + return this; + } + + public V1AuditResponseEvent build() { + return new V1AuditResponseEvent( + context, request, response, parentAccountId, accountId, resourceIDs, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1AuditResponseEventRequest.java b/src/main/java/com/skyflow/generated/rest/types/V1AuditResponseEventRequest.java new file mode 100644 index 00000000..c77bc31f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1AuditResponseEventRequest.java @@ -0,0 +1,339 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1AuditResponseEventRequest.Builder.class) +public final class V1AuditResponseEventRequest { + private final Optional data; + + private final Optional apiName; + + private final Optional workspaceId; + + private final Optional vaultId; + + private final Optional> tags; + + private final Optional timestamp; + + private final Optional actionType; + + private final Optional resourceType; + + private final Optional httpInfo; + + private final Map additionalProperties; + + private V1AuditResponseEventRequest( + Optional data, + Optional apiName, + Optional workspaceId, + Optional vaultId, + Optional> tags, + Optional timestamp, + Optional actionType, + Optional resourceType, + Optional httpInfo, + Map additionalProperties) { + this.data = data; + this.apiName = apiName; + this.workspaceId = workspaceId; + this.vaultId = vaultId; + this.tags = tags; + this.timestamp = timestamp; + this.actionType = actionType; + this.resourceType = resourceType; + this.httpInfo = httpInfo; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("data") + public Optional getData() { + return data; + } + + /** + * @return API name. + */ + @JsonProperty("apiName") + public Optional getApiName() { + return apiName; + } + + /** + * @return The workspaceID (if any) of the request. + */ + @JsonProperty("workspaceID") + public Optional getWorkspaceId() { + return workspaceId; + } + + /** + * @return The vaultID (if any) of the request. + */ + @JsonProperty("vaultID") + public Optional getVaultId() { + return vaultId; + } + + /** + * @return Tags associated with the event. To provide better search capabilities. Like login. + */ + @JsonProperty("tags") + public Optional> getTags() { + return tags; + } + + /** + * @return time when this request is generated, use extention method to set it. + */ + @JsonProperty("timestamp") + public Optional getTimestamp() { + return timestamp; + } + + @JsonProperty("actionType") + public Optional getActionType() { + return actionType; + } + + @JsonProperty("resourceType") + public Optional getResourceType() { + return resourceType; + } + + @JsonProperty("httpInfo") + public Optional getHttpInfo() { + return httpInfo; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1AuditResponseEventRequest && equalTo((V1AuditResponseEventRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1AuditResponseEventRequest other) { + return data.equals(other.data) + && apiName.equals(other.apiName) + && workspaceId.equals(other.workspaceId) + && vaultId.equals(other.vaultId) + && tags.equals(other.tags) + && timestamp.equals(other.timestamp) + && actionType.equals(other.actionType) + && resourceType.equals(other.resourceType) + && httpInfo.equals(other.httpInfo); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.data, + this.apiName, + this.workspaceId, + this.vaultId, + this.tags, + this.timestamp, + this.actionType, + this.resourceType, + this.httpInfo); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional data = Optional.empty(); + + private Optional apiName = Optional.empty(); + + private Optional workspaceId = Optional.empty(); + + private Optional vaultId = Optional.empty(); + + private Optional> tags = Optional.empty(); + + private Optional timestamp = Optional.empty(); + + private Optional actionType = Optional.empty(); + + private Optional resourceType = Optional.empty(); + + private Optional httpInfo = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1AuditResponseEventRequest other) { + data(other.getData()); + apiName(other.getApiName()); + workspaceId(other.getWorkspaceId()); + vaultId(other.getVaultId()); + tags(other.getTags()); + timestamp(other.getTimestamp()); + actionType(other.getActionType()); + resourceType(other.getResourceType()); + httpInfo(other.getHttpInfo()); + return this; + } + + @JsonSetter(value = "data", nulls = Nulls.SKIP) + public Builder data(Optional data) { + this.data = data; + return this; + } + + public Builder data(AuditEventData data) { + this.data = Optional.ofNullable(data); + return this; + } + + /** + *

API name.

+ */ + @JsonSetter(value = "apiName", nulls = Nulls.SKIP) + public Builder apiName(Optional apiName) { + this.apiName = apiName; + return this; + } + + public Builder apiName(String apiName) { + this.apiName = Optional.ofNullable(apiName); + return this; + } + + /** + *

The workspaceID (if any) of the request.

+ */ + @JsonSetter(value = "workspaceID", nulls = Nulls.SKIP) + public Builder workspaceId(Optional workspaceId) { + this.workspaceId = workspaceId; + return this; + } + + public Builder workspaceId(String workspaceId) { + this.workspaceId = Optional.ofNullable(workspaceId); + return this; + } + + /** + *

The vaultID (if any) of the request.

+ */ + @JsonSetter(value = "vaultID", nulls = Nulls.SKIP) + public Builder vaultId(Optional vaultId) { + this.vaultId = vaultId; + return this; + } + + public Builder vaultId(String vaultId) { + this.vaultId = Optional.ofNullable(vaultId); + return this; + } + + /** + *

Tags associated with the event. To provide better search capabilities. Like login.

+ */ + @JsonSetter(value = "tags", nulls = Nulls.SKIP) + public Builder tags(Optional> tags) { + this.tags = tags; + return this; + } + + public Builder tags(List tags) { + this.tags = Optional.ofNullable(tags); + return this; + } + + /** + *

time when this request is generated, use extention method to set it.

+ */ + @JsonSetter(value = "timestamp", nulls = Nulls.SKIP) + public Builder timestamp(Optional timestamp) { + this.timestamp = timestamp; + return this; + } + + public Builder timestamp(String timestamp) { + this.timestamp = Optional.ofNullable(timestamp); + return this; + } + + @JsonSetter(value = "actionType", nulls = Nulls.SKIP) + public Builder actionType(Optional actionType) { + this.actionType = actionType; + return this; + } + + public Builder actionType(RequestActionType actionType) { + this.actionType = Optional.ofNullable(actionType); + return this; + } + + @JsonSetter(value = "resourceType", nulls = Nulls.SKIP) + public Builder resourceType(Optional resourceType) { + this.resourceType = resourceType; + return this; + } + + public Builder resourceType(AuditEventAuditResourceType resourceType) { + this.resourceType = Optional.ofNullable(resourceType); + return this; + } + + @JsonSetter(value = "httpInfo", nulls = Nulls.SKIP) + public Builder httpInfo(Optional httpInfo) { + this.httpInfo = httpInfo; + return this; + } + + public Builder httpInfo(AuditEventHttpInfo httpInfo) { + this.httpInfo = Optional.ofNullable(httpInfo); + return this; + } + + public V1AuditResponseEventRequest build() { + return new V1AuditResponseEventRequest( + data, + apiName, + workspaceId, + vaultId, + tags, + timestamp, + actionType, + resourceType, + httpInfo, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1BatchOperationResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1BatchOperationResponse.java new file mode 100644 index 00000000..03d752d9 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1BatchOperationResponse.java @@ -0,0 +1,133 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1BatchOperationResponse.Builder.class) +public final class V1BatchOperationResponse { + private final Optional vaultId; + + private final Optional>> responses; + + private final Map additionalProperties; + + private V1BatchOperationResponse( + Optional vaultId, + Optional>> responses, + Map additionalProperties) { + this.vaultId = vaultId; + this.responses = responses; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vaultID") + public Optional getVaultId() { + return vaultId; + } + + /** + * @return Responses in the same order as in the request. Responses have the same payload structure as their corresponding APIs: <br/><ul><li>POST returns an Insert Records response.</li><li>PUT returns an Update Record response.</li><li>GET returns a Get Record response.</li><li>DELETE returns a Delete Record response.</li></ul> + */ + @JsonProperty("responses") + public Optional>> getResponses() { + return responses; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1BatchOperationResponse && equalTo((V1BatchOperationResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1BatchOperationResponse other) { + return vaultId.equals(other.vaultId) && responses.equals(other.responses); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.responses); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional vaultId = Optional.empty(); + + private Optional>> responses = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1BatchOperationResponse other) { + vaultId(other.getVaultId()); + responses(other.getResponses()); + return this; + } + + /** + *

ID of the vault.

+ */ + @JsonSetter(value = "vaultID", nulls = Nulls.SKIP) + public Builder vaultId(Optional vaultId) { + this.vaultId = vaultId; + return this; + } + + public Builder vaultId(String vaultId) { + this.vaultId = Optional.ofNullable(vaultId); + return this; + } + + /** + *

Responses in the same order as in the request. Responses have the same payload structure as their corresponding APIs: <br/><ul><li>POST returns an Insert Records response.</li><li>PUT returns an Update Record response.</li><li>GET returns a Get Record response.</li><li>DELETE returns a Delete Record response.</li></ul>

+ */ + @JsonSetter(value = "responses", nulls = Nulls.SKIP) + public Builder responses(Optional>> responses) { + this.responses = responses; + return this; + } + + public Builder responses(List> responses) { + this.responses = Optional.ofNullable(responses); + return this; + } + + public V1BatchOperationResponse build() { + return new V1BatchOperationResponse(vaultId, responses, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1BatchRecord.java b/src/main/java/com/skyflow/generated/rest/types/V1BatchRecord.java new file mode 100644 index 00000000..39eb2e68 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1BatchRecord.java @@ -0,0 +1,382 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1BatchRecord.Builder.class) +public final class V1BatchRecord { + private final Optional> fields; + + private final Optional tableName; + + private final Optional method; + + private final Optional batchId; + + private final Optional redaction; + + private final Optional tokenization; + + private final Optional id; + + private final Optional downloadUrl; + + private final Optional upsert; + + private final Optional> tokens; + + private final Map additionalProperties; + + private V1BatchRecord( + Optional> fields, + Optional tableName, + Optional method, + Optional batchId, + Optional redaction, + Optional tokenization, + Optional id, + Optional downloadUrl, + Optional upsert, + Optional> tokens, + Map additionalProperties) { + this.fields = fields; + this.tableName = tableName; + this.method = method; + this.batchId = batchId; + this.redaction = redaction; + this.tokenization = tokenization; + this.id = id; + this.downloadUrl = downloadUrl; + this.upsert = upsert; + this.tokens = tokens; + this.additionalProperties = additionalProperties; + } + + /** + * @return Field and value key pairs. For example, {'field_1':'value_1', 'field_2':'value_2'}. Only valid when method is POST or PUT. + */ + @JsonProperty("fields") + public Optional> getFields() { + return fields; + } + + /** + * @return Name of the table to perform the operation on. + */ + @JsonProperty("tableName") + public Optional getTableName() { + return tableName; + } + + @JsonProperty("method") + public Optional getMethod() { + return method; + } + + /** + * @return ID to group operations by. Operations in the same group are executed sequentially. + */ + @JsonProperty("batchID") + public Optional getBatchId() { + return batchId; + } + + @JsonProperty("redaction") + public Optional getRedaction() { + return redaction; + } + + /** + * @return If true, this operation returns tokens for fields with tokenization enabled. Only applicable if skyflow_id values are specified. + */ + @JsonProperty("tokenization") + public Optional getTokenization() { + return tokenization; + } + + /** + * @return skyflow_id for the record. Only valid when method is GET, DELETE, or PUT. + */ + @JsonProperty("ID") + public Optional getId() { + return id; + } + + /** + * @return If true, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean. + */ + @JsonProperty("downloadURL") + public Optional getDownloadUrl() { + return downloadUrl; + } + + /** + * @return Column that stores primary keys for upsert operations. The column must be marked as unique in the vault schema. Only valid when method is POST. + */ + @JsonProperty("upsert") + public Optional getUpsert() { + return upsert; + } + + /** + * @return Fields and tokens for the record. For example, {'field_1':'token_1', 'field_2':'token_2'}. + */ + @JsonProperty("tokens") + public Optional> getTokens() { + return tokens; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1BatchRecord && equalTo((V1BatchRecord) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1BatchRecord other) { + return fields.equals(other.fields) + && tableName.equals(other.tableName) + && method.equals(other.method) + && batchId.equals(other.batchId) + && redaction.equals(other.redaction) + && tokenization.equals(other.tokenization) + && id.equals(other.id) + && downloadUrl.equals(other.downloadUrl) + && upsert.equals(other.upsert) + && tokens.equals(other.tokens); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.fields, + this.tableName, + this.method, + this.batchId, + this.redaction, + this.tokenization, + this.id, + this.downloadUrl, + this.upsert, + this.tokens); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> fields = Optional.empty(); + + private Optional tableName = Optional.empty(); + + private Optional method = Optional.empty(); + + private Optional batchId = Optional.empty(); + + private Optional redaction = Optional.empty(); + + private Optional tokenization = Optional.empty(); + + private Optional id = Optional.empty(); + + private Optional downloadUrl = Optional.empty(); + + private Optional upsert = Optional.empty(); + + private Optional> tokens = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1BatchRecord other) { + fields(other.getFields()); + tableName(other.getTableName()); + method(other.getMethod()); + batchId(other.getBatchId()); + redaction(other.getRedaction()); + tokenization(other.getTokenization()); + id(other.getId()); + downloadUrl(other.getDownloadUrl()); + upsert(other.getUpsert()); + tokens(other.getTokens()); + return this; + } + + /** + *

Field and value key pairs. For example, {'field_1':'value_1', 'field_2':'value_2'}. Only valid when method is POST or PUT.

+ */ + @JsonSetter(value = "fields", nulls = Nulls.SKIP) + public Builder fields(Optional> fields) { + this.fields = fields; + return this; + } + + public Builder fields(Map fields) { + this.fields = Optional.ofNullable(fields); + return this; + } + + /** + *

Name of the table to perform the operation on.

+ */ + @JsonSetter(value = "tableName", nulls = Nulls.SKIP) + public Builder tableName(Optional tableName) { + this.tableName = tableName; + return this; + } + + public Builder tableName(String tableName) { + this.tableName = Optional.ofNullable(tableName); + return this; + } + + @JsonSetter(value = "method", nulls = Nulls.SKIP) + public Builder method(Optional method) { + this.method = method; + return this; + } + + public Builder method(BatchRecordMethod method) { + this.method = Optional.ofNullable(method); + return this; + } + + /** + *

ID to group operations by. Operations in the same group are executed sequentially.

+ */ + @JsonSetter(value = "batchID", nulls = Nulls.SKIP) + public Builder batchId(Optional batchId) { + this.batchId = batchId; + return this; + } + + public Builder batchId(String batchId) { + this.batchId = Optional.ofNullable(batchId); + return this; + } + + @JsonSetter(value = "redaction", nulls = Nulls.SKIP) + public Builder redaction(Optional redaction) { + this.redaction = redaction; + return this; + } + + public Builder redaction(RedactionEnumRedaction redaction) { + this.redaction = Optional.ofNullable(redaction); + return this; + } + + /** + *

If true, this operation returns tokens for fields with tokenization enabled. Only applicable if skyflow_id values are specified.

+ */ + @JsonSetter(value = "tokenization", nulls = Nulls.SKIP) + public Builder tokenization(Optional tokenization) { + this.tokenization = tokenization; + return this; + } + + public Builder tokenization(Boolean tokenization) { + this.tokenization = Optional.ofNullable(tokenization); + return this; + } + + /** + *

skyflow_id for the record. Only valid when method is GET, DELETE, or PUT.

+ */ + @JsonSetter(value = "ID", nulls = Nulls.SKIP) + public Builder id(Optional id) { + this.id = id; + return this; + } + + public Builder id(String id) { + this.id = Optional.ofNullable(id); + return this; + } + + /** + *

If true, returns download URLs for fields with a file data type. URLs are valid for 15 minutes. If virus scanning is enabled, only returns if the file is clean.

+ */ + @JsonSetter(value = "downloadURL", nulls = Nulls.SKIP) + public Builder downloadUrl(Optional downloadUrl) { + this.downloadUrl = downloadUrl; + return this; + } + + public Builder downloadUrl(Boolean downloadUrl) { + this.downloadUrl = Optional.ofNullable(downloadUrl); + return this; + } + + /** + *

Column that stores primary keys for upsert operations. The column must be marked as unique in the vault schema. Only valid when method is POST.

+ */ + @JsonSetter(value = "upsert", nulls = Nulls.SKIP) + public Builder upsert(Optional upsert) { + this.upsert = upsert; + return this; + } + + public Builder upsert(String upsert) { + this.upsert = Optional.ofNullable(upsert); + return this; + } + + /** + *

Fields and tokens for the record. For example, {'field_1':'token_1', 'field_2':'token_2'}.

+ */ + @JsonSetter(value = "tokens", nulls = Nulls.SKIP) + public Builder tokens(Optional> tokens) { + this.tokens = tokens; + return this; + } + + public Builder tokens(Map tokens) { + this.tokens = Optional.ofNullable(tokens); + return this; + } + + public V1BatchRecord build() { + return new V1BatchRecord( + fields, + tableName, + method, + batchId, + redaction, + tokenization, + id, + downloadUrl, + upsert, + tokens, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1BinListResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1BinListResponse.java new file mode 100644 index 00000000..cf3a3326 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1BinListResponse.java @@ -0,0 +1,102 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1BinListResponse.Builder.class) +public final class V1BinListResponse { + private final Optional> cardsData; + + private final Map additionalProperties; + + private V1BinListResponse(Optional> cardsData, Map additionalProperties) { + this.cardsData = cardsData; + this.additionalProperties = additionalProperties; + } + + /** + * @return Card metadata associated with the specified BIN. + */ + @JsonProperty("cards_data") + public Optional> getCardsData() { + return cardsData; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1BinListResponse && equalTo((V1BinListResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1BinListResponse other) { + return cardsData.equals(other.cardsData); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.cardsData); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> cardsData = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1BinListResponse other) { + cardsData(other.getCardsData()); + return this; + } + + /** + *

Card metadata associated with the specified BIN.

+ */ + @JsonSetter(value = "cards_data", nulls = Nulls.SKIP) + public Builder cardsData(Optional> cardsData) { + this.cardsData = cardsData; + return this; + } + + public Builder cardsData(List cardsData) { + this.cardsData = Optional.ofNullable(cardsData); + return this; + } + + public V1BinListResponse build() { + return new V1BinListResponse(cardsData, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1BulkDeleteRecordResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1BulkDeleteRecordResponse.java new file mode 100644 index 00000000..5f781686 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1BulkDeleteRecordResponse.java @@ -0,0 +1,103 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1BulkDeleteRecordResponse.Builder.class) +public final class V1BulkDeleteRecordResponse { + private final Optional> recordIdResponse; + + private final Map additionalProperties; + + private V1BulkDeleteRecordResponse( + Optional> recordIdResponse, Map additionalProperties) { + this.recordIdResponse = recordIdResponse; + this.additionalProperties = additionalProperties; + } + + /** + * @return IDs for the deleted records, or * if all records were deleted. + */ + @JsonProperty("RecordIDResponse") + public Optional> getRecordIdResponse() { + return recordIdResponse; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1BulkDeleteRecordResponse && equalTo((V1BulkDeleteRecordResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1BulkDeleteRecordResponse other) { + return recordIdResponse.equals(other.recordIdResponse); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.recordIdResponse); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> recordIdResponse = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1BulkDeleteRecordResponse other) { + recordIdResponse(other.getRecordIdResponse()); + return this; + } + + /** + *

IDs for the deleted records, or * if all records were deleted.

+ */ + @JsonSetter(value = "RecordIDResponse", nulls = Nulls.SKIP) + public Builder recordIdResponse(Optional> recordIdResponse) { + this.recordIdResponse = recordIdResponse; + return this; + } + + public Builder recordIdResponse(List recordIdResponse) { + this.recordIdResponse = Optional.ofNullable(recordIdResponse); + return this; + } + + public V1BulkDeleteRecordResponse build() { + return new V1BulkDeleteRecordResponse(recordIdResponse, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1BulkGetRecordResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1BulkGetRecordResponse.java new file mode 100644 index 00000000..70d31034 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1BulkGetRecordResponse.java @@ -0,0 +1,102 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1BulkGetRecordResponse.Builder.class) +public final class V1BulkGetRecordResponse { + private final Optional> records; + + private final Map additionalProperties; + + private V1BulkGetRecordResponse(Optional> records, Map additionalProperties) { + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return The specified records. + */ + @JsonProperty("records") + public Optional> getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1BulkGetRecordResponse && equalTo((V1BulkGetRecordResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1BulkGetRecordResponse other) { + return records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> records = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1BulkGetRecordResponse other) { + records(other.getRecords()); + return this; + } + + /** + *

The specified records.

+ */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(Optional> records) { + this.records = records; + return this; + } + + public Builder records(List records) { + this.records = Optional.ofNullable(records); + return this; + } + + public V1BulkGetRecordResponse build() { + return new V1BulkGetRecordResponse(records, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1Byot.java b/src/main/java/com/skyflow/generated/rest/types/V1Byot.java new file mode 100644 index 00000000..819fdb42 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1Byot.java @@ -0,0 +1,26 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum V1Byot { + DISABLE("DISABLE"), + + ENABLE("ENABLE"), + + ENABLE_STRICT("ENABLE_STRICT"); + + private final String value; + + V1Byot(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1Card.java b/src/main/java/com/skyflow/generated/rest/types/V1Card.java new file mode 100644 index 00000000..d19d3099 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1Card.java @@ -0,0 +1,362 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1Card.Builder.class) +public final class V1Card { + private final Optional bin; + + private final Optional issuerName; + + private final Optional countryCode; + + private final Optional currency; + + private final Optional cardType; + + private final Optional cardCategory; + + private final Optional cardScheme; + + private final Optional cardLastFourDigits; + + private final Optional cardExpiry; + + private final Map additionalProperties; + + private V1Card( + Optional bin, + Optional issuerName, + Optional countryCode, + Optional currency, + Optional cardType, + Optional cardCategory, + Optional cardScheme, + Optional cardLastFourDigits, + Optional cardExpiry, + Map additionalProperties) { + this.bin = bin; + this.issuerName = issuerName; + this.countryCode = countryCode; + this.currency = currency; + this.cardType = cardType; + this.cardCategory = cardCategory; + this.cardScheme = cardScheme; + this.cardLastFourDigits = cardLastFourDigits; + this.cardExpiry = cardExpiry; + this.additionalProperties = additionalProperties; + } + + /** + * @return BIN of the card. + */ + @JsonProperty("BIN") + public Optional getBin() { + return bin; + } + + /** + * @return Name of the card issuer bank. + */ + @JsonProperty("issuer_name") + public Optional getIssuerName() { + return issuerName; + } + + /** + * @return Country code of the card. + */ + @JsonProperty("country_code") + public Optional getCountryCode() { + return countryCode; + } + + /** + * @return Currency of the card. + */ + @JsonProperty("currency") + public Optional getCurrency() { + return currency; + } + + /** + * @return Type of the card. + */ + @JsonProperty("card_type") + public Optional getCardType() { + return cardType; + } + + /** + * @return Category of the card. + */ + @JsonProperty("card_category") + public Optional getCardCategory() { + return cardCategory; + } + + /** + * @return Scheme of the card. + */ + @JsonProperty("card_scheme") + public Optional getCardScheme() { + return cardScheme; + } + + /** + * @return Last four digits of the card number. + */ + @JsonProperty("card_last_four_digits") + public Optional getCardLastFourDigits() { + return cardLastFourDigits; + } + + /** + * @return Expiry date of the card. + */ + @JsonProperty("card_expiry") + public Optional getCardExpiry() { + return cardExpiry; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1Card && equalTo((V1Card) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1Card other) { + return bin.equals(other.bin) + && issuerName.equals(other.issuerName) + && countryCode.equals(other.countryCode) + && currency.equals(other.currency) + && cardType.equals(other.cardType) + && cardCategory.equals(other.cardCategory) + && cardScheme.equals(other.cardScheme) + && cardLastFourDigits.equals(other.cardLastFourDigits) + && cardExpiry.equals(other.cardExpiry); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.bin, + this.issuerName, + this.countryCode, + this.currency, + this.cardType, + this.cardCategory, + this.cardScheme, + this.cardLastFourDigits, + this.cardExpiry); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional bin = Optional.empty(); + + private Optional issuerName = Optional.empty(); + + private Optional countryCode = Optional.empty(); + + private Optional currency = Optional.empty(); + + private Optional cardType = Optional.empty(); + + private Optional cardCategory = Optional.empty(); + + private Optional cardScheme = Optional.empty(); + + private Optional cardLastFourDigits = Optional.empty(); + + private Optional cardExpiry = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1Card other) { + bin(other.getBin()); + issuerName(other.getIssuerName()); + countryCode(other.getCountryCode()); + currency(other.getCurrency()); + cardType(other.getCardType()); + cardCategory(other.getCardCategory()); + cardScheme(other.getCardScheme()); + cardLastFourDigits(other.getCardLastFourDigits()); + cardExpiry(other.getCardExpiry()); + return this; + } + + /** + *

BIN of the card.

+ */ + @JsonSetter(value = "BIN", nulls = Nulls.SKIP) + public Builder bin(Optional bin) { + this.bin = bin; + return this; + } + + public Builder bin(String bin) { + this.bin = Optional.ofNullable(bin); + return this; + } + + /** + *

Name of the card issuer bank.

+ */ + @JsonSetter(value = "issuer_name", nulls = Nulls.SKIP) + public Builder issuerName(Optional issuerName) { + this.issuerName = issuerName; + return this; + } + + public Builder issuerName(String issuerName) { + this.issuerName = Optional.ofNullable(issuerName); + return this; + } + + /** + *

Country code of the card.

+ */ + @JsonSetter(value = "country_code", nulls = Nulls.SKIP) + public Builder countryCode(Optional countryCode) { + this.countryCode = countryCode; + return this; + } + + public Builder countryCode(String countryCode) { + this.countryCode = Optional.ofNullable(countryCode); + return this; + } + + /** + *

Currency of the card.

+ */ + @JsonSetter(value = "currency", nulls = Nulls.SKIP) + public Builder currency(Optional currency) { + this.currency = currency; + return this; + } + + public Builder currency(String currency) { + this.currency = Optional.ofNullable(currency); + return this; + } + + /** + *

Type of the card.

+ */ + @JsonSetter(value = "card_type", nulls = Nulls.SKIP) + public Builder cardType(Optional cardType) { + this.cardType = cardType; + return this; + } + + public Builder cardType(String cardType) { + this.cardType = Optional.ofNullable(cardType); + return this; + } + + /** + *

Category of the card.

+ */ + @JsonSetter(value = "card_category", nulls = Nulls.SKIP) + public Builder cardCategory(Optional cardCategory) { + this.cardCategory = cardCategory; + return this; + } + + public Builder cardCategory(String cardCategory) { + this.cardCategory = Optional.ofNullable(cardCategory); + return this; + } + + /** + *

Scheme of the card.

+ */ + @JsonSetter(value = "card_scheme", nulls = Nulls.SKIP) + public Builder cardScheme(Optional cardScheme) { + this.cardScheme = cardScheme; + return this; + } + + public Builder cardScheme(String cardScheme) { + this.cardScheme = Optional.ofNullable(cardScheme); + return this; + } + + /** + *

Last four digits of the card number.

+ */ + @JsonSetter(value = "card_last_four_digits", nulls = Nulls.SKIP) + public Builder cardLastFourDigits(Optional cardLastFourDigits) { + this.cardLastFourDigits = cardLastFourDigits; + return this; + } + + public Builder cardLastFourDigits(String cardLastFourDigits) { + this.cardLastFourDigits = Optional.ofNullable(cardLastFourDigits); + return this; + } + + /** + *

Expiry date of the card.

+ */ + @JsonSetter(value = "card_expiry", nulls = Nulls.SKIP) + public Builder cardExpiry(Optional cardExpiry) { + this.cardExpiry = cardExpiry; + return this; + } + + public Builder cardExpiry(String cardExpiry) { + this.cardExpiry = Optional.ofNullable(cardExpiry); + return this; + } + + public V1Card build() { + return new V1Card( + bin, + issuerName, + countryCode, + currency, + cardType, + cardCategory, + cardScheme, + cardLastFourDigits, + cardExpiry, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DeleteFileResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1DeleteFileResponse.java new file mode 100644 index 00000000..efdb8e42 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1DeleteFileResponse.java @@ -0,0 +1,130 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1DeleteFileResponse.Builder.class) +public final class V1DeleteFileResponse { + private final Optional skyflowId; + + private final Optional deleted; + + private final Map additionalProperties; + + private V1DeleteFileResponse( + Optional skyflowId, Optional deleted, Map additionalProperties) { + this.skyflowId = skyflowId; + this.deleted = deleted; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the record. + */ + @JsonProperty("skyflow_id") + public Optional getSkyflowId() { + return skyflowId; + } + + /** + * @return If true, the file was deleted. + */ + @JsonProperty("deleted") + public Optional getDeleted() { + return deleted; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1DeleteFileResponse && equalTo((V1DeleteFileResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1DeleteFileResponse other) { + return skyflowId.equals(other.skyflowId) && deleted.equals(other.deleted); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.skyflowId, this.deleted); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional skyflowId = Optional.empty(); + + private Optional deleted = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1DeleteFileResponse other) { + skyflowId(other.getSkyflowId()); + deleted(other.getDeleted()); + return this; + } + + /** + *

ID of the record.

+ */ + @JsonSetter(value = "skyflow_id", nulls = Nulls.SKIP) + public Builder skyflowId(Optional skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + public Builder skyflowId(String skyflowId) { + this.skyflowId = Optional.ofNullable(skyflowId); + return this; + } + + /** + *

If true, the file was deleted.

+ */ + @JsonSetter(value = "deleted", nulls = Nulls.SKIP) + public Builder deleted(Optional deleted) { + this.deleted = deleted; + return this; + } + + public Builder deleted(Boolean deleted) { + this.deleted = Optional.ofNullable(deleted); + return this; + } + + public V1DeleteFileResponse build() { + return new V1DeleteFileResponse(skyflowId, deleted, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DeleteRecordResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1DeleteRecordResponse.java new file mode 100644 index 00000000..700bfe2f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1DeleteRecordResponse.java @@ -0,0 +1,130 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1DeleteRecordResponse.Builder.class) +public final class V1DeleteRecordResponse { + private final Optional skyflowId; + + private final Optional deleted; + + private final Map additionalProperties; + + private V1DeleteRecordResponse( + Optional skyflowId, Optional deleted, Map additionalProperties) { + this.skyflowId = skyflowId; + this.deleted = deleted; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the deleted record. + */ + @JsonProperty("skyflow_id") + public Optional getSkyflowId() { + return skyflowId; + } + + /** + * @return If true, the record was deleted. + */ + @JsonProperty("deleted") + public Optional getDeleted() { + return deleted; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1DeleteRecordResponse && equalTo((V1DeleteRecordResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1DeleteRecordResponse other) { + return skyflowId.equals(other.skyflowId) && deleted.equals(other.deleted); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.skyflowId, this.deleted); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional skyflowId = Optional.empty(); + + private Optional deleted = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1DeleteRecordResponse other) { + skyflowId(other.getSkyflowId()); + deleted(other.getDeleted()); + return this; + } + + /** + *

ID of the deleted record.

+ */ + @JsonSetter(value = "skyflow_id", nulls = Nulls.SKIP) + public Builder skyflowId(Optional skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + public Builder skyflowId(String skyflowId) { + this.skyflowId = Optional.ofNullable(skyflowId); + return this; + } + + /** + *

If true, the record was deleted.

+ */ + @JsonSetter(value = "deleted", nulls = Nulls.SKIP) + public Builder deleted(Optional deleted) { + this.deleted = deleted; + return this; + } + + public Builder deleted(Boolean deleted) { + this.deleted = Optional.ofNullable(deleted); + return this; + } + + public V1DeleteRecordResponse build() { + return new V1DeleteRecordResponse(skyflowId, deleted, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DetectFileResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1DetectFileResponse.java new file mode 100644 index 00000000..0c309cb9 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1DetectFileResponse.java @@ -0,0 +1,101 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1DetectFileResponse.Builder.class) +public final class V1DetectFileResponse { + private final Optional statusUrl; + + private final Map additionalProperties; + + private V1DetectFileResponse(Optional statusUrl, Map additionalProperties) { + this.statusUrl = statusUrl; + this.additionalProperties = additionalProperties; + } + + /** + * @return Status URL for the deidentification request. + */ + @JsonProperty("status_url") + public Optional getStatusUrl() { + return statusUrl; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1DetectFileResponse && equalTo((V1DetectFileResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1DetectFileResponse other) { + return statusUrl.equals(other.statusUrl); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.statusUrl); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional statusUrl = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1DetectFileResponse other) { + statusUrl(other.getStatusUrl()); + return this; + } + + /** + *

Status URL for the deidentification request.

+ */ + @JsonSetter(value = "status_url", nulls = Nulls.SKIP) + public Builder statusUrl(Optional statusUrl) { + this.statusUrl = statusUrl; + return this; + } + + public Builder statusUrl(String statusUrl) { + this.statusUrl = Optional.ofNullable(statusUrl); + return this; + } + + public V1DetectFileResponse build() { + return new V1DetectFileResponse(statusUrl, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponse.java new file mode 100644 index 00000000..95e7845c --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponse.java @@ -0,0 +1,156 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1DetectStatusResponse.Builder.class) +public final class V1DetectStatusResponse { + private final Optional status; + + private final Optional> output; + + private final Optional message; + + private final Map additionalProperties; + + private V1DetectStatusResponse( + Optional status, + Optional> output, + Optional message, + Map additionalProperties) { + this.status = status; + this.output = output; + this.message = message; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("status") + public Optional getStatus() { + return status; + } + + /** + * @return How the input file was specified. + */ + @JsonProperty("output") + public Optional> getOutput() { + return output; + } + + /** + * @return Status details about the deidentification request. + */ + @JsonProperty("message") + public Optional getMessage() { + return message; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1DetectStatusResponse && equalTo((V1DetectStatusResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1DetectStatusResponse other) { + return status.equals(other.status) && output.equals(other.output) && message.equals(other.message); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.status, this.output, this.message); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional status = Optional.empty(); + + private Optional> output = Optional.empty(); + + private Optional message = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1DetectStatusResponse other) { + status(other.getStatus()); + output(other.getOutput()); + message(other.getMessage()); + return this; + } + + @JsonSetter(value = "status", nulls = Nulls.SKIP) + public Builder status(Optional status) { + this.status = status; + return this; + } + + public Builder status(V1DetectStatusResponseStatus status) { + this.status = Optional.ofNullable(status); + return this; + } + + /** + *

How the input file was specified.

+ */ + @JsonSetter(value = "output", nulls = Nulls.SKIP) + public Builder output(Optional> output) { + this.output = output; + return this; + } + + public Builder output(List output) { + this.output = Optional.ofNullable(output); + return this; + } + + /** + *

Status details about the deidentification request.

+ */ + @JsonSetter(value = "message", nulls = Nulls.SKIP) + public Builder message(Optional message) { + this.message = message; + return this; + } + + public Builder message(String message) { + this.message = Optional.ofNullable(message); + return this; + } + + public V1DetectStatusResponse build() { + return new V1DetectStatusResponse(status, output, message, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponseStatus.java b/src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponseStatus.java new file mode 100644 index 00000000..c819b167 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponseStatus.java @@ -0,0 +1,28 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum V1DetectStatusResponseStatus { + UNKNOWN("UNKNOWN"), + + FAILED("FAILED"), + + SUCCESS("SUCCESS"), + + IN_PROGRESS("IN_PROGRESS"); + + private final String value; + + V1DetectStatusResponseStatus(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DetectTextRequest.java b/src/main/java/com/skyflow/generated/rest/types/V1DetectTextRequest.java new file mode 100644 index 00000000..57778d80 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1DetectTextRequest.java @@ -0,0 +1,522 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1DetectTextRequest.Builder.class) +public final class V1DetectTextRequest { + private final String text; + + private final String vaultId; + + private final Optional sessionId; + + private final Optional> restrictEntityTypes; + + private final Optional deidentifyTokenFormat; + + private final Optional> allowRegex; + + private final Optional> restrictRegex; + + private final Optional returnEntities; + + private final Optional accuracy; + + private final Optional advancedOptions; + + private final Optional storeEntities; + + private final Map additionalProperties; + + private V1DetectTextRequest( + String text, + String vaultId, + Optional sessionId, + Optional> restrictEntityTypes, + Optional deidentifyTokenFormat, + Optional> allowRegex, + Optional> restrictRegex, + Optional returnEntities, + Optional accuracy, + Optional advancedOptions, + Optional storeEntities, + Map additionalProperties) { + this.text = text; + this.vaultId = vaultId; + this.sessionId = sessionId; + this.restrictEntityTypes = restrictEntityTypes; + this.deidentifyTokenFormat = deidentifyTokenFormat; + this.allowRegex = allowRegex; + this.restrictRegex = restrictRegex; + this.returnEntities = returnEntities; + this.accuracy = accuracy; + this.advancedOptions = advancedOptions; + this.storeEntities = storeEntities; + this.additionalProperties = additionalProperties; + } + + /** + * @return Data to deidentify. + */ + @JsonProperty("text") + public String getText() { + return text; + } + + /** + * @return ID of the vault. + */ + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return Will give a handle to delete the tokens generated during a specific interaction. + */ + @JsonProperty("session_id") + public Optional getSessionId() { + return sessionId; + } + + /** + * @return Entities to detect and deidentify. + */ + @JsonProperty("restrict_entity_types") + public Optional> getRestrictEntityTypes() { + return restrictEntityTypes; + } + + @JsonProperty("deidentify_token_format") + public Optional getDeidentifyTokenFormat() { + return deidentifyTokenFormat; + } + + /** + * @return Regular expressions to ignore when detecting entities. + */ + @JsonProperty("allow_regex") + public Optional> getAllowRegex() { + return allowRegex; + } + + /** + * @return Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'. + */ + @JsonProperty("restrict_regex") + public Optional> getRestrictRegex() { + return restrictRegex; + } + + /** + * @return If true, returns the details for the detected entities. + */ + @JsonProperty("return_entities") + public Optional getReturnEntities() { + return returnEntities; + } + + @JsonProperty("accuracy") + public Optional getAccuracy() { + return accuracy; + } + + @JsonProperty("advanced_options") + public Optional getAdvancedOptions() { + return advancedOptions; + } + + /** + * @return Indicates whether entities should be stored in the vault. + */ + @JsonProperty("store_entities") + public Optional getStoreEntities() { + return storeEntities; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1DetectTextRequest && equalTo((V1DetectTextRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1DetectTextRequest other) { + return text.equals(other.text) + && vaultId.equals(other.vaultId) + && sessionId.equals(other.sessionId) + && restrictEntityTypes.equals(other.restrictEntityTypes) + && deidentifyTokenFormat.equals(other.deidentifyTokenFormat) + && allowRegex.equals(other.allowRegex) + && restrictRegex.equals(other.restrictRegex) + && returnEntities.equals(other.returnEntities) + && accuracy.equals(other.accuracy) + && advancedOptions.equals(other.advancedOptions) + && storeEntities.equals(other.storeEntities); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.text, + this.vaultId, + this.sessionId, + this.restrictEntityTypes, + this.deidentifyTokenFormat, + this.allowRegex, + this.restrictRegex, + this.returnEntities, + this.accuracy, + this.advancedOptions, + this.storeEntities); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TextStage builder() { + return new Builder(); + } + + public interface TextStage { + /** + * Data to deidentify. + */ + VaultIdStage text(@NotNull String text); + + Builder from(V1DetectTextRequest other); + } + + public interface VaultIdStage { + /** + * ID of the vault. + */ + _FinalStage vaultId(@NotNull String vaultId); + } + + public interface _FinalStage { + V1DetectTextRequest build(); + + /** + *

Will give a handle to delete the tokens generated during a specific interaction.

+ */ + _FinalStage sessionId(Optional sessionId); + + _FinalStage sessionId(String sessionId); + + /** + *

Entities to detect and deidentify.

+ */ + _FinalStage restrictEntityTypes(Optional> restrictEntityTypes); + + _FinalStage restrictEntityTypes(List restrictEntityTypes); + + _FinalStage deidentifyTokenFormat(Optional deidentifyTokenFormat); + + _FinalStage deidentifyTokenFormat(DetectRequestDeidentifyOption deidentifyTokenFormat); + + /** + *

Regular expressions to ignore when detecting entities.

+ */ + _FinalStage allowRegex(Optional> allowRegex); + + _FinalStage allowRegex(List allowRegex); + + /** + *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

+ */ + _FinalStage restrictRegex(Optional> restrictRegex); + + _FinalStage restrictRegex(List restrictRegex); + + /** + *

If true, returns the details for the detected entities.

+ */ + _FinalStage returnEntities(Optional returnEntities); + + _FinalStage returnEntities(Boolean returnEntities); + + _FinalStage accuracy(Optional accuracy); + + _FinalStage accuracy(DetectDataAccuracy accuracy); + + _FinalStage advancedOptions(Optional advancedOptions); + + _FinalStage advancedOptions(V1AdvancedOptions advancedOptions); + + /** + *

Indicates whether entities should be stored in the vault.

+ */ + _FinalStage storeEntities(Optional storeEntities); + + _FinalStage storeEntities(Boolean storeEntities); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TextStage, VaultIdStage, _FinalStage { + private String text; + + private String vaultId; + + private Optional storeEntities = Optional.empty(); + + private Optional advancedOptions = Optional.empty(); + + private Optional accuracy = Optional.empty(); + + private Optional returnEntities = Optional.empty(); + + private Optional> restrictRegex = Optional.empty(); + + private Optional> allowRegex = Optional.empty(); + + private Optional deidentifyTokenFormat = Optional.empty(); + + private Optional> restrictEntityTypes = Optional.empty(); + + private Optional sessionId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(V1DetectTextRequest other) { + text(other.getText()); + vaultId(other.getVaultId()); + sessionId(other.getSessionId()); + restrictEntityTypes(other.getRestrictEntityTypes()); + deidentifyTokenFormat(other.getDeidentifyTokenFormat()); + allowRegex(other.getAllowRegex()); + restrictRegex(other.getRestrictRegex()); + returnEntities(other.getReturnEntities()); + accuracy(other.getAccuracy()); + advancedOptions(other.getAdvancedOptions()); + storeEntities(other.getStoreEntities()); + return this; + } + + /** + * Data to deidentify.

Data to deidentify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("text") + public VaultIdStage text(@NotNull String text) { + this.text = Objects.requireNonNull(text, "text must not be null"); + return this; + } + + /** + * ID of the vault.

ID of the vault.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("vault_id") + public _FinalStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + *

Indicates whether entities should be stored in the vault.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage storeEntities(Boolean storeEntities) { + this.storeEntities = Optional.ofNullable(storeEntities); + return this; + } + + /** + *

Indicates whether entities should be stored in the vault.

+ */ + @java.lang.Override + @JsonSetter(value = "store_entities", nulls = Nulls.SKIP) + public _FinalStage storeEntities(Optional storeEntities) { + this.storeEntities = storeEntities; + return this; + } + + @java.lang.Override + public _FinalStage advancedOptions(V1AdvancedOptions advancedOptions) { + this.advancedOptions = Optional.ofNullable(advancedOptions); + return this; + } + + @java.lang.Override + @JsonSetter(value = "advanced_options", nulls = Nulls.SKIP) + public _FinalStage advancedOptions(Optional advancedOptions) { + this.advancedOptions = advancedOptions; + return this; + } + + @java.lang.Override + public _FinalStage accuracy(DetectDataAccuracy accuracy) { + this.accuracy = Optional.ofNullable(accuracy); + return this; + } + + @java.lang.Override + @JsonSetter(value = "accuracy", nulls = Nulls.SKIP) + public _FinalStage accuracy(Optional accuracy) { + this.accuracy = accuracy; + return this; + } + + /** + *

If true, returns the details for the detected entities.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage returnEntities(Boolean returnEntities) { + this.returnEntities = Optional.ofNullable(returnEntities); + return this; + } + + /** + *

If true, returns the details for the detected entities.

+ */ + @java.lang.Override + @JsonSetter(value = "return_entities", nulls = Nulls.SKIP) + public _FinalStage returnEntities(Optional returnEntities) { + this.returnEntities = returnEntities; + return this; + } + + /** + *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage restrictRegex(List restrictRegex) { + this.restrictRegex = Optional.ofNullable(restrictRegex); + return this; + } + + /** + *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

+ */ + @java.lang.Override + @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) + public _FinalStage restrictRegex(Optional> restrictRegex) { + this.restrictRegex = restrictRegex; + return this; + } + + /** + *

Regular expressions to ignore when detecting entities.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage allowRegex(List allowRegex) { + this.allowRegex = Optional.ofNullable(allowRegex); + return this; + } + + /** + *

Regular expressions to ignore when detecting entities.

+ */ + @java.lang.Override + @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) + public _FinalStage allowRegex(Optional> allowRegex) { + this.allowRegex = allowRegex; + return this; + } + + @java.lang.Override + public _FinalStage deidentifyTokenFormat(DetectRequestDeidentifyOption deidentifyTokenFormat) { + this.deidentifyTokenFormat = Optional.ofNullable(deidentifyTokenFormat); + return this; + } + + @java.lang.Override + @JsonSetter(value = "deidentify_token_format", nulls = Nulls.SKIP) + public _FinalStage deidentifyTokenFormat(Optional deidentifyTokenFormat) { + this.deidentifyTokenFormat = deidentifyTokenFormat; + return this; + } + + /** + *

Entities to detect and deidentify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage restrictEntityTypes(List restrictEntityTypes) { + this.restrictEntityTypes = Optional.ofNullable(restrictEntityTypes); + return this; + } + + /** + *

Entities to detect and deidentify.

+ */ + @java.lang.Override + @JsonSetter(value = "restrict_entity_types", nulls = Nulls.SKIP) + public _FinalStage restrictEntityTypes(Optional> restrictEntityTypes) { + this.restrictEntityTypes = restrictEntityTypes; + return this; + } + + /** + *

Will give a handle to delete the tokens generated during a specific interaction.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage sessionId(String sessionId) { + this.sessionId = Optional.ofNullable(sessionId); + return this; + } + + /** + *

Will give a handle to delete the tokens generated during a specific interaction.

+ */ + @java.lang.Override + @JsonSetter(value = "session_id", nulls = Nulls.SKIP) + public _FinalStage sessionId(Optional sessionId) { + this.sessionId = sessionId; + return this; + } + + @java.lang.Override + public V1DetectTextRequest build() { + return new V1DetectTextRequest( + text, + vaultId, + sessionId, + restrictEntityTypes, + deidentifyTokenFormat, + allowRegex, + restrictRegex, + returnEntities, + accuracy, + advancedOptions, + storeEntities, + additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DetectTextResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1DetectTextResponse.java new file mode 100644 index 00000000..a07c3344 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1DetectTextResponse.java @@ -0,0 +1,133 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1DetectTextResponse.Builder.class) +public final class V1DetectTextResponse { + private final Optional processedText; + + private final Optional> entities; + + private final Map additionalProperties; + + private V1DetectTextResponse( + Optional processedText, + Optional> entities, + Map additionalProperties) { + this.processedText = processedText; + this.entities = entities; + this.additionalProperties = additionalProperties; + } + + /** + * @return Deidentified text. If the input was a file, text that was extracted or transcribed from the file and deidentified. + */ + @JsonProperty("processed_text") + public Optional getProcessedText() { + return processedText; + } + + /** + * @return Detected entities. + */ + @JsonProperty("entities") + public Optional> getEntities() { + return entities; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1DetectTextResponse && equalTo((V1DetectTextResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1DetectTextResponse other) { + return processedText.equals(other.processedText) && entities.equals(other.entities); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.processedText, this.entities); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional processedText = Optional.empty(); + + private Optional> entities = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1DetectTextResponse other) { + processedText(other.getProcessedText()); + entities(other.getEntities()); + return this; + } + + /** + *

Deidentified text. If the input was a file, text that was extracted or transcribed from the file and deidentified.

+ */ + @JsonSetter(value = "processed_text", nulls = Nulls.SKIP) + public Builder processedText(Optional processedText) { + this.processedText = processedText; + return this; + } + + public Builder processedText(String processedText) { + this.processedText = Optional.ofNullable(processedText); + return this; + } + + /** + *

Detected entities.

+ */ + @JsonSetter(value = "entities", nulls = Nulls.SKIP) + public Builder entities(Optional> entities) { + this.entities = entities; + return this; + } + + public Builder entities(List entities) { + this.entities = Optional.ofNullable(entities); + return this; + } + + public V1DetectTextResponse build() { + return new V1DetectTextResponse(processedText, entities, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DetokenizeRecordRequest.java b/src/main/java/com/skyflow/generated/rest/types/V1DetokenizeRecordRequest.java new file mode 100644 index 00000000..5b6927d1 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1DetokenizeRecordRequest.java @@ -0,0 +1,126 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1DetokenizeRecordRequest.Builder.class) +public final class V1DetokenizeRecordRequest { + private final Optional token; + + private final Optional redaction; + + private final Map additionalProperties; + + private V1DetokenizeRecordRequest( + Optional token, + Optional redaction, + Map additionalProperties) { + this.token = token; + this.redaction = redaction; + this.additionalProperties = additionalProperties; + } + + /** + * @return Token that identifies the record to detokenize. + */ + @JsonProperty("token") + public Optional getToken() { + return token; + } + + @JsonProperty("redaction") + public Optional getRedaction() { + return redaction; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1DetokenizeRecordRequest && equalTo((V1DetokenizeRecordRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1DetokenizeRecordRequest other) { + return token.equals(other.token) && redaction.equals(other.redaction); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.token, this.redaction); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional token = Optional.empty(); + + private Optional redaction = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1DetokenizeRecordRequest other) { + token(other.getToken()); + redaction(other.getRedaction()); + return this; + } + + /** + *

Token that identifies the record to detokenize.

+ */ + @JsonSetter(value = "token", nulls = Nulls.SKIP) + public Builder token(Optional token) { + this.token = token; + return this; + } + + public Builder token(String token) { + this.token = Optional.ofNullable(token); + return this; + } + + @JsonSetter(value = "redaction", nulls = Nulls.SKIP) + public Builder redaction(Optional redaction) { + this.redaction = redaction; + return this; + } + + public Builder redaction(RedactionEnumRedaction redaction) { + this.redaction = Optional.ofNullable(redaction); + return this; + } + + public V1DetokenizeRecordRequest build() { + return new V1DetokenizeRecordRequest(token, redaction, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DetokenizeRecordResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1DetokenizeRecordResponse.java new file mode 100644 index 00000000..423abfe8 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1DetokenizeRecordResponse.java @@ -0,0 +1,187 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1DetokenizeRecordResponse.Builder.class) +public final class V1DetokenizeRecordResponse { + private final Optional token; + + private final Optional valueType; + + private final Optional value; + + private final Optional error; + + private final Map additionalProperties; + + private V1DetokenizeRecordResponse( + Optional token, + Optional valueType, + Optional value, + Optional error, + Map additionalProperties) { + this.token = token; + this.valueType = valueType; + this.value = value; + this.error = error; + this.additionalProperties = additionalProperties; + } + + /** + * @return Token of the record. + */ + @JsonProperty("token") + public Optional getToken() { + return token; + } + + @JsonProperty("valueType") + public Optional getValueType() { + return valueType; + } + + /** + * @return Data corresponding to the token. + */ + @JsonProperty("value") + public Optional getValue() { + return value; + } + + /** + * @return Error if token isn't found. + */ + @JsonProperty("error") + public Optional getError() { + return error; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1DetokenizeRecordResponse && equalTo((V1DetokenizeRecordResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1DetokenizeRecordResponse other) { + return token.equals(other.token) + && valueType.equals(other.valueType) + && value.equals(other.value) + && error.equals(other.error); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.token, this.valueType, this.value, this.error); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional token = Optional.empty(); + + private Optional valueType = Optional.empty(); + + private Optional value = Optional.empty(); + + private Optional error = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1DetokenizeRecordResponse other) { + token(other.getToken()); + valueType(other.getValueType()); + value(other.getValue()); + error(other.getError()); + return this; + } + + /** + *

Token of the record.

+ */ + @JsonSetter(value = "token", nulls = Nulls.SKIP) + public Builder token(Optional token) { + this.token = token; + return this; + } + + public Builder token(String token) { + this.token = Optional.ofNullable(token); + return this; + } + + @JsonSetter(value = "valueType", nulls = Nulls.SKIP) + public Builder valueType(Optional valueType) { + this.valueType = valueType; + return this; + } + + public Builder valueType(DetokenizeRecordResponseValueType valueType) { + this.valueType = Optional.ofNullable(valueType); + return this; + } + + /** + *

Data corresponding to the token.

+ */ + @JsonSetter(value = "value", nulls = Nulls.SKIP) + public Builder value(Optional value) { + this.value = value; + return this; + } + + public Builder value(String value) { + this.value = Optional.ofNullable(value); + return this; + } + + /** + *

Error if token isn't found.

+ */ + @JsonSetter(value = "error", nulls = Nulls.SKIP) + public Builder error(Optional error) { + this.error = error; + return this; + } + + public Builder error(String error) { + this.error = Optional.ofNullable(error); + return this; + } + + public V1DetokenizeRecordResponse build() { + return new V1DetokenizeRecordResponse(token, valueType, value, error, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DetokenizeResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1DetokenizeResponse.java new file mode 100644 index 00000000..20d7d8e4 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1DetokenizeResponse.java @@ -0,0 +1,103 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1DetokenizeResponse.Builder.class) +public final class V1DetokenizeResponse { + private final Optional> records; + + private final Map additionalProperties; + + private V1DetokenizeResponse( + Optional> records, Map additionalProperties) { + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return Records corresponding to the specified tokens. + */ + @JsonProperty("records") + public Optional> getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1DetokenizeResponse && equalTo((V1DetokenizeResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1DetokenizeResponse other) { + return records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> records = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1DetokenizeResponse other) { + records(other.getRecords()); + return this; + } + + /** + *

Records corresponding to the specified tokens.

+ */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(Optional> records) { + this.records = records; + return this; + } + + public Builder records(List records) { + this.records = Optional.ofNullable(records); + return this; + } + + public V1DetokenizeResponse build() { + return new V1DetokenizeResponse(records, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1FieldRecords.java b/src/main/java/com/skyflow/generated/rest/types/V1FieldRecords.java new file mode 100644 index 00000000..8d520d3b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1FieldRecords.java @@ -0,0 +1,132 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1FieldRecords.Builder.class) +public final class V1FieldRecords { + private final Optional> fields; + + private final Optional> tokens; + + private final Map additionalProperties; + + private V1FieldRecords( + Optional> fields, + Optional> tokens, + Map additionalProperties) { + this.fields = fields; + this.tokens = tokens; + this.additionalProperties = additionalProperties; + } + + /** + * @return Fields and values for the record. For example, {'field_1':'value_1', 'field_2':'value_2'}. + */ + @JsonProperty("fields") + public Optional> getFields() { + return fields; + } + + /** + * @return Fields and tokens for the record. For example, {'field_1':'token_1', 'field_2':'token_2'}. + */ + @JsonProperty("tokens") + public Optional> getTokens() { + return tokens; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1FieldRecords && equalTo((V1FieldRecords) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1FieldRecords other) { + return fields.equals(other.fields) && tokens.equals(other.tokens); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.fields, this.tokens); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> fields = Optional.empty(); + + private Optional> tokens = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1FieldRecords other) { + fields(other.getFields()); + tokens(other.getTokens()); + return this; + } + + /** + *

Fields and values for the record. For example, {'field_1':'value_1', 'field_2':'value_2'}.

+ */ + @JsonSetter(value = "fields", nulls = Nulls.SKIP) + public Builder fields(Optional> fields) { + this.fields = fields; + return this; + } + + public Builder fields(Map fields) { + this.fields = Optional.ofNullable(fields); + return this; + } + + /** + *

Fields and tokens for the record. For example, {'field_1':'token_1', 'field_2':'token_2'}.

+ */ + @JsonSetter(value = "tokens", nulls = Nulls.SKIP) + public Builder tokens(Optional> tokens) { + this.tokens = tokens; + return this; + } + + public Builder tokens(Map tokens) { + this.tokens = Optional.ofNullable(tokens); + return this; + } + + public V1FieldRecords build() { + return new V1FieldRecords(fields, tokens, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1FileAvScanStatus.java b/src/main/java/com/skyflow/generated/rest/types/V1FileAvScanStatus.java new file mode 100644 index 00000000..afe545fe --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1FileAvScanStatus.java @@ -0,0 +1,38 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum V1FileAvScanStatus { + SCAN_NONE("SCAN_NONE"), + + SCAN_CLEAN("SCAN_CLEAN"), + + SCAN_INFECTED("SCAN_INFECTED"), + + SCAN_DELETED("SCAN_DELETED"), + + SCAN_ERROR("SCAN_ERROR"), + + SCAN_PENDING("SCAN_PENDING"), + + SCAN_UNSCANNABLE("SCAN_UNSCANNABLE"), + + SCAN_FILE_NOT_FOUND("SCAN_FILE_NOT_FOUND"), + + SCAN_INVALID("SCAN_INVALID"); + + private final String value; + + V1FileAvScanStatus(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1FileDataFormat.java b/src/main/java/com/skyflow/generated/rest/types/V1FileDataFormat.java new file mode 100644 index 00000000..a384af7f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1FileDataFormat.java @@ -0,0 +1,58 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum V1FileDataFormat { + BMP("bmp"), + + CSV("csv"), + + DOC("doc"), + + DOCX("docx"), + + JPEG("jpeg"), + + JPG("jpg"), + + JSON("json"), + + MP_3("mp3"), + + PDF("pdf"), + + PNG("png"), + + PPT("ppt"), + + PPTX("pptx"), + + TIF("tif"), + + TIFF("tiff"), + + TXT("txt"), + + UNKNOWN("unknown"), + + WAV("wav"), + + XLS("xls"), + + XLSX("xlsx"); + + private final String value; + + V1FileDataFormat(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1GetAuthTokenResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1GetAuthTokenResponse.java new file mode 100644 index 00000000..9b6be70b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1GetAuthTokenResponse.java @@ -0,0 +1,130 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1GetAuthTokenResponse.Builder.class) +public final class V1GetAuthTokenResponse { + private final Optional accessToken; + + private final Optional tokenType; + + private final Map additionalProperties; + + private V1GetAuthTokenResponse( + Optional accessToken, Optional tokenType, Map additionalProperties) { + this.accessToken = accessToken; + this.tokenType = tokenType; + this.additionalProperties = additionalProperties; + } + + /** + * @return AccessToken. + */ + @JsonProperty("accessToken") + public Optional getAccessToken() { + return accessToken; + } + + /** + * @return TokenType : Bearer. + */ + @JsonProperty("tokenType") + public Optional getTokenType() { + return tokenType; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1GetAuthTokenResponse && equalTo((V1GetAuthTokenResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1GetAuthTokenResponse other) { + return accessToken.equals(other.accessToken) && tokenType.equals(other.tokenType); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.accessToken, this.tokenType); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional accessToken = Optional.empty(); + + private Optional tokenType = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1GetAuthTokenResponse other) { + accessToken(other.getAccessToken()); + tokenType(other.getTokenType()); + return this; + } + + /** + *

AccessToken.

+ */ + @JsonSetter(value = "accessToken", nulls = Nulls.SKIP) + public Builder accessToken(Optional accessToken) { + this.accessToken = accessToken; + return this; + } + + public Builder accessToken(String accessToken) { + this.accessToken = Optional.ofNullable(accessToken); + return this; + } + + /** + *

TokenType : Bearer.

+ */ + @JsonSetter(value = "tokenType", nulls = Nulls.SKIP) + public Builder tokenType(Optional tokenType) { + this.tokenType = tokenType; + return this; + } + + public Builder tokenType(String tokenType) { + this.tokenType = Optional.ofNullable(tokenType); + return this; + } + + public V1GetAuthTokenResponse build() { + return new V1GetAuthTokenResponse(accessToken, tokenType, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1GetFileScanStatusResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1GetFileScanStatusResponse.java new file mode 100644 index 00000000..27100e6d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1GetFileScanStatusResponse.java @@ -0,0 +1,96 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1GetFileScanStatusResponse.Builder.class) +public final class V1GetFileScanStatusResponse { + private final Optional avScanStatus; + + private final Map additionalProperties; + + private V1GetFileScanStatusResponse( + Optional avScanStatus, Map additionalProperties) { + this.avScanStatus = avScanStatus; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("av_scan_status") + public Optional getAvScanStatus() { + return avScanStatus; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1GetFileScanStatusResponse && equalTo((V1GetFileScanStatusResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1GetFileScanStatusResponse other) { + return avScanStatus.equals(other.avScanStatus); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.avScanStatus); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional avScanStatus = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1GetFileScanStatusResponse other) { + avScanStatus(other.getAvScanStatus()); + return this; + } + + @JsonSetter(value = "av_scan_status", nulls = Nulls.SKIP) + public Builder avScanStatus(Optional avScanStatus) { + this.avScanStatus = avScanStatus; + return this; + } + + public Builder avScanStatus(V1FileAvScanStatus avScanStatus) { + this.avScanStatus = Optional.ofNullable(avScanStatus); + return this; + } + + public V1GetFileScanStatusResponse build() { + return new V1GetFileScanStatusResponse(avScanStatus, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1GetQueryResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1GetQueryResponse.java new file mode 100644 index 00000000..6a8689ae --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1GetQueryResponse.java @@ -0,0 +1,102 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1GetQueryResponse.Builder.class) +public final class V1GetQueryResponse { + private final Optional> records; + + private final Map additionalProperties; + + private V1GetQueryResponse(Optional> records, Map additionalProperties) { + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return Records returned by the query. + */ + @JsonProperty("records") + public Optional> getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1GetQueryResponse && equalTo((V1GetQueryResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1GetQueryResponse other) { + return records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> records = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1GetQueryResponse other) { + records(other.getRecords()); + return this; + } + + /** + *

Records returned by the query.

+ */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(Optional> records) { + this.records = records; + return this; + } + + public Builder records(List records) { + this.records = Optional.ofNullable(records); + return this; + } + + public V1GetQueryResponse build() { + return new V1GetQueryResponse(records, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1ImageOptions.java b/src/main/java/com/skyflow/generated/rest/types/V1ImageOptions.java new file mode 100644 index 00000000..cd40fb5b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1ImageOptions.java @@ -0,0 +1,132 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1ImageOptions.Builder.class) +public final class V1ImageOptions { + private final Optional outputProcessedImage; + + private final Optional outputOcrText; + + private final Map additionalProperties; + + private V1ImageOptions( + Optional outputProcessedImage, + Optional outputOcrText, + Map additionalProperties) { + this.outputProcessedImage = outputProcessedImage; + this.outputOcrText = outputOcrText; + this.additionalProperties = additionalProperties; + } + + /** + * @return If true, includes processed image in the output. + */ + @JsonProperty("output_processed_image") + public Optional getOutputProcessedImage() { + return outputProcessedImage; + } + + /** + * @return If true, includes OCR text output in the response. + */ + @JsonProperty("output_ocr_text") + public Optional getOutputOcrText() { + return outputOcrText; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1ImageOptions && equalTo((V1ImageOptions) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1ImageOptions other) { + return outputProcessedImage.equals(other.outputProcessedImage) && outputOcrText.equals(other.outputOcrText); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.outputProcessedImage, this.outputOcrText); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional outputProcessedImage = Optional.empty(); + + private Optional outputOcrText = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1ImageOptions other) { + outputProcessedImage(other.getOutputProcessedImage()); + outputOcrText(other.getOutputOcrText()); + return this; + } + + /** + *

If true, includes processed image in the output.

+ */ + @JsonSetter(value = "output_processed_image", nulls = Nulls.SKIP) + public Builder outputProcessedImage(Optional outputProcessedImage) { + this.outputProcessedImage = outputProcessedImage; + return this; + } + + public Builder outputProcessedImage(Boolean outputProcessedImage) { + this.outputProcessedImage = Optional.ofNullable(outputProcessedImage); + return this; + } + + /** + *

If true, includes OCR text output in the response.

+ */ + @JsonSetter(value = "output_ocr_text", nulls = Nulls.SKIP) + public Builder outputOcrText(Optional outputOcrText) { + this.outputOcrText = outputOcrText; + return this; + } + + public Builder outputOcrText(Boolean outputOcrText) { + this.outputOcrText = Optional.ofNullable(outputOcrText); + return this; + } + + public V1ImageOptions build() { + return new V1ImageOptions(outputProcessedImage, outputOcrText, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1InsertRecordResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1InsertRecordResponse.java new file mode 100644 index 00000000..724bee91 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1InsertRecordResponse.java @@ -0,0 +1,103 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1InsertRecordResponse.Builder.class) +public final class V1InsertRecordResponse { + private final Optional> records; + + private final Map additionalProperties; + + private V1InsertRecordResponse( + Optional> records, Map additionalProperties) { + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return Identifiers for the inserted records. + */ + @JsonProperty("records") + public Optional> getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1InsertRecordResponse && equalTo((V1InsertRecordResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1InsertRecordResponse other) { + return records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> records = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1InsertRecordResponse other) { + records(other.getRecords()); + return this; + } + + /** + *

Identifiers for the inserted records.

+ */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(Optional> records) { + this.records = records; + return this; + } + + public Builder records(List records) { + this.records = Optional.ofNullable(records); + return this; + } + + public V1InsertRecordResponse build() { + return new V1InsertRecordResponse(records, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1Locations.java b/src/main/java/com/skyflow/generated/rest/types/V1Locations.java new file mode 100644 index 00000000..ef1593ca --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1Locations.java @@ -0,0 +1,193 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1Locations.Builder.class) +public final class V1Locations { + private final Optional startIndex; + + private final Optional endIndex; + + private final Optional startIndexProcessed; + + private final Optional endIndexProcessed; + + private final Map additionalProperties; + + private V1Locations( + Optional startIndex, + Optional endIndex, + Optional startIndexProcessed, + Optional endIndexProcessed, + Map additionalProperties) { + this.startIndex = startIndex; + this.endIndex = endIndex; + this.startIndexProcessed = startIndexProcessed; + this.endIndexProcessed = endIndexProcessed; + this.additionalProperties = additionalProperties; + } + + /** + * @return Index of the first character of the string in the original text. + */ + @JsonProperty("start_index") + public Optional getStartIndex() { + return startIndex; + } + + /** + * @return Index of the last character of the string in the original text. + */ + @JsonProperty("end_index") + public Optional getEndIndex() { + return endIndex; + } + + /** + * @return Index of the first character of the string in the processed text. + */ + @JsonProperty("start_index_processed") + public Optional getStartIndexProcessed() { + return startIndexProcessed; + } + + /** + * @return Index of the last character of the string in the processed text. + */ + @JsonProperty("end_index_processed") + public Optional getEndIndexProcessed() { + return endIndexProcessed; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1Locations && equalTo((V1Locations) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1Locations other) { + return startIndex.equals(other.startIndex) + && endIndex.equals(other.endIndex) + && startIndexProcessed.equals(other.startIndexProcessed) + && endIndexProcessed.equals(other.endIndexProcessed); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.startIndex, this.endIndex, this.startIndexProcessed, this.endIndexProcessed); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional startIndex = Optional.empty(); + + private Optional endIndex = Optional.empty(); + + private Optional startIndexProcessed = Optional.empty(); + + private Optional endIndexProcessed = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1Locations other) { + startIndex(other.getStartIndex()); + endIndex(other.getEndIndex()); + startIndexProcessed(other.getStartIndexProcessed()); + endIndexProcessed(other.getEndIndexProcessed()); + return this; + } + + /** + *

Index of the first character of the string in the original text.

+ */ + @JsonSetter(value = "start_index", nulls = Nulls.SKIP) + public Builder startIndex(Optional startIndex) { + this.startIndex = startIndex; + return this; + } + + public Builder startIndex(Integer startIndex) { + this.startIndex = Optional.ofNullable(startIndex); + return this; + } + + /** + *

Index of the last character of the string in the original text.

+ */ + @JsonSetter(value = "end_index", nulls = Nulls.SKIP) + public Builder endIndex(Optional endIndex) { + this.endIndex = endIndex; + return this; + } + + public Builder endIndex(Integer endIndex) { + this.endIndex = Optional.ofNullable(endIndex); + return this; + } + + /** + *

Index of the first character of the string in the processed text.

+ */ + @JsonSetter(value = "start_index_processed", nulls = Nulls.SKIP) + public Builder startIndexProcessed(Optional startIndexProcessed) { + this.startIndexProcessed = startIndexProcessed; + return this; + } + + public Builder startIndexProcessed(Integer startIndexProcessed) { + this.startIndexProcessed = Optional.ofNullable(startIndexProcessed); + return this; + } + + /** + *

Index of the last character of the string in the processed text.

+ */ + @JsonSetter(value = "end_index_processed", nulls = Nulls.SKIP) + public Builder endIndexProcessed(Optional endIndexProcessed) { + this.endIndexProcessed = endIndexProcessed; + return this; + } + + public Builder endIndexProcessed(Integer endIndexProcessed) { + this.endIndexProcessed = Optional.ofNullable(endIndexProcessed); + return this; + } + + public V1Locations build() { + return new V1Locations(startIndex, endIndex, startIndexProcessed, endIndexProcessed, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1MemberType.java b/src/main/java/com/skyflow/generated/rest/types/V1MemberType.java new file mode 100644 index 00000000..dacca1b9 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1MemberType.java @@ -0,0 +1,26 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum V1MemberType { + NONE("NONE"), + + USER("USER"), + + SERVICE_ACCOUNT("SERVICE_ACCOUNT"); + + private final String value; + + V1MemberType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1PdfConfig.java b/src/main/java/com/skyflow/generated/rest/types/V1PdfConfig.java new file mode 100644 index 00000000..8731c1b9 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1PdfConfig.java @@ -0,0 +1,95 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1PdfConfig.Builder.class) +public final class V1PdfConfig { + private final Optional options; + + private final Map additionalProperties; + + private V1PdfConfig(Optional options, Map additionalProperties) { + this.options = options; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("options") + public Optional getOptions() { + return options; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1PdfConfig && equalTo((V1PdfConfig) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1PdfConfig other) { + return options.equals(other.options); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.options); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional options = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1PdfConfig other) { + options(other.getOptions()); + return this; + } + + @JsonSetter(value = "options", nulls = Nulls.SKIP) + public Builder options(Optional options) { + this.options = options; + return this; + } + + public Builder options(V1PdfOptions options) { + this.options = Optional.ofNullable(options); + return this; + } + + public V1PdfConfig build() { + return new V1PdfConfig(options, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1PdfOptions.java b/src/main/java/com/skyflow/generated/rest/types/V1PdfOptions.java new file mode 100644 index 00000000..63de909b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1PdfOptions.java @@ -0,0 +1,130 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1PdfOptions.Builder.class) +public final class V1PdfOptions { + private final Optional density; + + private final Optional maxResolution; + + private final Map additionalProperties; + + private V1PdfOptions( + Optional density, Optional maxResolution, Map additionalProperties) { + this.density = density; + this.maxResolution = maxResolution; + this.additionalProperties = additionalProperties; + } + + /** + * @return Pixel density at which to process the PDF file. + */ + @JsonProperty("density") + public Optional getDensity() { + return density; + } + + /** + * @return Max resolution at which to process the PDF file. + */ + @JsonProperty("max_resolution") + public Optional getMaxResolution() { + return maxResolution; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1PdfOptions && equalTo((V1PdfOptions) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1PdfOptions other) { + return density.equals(other.density) && maxResolution.equals(other.maxResolution); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.density, this.maxResolution); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional density = Optional.empty(); + + private Optional maxResolution = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1PdfOptions other) { + density(other.getDensity()); + maxResolution(other.getMaxResolution()); + return this; + } + + /** + *

Pixel density at which to process the PDF file.

+ */ + @JsonSetter(value = "density", nulls = Nulls.SKIP) + public Builder density(Optional density) { + this.density = density; + return this; + } + + public Builder density(Integer density) { + this.density = Optional.ofNullable(density); + return this; + } + + /** + *

Max resolution at which to process the PDF file.

+ */ + @JsonSetter(value = "max_resolution", nulls = Nulls.SKIP) + public Builder maxResolution(Optional maxResolution) { + this.maxResolution = maxResolution; + return this; + } + + public Builder maxResolution(Integer maxResolution) { + this.maxResolution = Optional.ofNullable(maxResolution); + return this; + } + + public V1PdfOptions build() { + return new V1PdfOptions(density, maxResolution, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1ProcessedFileOutput.java b/src/main/java/com/skyflow/generated/rest/types/V1ProcessedFileOutput.java new file mode 100644 index 00000000..e4117109 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1ProcessedFileOutput.java @@ -0,0 +1,151 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1ProcessedFileOutput.Builder.class) +public final class V1ProcessedFileOutput { + private final Optional outputType; + + private final Optional processedFile; + + private final Optional processedFileType; + + private final Map additionalProperties; + + private V1ProcessedFileOutput( + Optional outputType, + Optional processedFile, + Optional processedFileType, + Map additionalProperties) { + this.outputType = outputType; + this.processedFile = processedFile; + this.processedFileType = processedFileType; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("output_type") + public Optional getOutputType() { + return outputType; + } + + /** + * @return URL or base64-encoded data of the output. + */ + @JsonProperty("processed_file") + public Optional getProcessedFile() { + return processedFile; + } + + @JsonProperty("processed_file_type") + public Optional getProcessedFileType() { + return processedFileType; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1ProcessedFileOutput && equalTo((V1ProcessedFileOutput) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1ProcessedFileOutput other) { + return outputType.equals(other.outputType) + && processedFile.equals(other.processedFile) + && processedFileType.equals(other.processedFileType); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.outputType, this.processedFile, this.processedFileType); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional outputType = Optional.empty(); + + private Optional processedFile = Optional.empty(); + + private Optional processedFileType = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1ProcessedFileOutput other) { + outputType(other.getOutputType()); + processedFile(other.getProcessedFile()); + processedFileType(other.getProcessedFileType()); + return this; + } + + @JsonSetter(value = "output_type", nulls = Nulls.SKIP) + public Builder outputType(Optional outputType) { + this.outputType = outputType; + return this; + } + + public Builder outputType(DetectFileRequestDataType outputType) { + this.outputType = Optional.ofNullable(outputType); + return this; + } + + /** + *

URL or base64-encoded data of the output.

+ */ + @JsonSetter(value = "processed_file", nulls = Nulls.SKIP) + public Builder processedFile(Optional processedFile) { + this.processedFile = processedFile; + return this; + } + + public Builder processedFile(String processedFile) { + this.processedFile = Optional.ofNullable(processedFile); + return this; + } + + @JsonSetter(value = "processed_file_type", nulls = Nulls.SKIP) + public Builder processedFileType(Optional processedFileType) { + this.processedFileType = processedFileType; + return this; + } + + public Builder processedFileType(ProcessedFileOutputProcessedFileType processedFileType) { + this.processedFileType = Optional.ofNullable(processedFileType); + return this; + } + + public V1ProcessedFileOutput build() { + return new V1ProcessedFileOutput(outputType, processedFile, processedFileType, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1RecordMetaProperties.java b/src/main/java/com/skyflow/generated/rest/types/V1RecordMetaProperties.java new file mode 100644 index 00000000..419b8e16 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1RecordMetaProperties.java @@ -0,0 +1,132 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1RecordMetaProperties.Builder.class) +public final class V1RecordMetaProperties { + private final Optional skyflowId; + + private final Optional> tokens; + + private final Map additionalProperties; + + private V1RecordMetaProperties( + Optional skyflowId, + Optional> tokens, + Map additionalProperties) { + this.skyflowId = skyflowId; + this.tokens = tokens; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the inserted record. + */ + @JsonProperty("skyflow_id") + public Optional getSkyflowId() { + return skyflowId; + } + + /** + * @return Tokens for the record. + */ + @JsonProperty("tokens") + public Optional> getTokens() { + return tokens; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1RecordMetaProperties && equalTo((V1RecordMetaProperties) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1RecordMetaProperties other) { + return skyflowId.equals(other.skyflowId) && tokens.equals(other.tokens); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.skyflowId, this.tokens); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional skyflowId = Optional.empty(); + + private Optional> tokens = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1RecordMetaProperties other) { + skyflowId(other.getSkyflowId()); + tokens(other.getTokens()); + return this; + } + + /** + *

ID of the inserted record.

+ */ + @JsonSetter(value = "skyflow_id", nulls = Nulls.SKIP) + public Builder skyflowId(Optional skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + public Builder skyflowId(String skyflowId) { + this.skyflowId = Optional.ofNullable(skyflowId); + return this; + } + + /** + *

Tokens for the record.

+ */ + @JsonSetter(value = "tokens", nulls = Nulls.SKIP) + public Builder tokens(Optional> tokens) { + this.tokens = tokens; + return this; + } + + public Builder tokens(Map tokens) { + this.tokens = Optional.ofNullable(tokens); + return this; + } + + public V1RecordMetaProperties build() { + return new V1RecordMetaProperties(skyflowId, tokens, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1ResponseEntities.java b/src/main/java/com/skyflow/generated/rest/types/V1ResponseEntities.java new file mode 100644 index 00000000..c02ab39f --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1ResponseEntities.java @@ -0,0 +1,218 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1ResponseEntities.Builder.class) +public final class V1ResponseEntities { + private final Optional processedText; + + private final Optional originalText; + + private final Optional location; + + private final Optional bestLabel; + + private final Optional> labels; + + private final Map additionalProperties; + + private V1ResponseEntities( + Optional processedText, + Optional originalText, + Optional location, + Optional bestLabel, + Optional> labels, + Map additionalProperties) { + this.processedText = processedText; + this.originalText = originalText; + this.location = location; + this.bestLabel = bestLabel; + this.labels = labels; + this.additionalProperties = additionalProperties; + } + + /** + * @return Processed text of the entity. + */ + @JsonProperty("processed_text") + public Optional getProcessedText() { + return processedText; + } + + /** + * @return Original text of the entity. + */ + @JsonProperty("original_text") + public Optional getOriginalText() { + return originalText; + } + + @JsonProperty("location") + public Optional getLocation() { + return location; + } + + /** + * @return Highest rated label. + */ + @JsonProperty("best_label") + public Optional getBestLabel() { + return bestLabel; + } + + /** + * @return Labels and their scores. + */ + @JsonProperty("labels") + public Optional> getLabels() { + return labels; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1ResponseEntities && equalTo((V1ResponseEntities) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1ResponseEntities other) { + return processedText.equals(other.processedText) + && originalText.equals(other.originalText) + && location.equals(other.location) + && bestLabel.equals(other.bestLabel) + && labels.equals(other.labels); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.processedText, this.originalText, this.location, this.bestLabel, this.labels); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional processedText = Optional.empty(); + + private Optional originalText = Optional.empty(); + + private Optional location = Optional.empty(); + + private Optional bestLabel = Optional.empty(); + + private Optional> labels = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1ResponseEntities other) { + processedText(other.getProcessedText()); + originalText(other.getOriginalText()); + location(other.getLocation()); + bestLabel(other.getBestLabel()); + labels(other.getLabels()); + return this; + } + + /** + *

Processed text of the entity.

+ */ + @JsonSetter(value = "processed_text", nulls = Nulls.SKIP) + public Builder processedText(Optional processedText) { + this.processedText = processedText; + return this; + } + + public Builder processedText(String processedText) { + this.processedText = Optional.ofNullable(processedText); + return this; + } + + /** + *

Original text of the entity.

+ */ + @JsonSetter(value = "original_text", nulls = Nulls.SKIP) + public Builder originalText(Optional originalText) { + this.originalText = originalText; + return this; + } + + public Builder originalText(String originalText) { + this.originalText = Optional.ofNullable(originalText); + return this; + } + + @JsonSetter(value = "location", nulls = Nulls.SKIP) + public Builder location(Optional location) { + this.location = location; + return this; + } + + public Builder location(V1Locations location) { + this.location = Optional.ofNullable(location); + return this; + } + + /** + *

Highest rated label.

+ */ + @JsonSetter(value = "best_label", nulls = Nulls.SKIP) + public Builder bestLabel(Optional bestLabel) { + this.bestLabel = bestLabel; + return this; + } + + public Builder bestLabel(String bestLabel) { + this.bestLabel = Optional.ofNullable(bestLabel); + return this; + } + + /** + *

Labels and their scores.

+ */ + @JsonSetter(value = "labels", nulls = Nulls.SKIP) + public Builder labels(Optional> labels) { + this.labels = labels; + return this; + } + + public Builder labels(Map labels) { + this.labels = Optional.ofNullable(labels); + return this; + } + + public V1ResponseEntities build() { + return new V1ResponseEntities( + processedText, originalText, location, bestLabel, labels, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1TokenizeRecordRequest.java b/src/main/java/com/skyflow/generated/rest/types/V1TokenizeRecordRequest.java new file mode 100644 index 00000000..03c5ef89 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1TokenizeRecordRequest.java @@ -0,0 +1,130 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1TokenizeRecordRequest.Builder.class) +public final class V1TokenizeRecordRequest { + private final Optional value; + + private final Optional columnGroup; + + private final Map additionalProperties; + + private V1TokenizeRecordRequest( + Optional value, Optional columnGroup, Map additionalProperties) { + this.value = value; + this.columnGroup = columnGroup; + this.additionalProperties = additionalProperties; + } + + /** + * @return Existing value to return a token for. + */ + @JsonProperty("value") + public Optional getValue() { + return value; + } + + /** + * @return Name of the column group that the value belongs to. + */ + @JsonProperty("columnGroup") + public Optional getColumnGroup() { + return columnGroup; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1TokenizeRecordRequest && equalTo((V1TokenizeRecordRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1TokenizeRecordRequest other) { + return value.equals(other.value) && columnGroup.equals(other.columnGroup); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.value, this.columnGroup); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional value = Optional.empty(); + + private Optional columnGroup = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1TokenizeRecordRequest other) { + value(other.getValue()); + columnGroup(other.getColumnGroup()); + return this; + } + + /** + *

Existing value to return a token for.

+ */ + @JsonSetter(value = "value", nulls = Nulls.SKIP) + public Builder value(Optional value) { + this.value = value; + return this; + } + + public Builder value(String value) { + this.value = Optional.ofNullable(value); + return this; + } + + /** + *

Name of the column group that the value belongs to.

+ */ + @JsonSetter(value = "columnGroup", nulls = Nulls.SKIP) + public Builder columnGroup(Optional columnGroup) { + this.columnGroup = columnGroup; + return this; + } + + public Builder columnGroup(String columnGroup) { + this.columnGroup = Optional.ofNullable(columnGroup); + return this; + } + + public V1TokenizeRecordRequest build() { + return new V1TokenizeRecordRequest(value, columnGroup, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1TokenizeRecordResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1TokenizeRecordResponse.java new file mode 100644 index 00000000..4cd41dd0 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1TokenizeRecordResponse.java @@ -0,0 +1,101 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1TokenizeRecordResponse.Builder.class) +public final class V1TokenizeRecordResponse { + private final Optional token; + + private final Map additionalProperties; + + private V1TokenizeRecordResponse(Optional token, Map additionalProperties) { + this.token = token; + this.additionalProperties = additionalProperties; + } + + /** + * @return Token corresponding to a value. + */ + @JsonProperty("token") + public Optional getToken() { + return token; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1TokenizeRecordResponse && equalTo((V1TokenizeRecordResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1TokenizeRecordResponse other) { + return token.equals(other.token); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.token); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional token = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1TokenizeRecordResponse other) { + token(other.getToken()); + return this; + } + + /** + *

Token corresponding to a value.

+ */ + @JsonSetter(value = "token", nulls = Nulls.SKIP) + public Builder token(Optional token) { + this.token = token; + return this; + } + + public Builder token(String token) { + this.token = Optional.ofNullable(token); + return this; + } + + public V1TokenizeRecordResponse build() { + return new V1TokenizeRecordResponse(token, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1TokenizeResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1TokenizeResponse.java new file mode 100644 index 00000000..38159283 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1TokenizeResponse.java @@ -0,0 +1,103 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1TokenizeResponse.Builder.class) +public final class V1TokenizeResponse { + private final Optional> records; + + private final Map additionalProperties; + + private V1TokenizeResponse( + Optional> records, Map additionalProperties) { + this.records = records; + this.additionalProperties = additionalProperties; + } + + /** + * @return Tokens corresponding to the specified values. + */ + @JsonProperty("records") + public Optional> getRecords() { + return records; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1TokenizeResponse && equalTo((V1TokenizeResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1TokenizeResponse other) { + return records.equals(other.records); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> records = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1TokenizeResponse other) { + records(other.getRecords()); + return this; + } + + /** + *

Tokens corresponding to the specified values.

+ */ + @JsonSetter(value = "records", nulls = Nulls.SKIP) + public Builder records(Optional> records) { + this.records = records; + return this; + } + + public Builder records(List records) { + this.records = Optional.ofNullable(records); + return this; + } + + public V1TokenizeResponse build() { + return new V1TokenizeResponse(records, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1UpdateRecordResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1UpdateRecordResponse.java new file mode 100644 index 00000000..658926b9 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1UpdateRecordResponse.java @@ -0,0 +1,132 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1UpdateRecordResponse.Builder.class) +public final class V1UpdateRecordResponse { + private final Optional skyflowId; + + private final Optional> tokens; + + private final Map additionalProperties; + + private V1UpdateRecordResponse( + Optional skyflowId, + Optional> tokens, + Map additionalProperties) { + this.skyflowId = skyflowId; + this.tokens = tokens; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the updated record. + */ + @JsonProperty("skyflow_id") + public Optional getSkyflowId() { + return skyflowId; + } + + /** + * @return Tokens for the record. + */ + @JsonProperty("tokens") + public Optional> getTokens() { + return tokens; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1UpdateRecordResponse && equalTo((V1UpdateRecordResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1UpdateRecordResponse other) { + return skyflowId.equals(other.skyflowId) && tokens.equals(other.tokens); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.skyflowId, this.tokens); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional skyflowId = Optional.empty(); + + private Optional> tokens = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1UpdateRecordResponse other) { + skyflowId(other.getSkyflowId()); + tokens(other.getTokens()); + return this; + } + + /** + *

ID of the updated record.

+ */ + @JsonSetter(value = "skyflow_id", nulls = Nulls.SKIP) + public Builder skyflowId(Optional skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + public Builder skyflowId(String skyflowId) { + this.skyflowId = Optional.ofNullable(skyflowId); + return this; + } + + /** + *

Tokens for the record.

+ */ + @JsonSetter(value = "tokens", nulls = Nulls.SKIP) + public Builder tokens(Optional> tokens) { + this.tokens = tokens; + return this; + } + + public Builder tokens(Map tokens) { + this.tokens = Optional.ofNullable(tokens); + return this; + } + + public V1UpdateRecordResponse build() { + return new V1UpdateRecordResponse(skyflowId, tokens, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1VaultFieldMapping.java b/src/main/java/com/skyflow/generated/rest/types/V1VaultFieldMapping.java new file mode 100644 index 00000000..bad4474a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1VaultFieldMapping.java @@ -0,0 +1,163 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1VaultFieldMapping.Builder.class) +public final class V1VaultFieldMapping { + private final Optional cardNumber; + + private final Optional cardLastFourDigits; + + private final Optional cardExpiry; + + private final Map additionalProperties; + + private V1VaultFieldMapping( + Optional cardNumber, + Optional cardLastFourDigits, + Optional cardExpiry, + Map additionalProperties) { + this.cardNumber = cardNumber; + this.cardLastFourDigits = cardLastFourDigits; + this.cardExpiry = cardExpiry; + this.additionalProperties = additionalProperties; + } + + /** + * @return Name of the column that stores the card number. + */ + @JsonProperty("card_number") + public Optional getCardNumber() { + return cardNumber; + } + + /** + * @return Name of the column that stores the card number suffix. + */ + @JsonProperty("card_last_four_digits") + public Optional getCardLastFourDigits() { + return cardLastFourDigits; + } + + /** + * @return Name of the column that stores the expiry date. + */ + @JsonProperty("card_expiry") + public Optional getCardExpiry() { + return cardExpiry; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1VaultFieldMapping && equalTo((V1VaultFieldMapping) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1VaultFieldMapping other) { + return cardNumber.equals(other.cardNumber) + && cardLastFourDigits.equals(other.cardLastFourDigits) + && cardExpiry.equals(other.cardExpiry); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.cardNumber, this.cardLastFourDigits, this.cardExpiry); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional cardNumber = Optional.empty(); + + private Optional cardLastFourDigits = Optional.empty(); + + private Optional cardExpiry = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1VaultFieldMapping other) { + cardNumber(other.getCardNumber()); + cardLastFourDigits(other.getCardLastFourDigits()); + cardExpiry(other.getCardExpiry()); + return this; + } + + /** + *

Name of the column that stores the card number.

+ */ + @JsonSetter(value = "card_number", nulls = Nulls.SKIP) + public Builder cardNumber(Optional cardNumber) { + this.cardNumber = cardNumber; + return this; + } + + public Builder cardNumber(String cardNumber) { + this.cardNumber = Optional.ofNullable(cardNumber); + return this; + } + + /** + *

Name of the column that stores the card number suffix.

+ */ + @JsonSetter(value = "card_last_four_digits", nulls = Nulls.SKIP) + public Builder cardLastFourDigits(Optional cardLastFourDigits) { + this.cardLastFourDigits = cardLastFourDigits; + return this; + } + + public Builder cardLastFourDigits(String cardLastFourDigits) { + this.cardLastFourDigits = Optional.ofNullable(cardLastFourDigits); + return this; + } + + /** + *

Name of the column that stores the expiry date.

+ */ + @JsonSetter(value = "card_expiry", nulls = Nulls.SKIP) + public Builder cardExpiry(Optional cardExpiry) { + this.cardExpiry = cardExpiry; + return this; + } + + public Builder cardExpiry(String cardExpiry) { + this.cardExpiry = Optional.ofNullable(cardExpiry); + return this; + } + + public V1VaultFieldMapping build() { + return new V1VaultFieldMapping(cardNumber, cardLastFourDigits, cardExpiry, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1VaultSchemaConfig.java b/src/main/java/com/skyflow/generated/rest/types/V1VaultSchemaConfig.java new file mode 100644 index 00000000..28a609b6 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1VaultSchemaConfig.java @@ -0,0 +1,155 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1VaultSchemaConfig.Builder.class) +public final class V1VaultSchemaConfig { + private final Optional id; + + private final Optional tableName; + + private final Optional mapping; + + private final Map additionalProperties; + + private V1VaultSchemaConfig( + Optional id, + Optional tableName, + Optional mapping, + Map additionalProperties) { + this.id = id; + this.tableName = tableName; + this.mapping = mapping; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID of the vault that stores card details. + */ + @JsonProperty("id") + public Optional getId() { + return id; + } + + /** + * @return Name of the table that stores card details. + */ + @JsonProperty("table_name") + public Optional getTableName() { + return tableName; + } + + @JsonProperty("mapping") + public Optional getMapping() { + return mapping; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1VaultSchemaConfig && equalTo((V1VaultSchemaConfig) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1VaultSchemaConfig other) { + return id.equals(other.id) && tableName.equals(other.tableName) && mapping.equals(other.mapping); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.id, this.tableName, this.mapping); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional id = Optional.empty(); + + private Optional tableName = Optional.empty(); + + private Optional mapping = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1VaultSchemaConfig other) { + id(other.getId()); + tableName(other.getTableName()); + mapping(other.getMapping()); + return this; + } + + /** + *

ID of the vault that stores card details.

+ */ + @JsonSetter(value = "id", nulls = Nulls.SKIP) + public Builder id(Optional id) { + this.id = id; + return this; + } + + public Builder id(String id) { + this.id = Optional.ofNullable(id); + return this; + } + + /** + *

Name of the table that stores card details.

+ */ + @JsonSetter(value = "table_name", nulls = Nulls.SKIP) + public Builder tableName(Optional tableName) { + this.tableName = tableName; + return this; + } + + public Builder tableName(String tableName) { + this.tableName = Optional.ofNullable(tableName); + return this; + } + + @JsonSetter(value = "mapping", nulls = Nulls.SKIP) + public Builder mapping(Optional mapping) { + this.mapping = mapping; + return this; + } + + public Builder mapping(V1VaultFieldMapping mapping) { + this.mapping = Optional.ofNullable(mapping); + return this; + } + + public V1VaultSchemaConfig build() { + return new V1VaultSchemaConfig(id, tableName, mapping, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/logs/ErrorLogs.java b/src/main/java/com/skyflow/logs/ErrorLogs.java index ad588aa0..3415860c 100644 --- a/src/main/java/com/skyflow/logs/ErrorLogs.java +++ b/src/main/java/com/skyflow/logs/ErrorLogs.java @@ -108,6 +108,24 @@ public enum ErrorLogs { EMPTY_REQUEST_BODY("Invalid %s1 request. Request body can not be empty."), INVALID_REQUEST_BODY("Invalid %s1 request. Request body can not be empty."), INVOKE_CONNECTION_REQUEST_REJECTED("Invoke connection request resulted in failure."), + + + // detect interface + INVALID_TEXT_IN_DEIDENTIFY("Invalid %s1 request. The text field is required and must be a non-empty string. Specify a valid text."), + DEIDENTIFY_TEXT_REQUEST_REJECTED("DeIdentify text request resulted in failure."), + INVALID_TEXT_IN_REIDENTIFY("Invalid %s1 request. The text field is required and must be a non-empty string. Specify a valid text."), + REIDENTIFY_TEXT_REQUEST_REJECTED("ReIdentify text request resulted in failure."), + DEIDENTIFY_FILE_REQUEST_REJECTED("DeIdentify file request resulted in failure."), + GET_DETECT_RUN_REQUEST_REJECTED("Get detect run request resulted in failure."), + INVALID_NULL_FILE_IN_DEIDENTIFY_FILE("Invalid %s1 request. The file field is required and must not be null. Specify a valid file."), + FILE_NOT_FOUND_TO_DEIDENTIFY("Invalid %s1 request. The file field is required and must not be empty. Specify a valid file."), + FILE_NOT_READABLE_TO_DEIDENTIFY("Invalid %s1 request. The file is not readable. Please check the file permissions or path."), + INVALID_PIXEL_DENSITY_TO_DEIDENTIFY_FILE("Invalid %s1 request. Pixel density must be a positive integer greater than 0. Specify a valid pixel density."), + INVALID_MAX_RESOLUTION("Invalid %s1 request. Max resolution must be a positive integer greater than 0. Specify a valid max resolution."), + INVALID_BLEEP_TO_DEIDENTIFY_AUDIO("Invalid %s1 request. Specify a valid bleep as AudioBleep"), + OUTPUT_DIRECTORY_NOT_FOUND("Invalid %s1 request. The output directory does not exist. Please specify a valid output directory."), + INVALID_PERMISSIONS_FOR_OUTPUT_DIRECTORY("Invalid %s1 request. The output directory is not writable. Please check the permissions or specify a valid output directory."), + EMPTY_FILE_AND_FILE_PATH_IN_DEIDENTIFY_FILE("Invalid %s1 request. The file and file path fields are both empty. Specify a valid file object or file path."), ; private final String log; diff --git a/src/main/java/com/skyflow/logs/InfoLogs.java b/src/main/java/com/skyflow/logs/InfoLogs.java index 5beecfd3..efd81a49 100644 --- a/src/main/java/com/skyflow/logs/InfoLogs.java +++ b/src/main/java/com/skyflow/logs/InfoLogs.java @@ -7,6 +7,7 @@ public enum InfoLogs { VALIDATING_CONNECTION_CONFIG("Validating connection config."), UNABLE_TO_GENERATE_SDK_METRIC("Unable to generate %s1 metric."), VAULT_CONTROLLER_INITIALIZED("Initialized vault controller with vault ID %s1."), + DETECT_CONTROLLER_INITIALIZED("Initialized detect controller with vault ID %s1."), CONNECTION_CONTROLLER_INITIALIZED("Initialized connection controller with connection ID %s1."), LOGGER_SETUP_DONE("Set up logger."), CURRENT_LOG_LEVEL("Current log level is %s1."), @@ -68,10 +69,29 @@ public enum InfoLogs { TOKENIZE_REQUEST_RESOLVED("Tokenize request resolved."), TOKENIZE_SUCCESS("Data tokenized."), + // Invoke connection interface INVOKE_CONNECTION_TRIGGERED("Invoke connection method triggered."), VALIDATING_INVOKE_CONNECTION_REQUEST("Validating invoke connection request."), - INVOKE_CONNECTION_REQUEST_RESOLVED("Invoke connection request resolved."); + INVOKE_CONNECTION_REQUEST_RESOLVED("Invoke connection request resolved."), + + // detect + VALIDATE_DEIDENTIFY_TEXT_REQUEST("Validating deidentify text request."), + DEIDENTIFY_TEXT_SUCCESS("Text data de-identified."), + DEIDENTIFY_TEXT_TRIGGERED("DeIdentify text method triggered."), + DEIDENTIFY_TEXT_REQUEST_RESOLVED("DeIdentify text request resolved."), + VALIDATE_REIDENTIFY_TEXT_REQUEST("Validating reidentify text request."), + REIDENTIFY_TEXT_TRIGGERED("ReIdentify text method triggered."), + REIDENTIFY_TEXT_REQUEST_RESOLVED("ReIdentify text request resolved."), + DEIDENTIFY_FILE_TRIGGERED("DeIdentify file method triggered."), + VALIDATE_DEIDENTIFY_FILE_REQUEST("Validating deidentify file request."), + DEIDENTIFY_FILE_REQUEST_RESOLVED("DeIdentify file request resolved."), + DEIDENTIFY_FILE_SUCCESS("File deidentified successfully."), + GET_DETECT_RUN_TRIGGERED("Get detect run method triggered."), + VALIDATE_GET_DETECT_RUN_REQUEST("Validating get detect run request."), + REIDENTIFY_TEXT_SUCCESS("Text data re-identified."), + ; + private final String log; diff --git a/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java b/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java index e6e4b534..23d09ab8 100644 --- a/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java +++ b/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java @@ -1,17 +1,15 @@ package com.skyflow.serviceaccount.util; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; +import com.google.gson.*; import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.ApiException; -import com.skyflow.generated.rest.api.AuthenticationApi; -import com.skyflow.generated.rest.models.V1GetAuthTokenRequest; -import com.skyflow.generated.rest.models.V1GetAuthTokenResponse; +import com.skyflow.generated.rest.ApiClientBuilder; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.resources.authentication.AuthenticationClient; +import com.skyflow.generated.rest.resources.authentication.requests.V1GetAuthTokenRequest; +import com.skyflow.generated.rest.types.V1GetAuthTokenResponse; import com.skyflow.logs.ErrorLogs; import com.skyflow.logs.InfoLogs; import com.skyflow.utils.Constants; @@ -30,8 +28,8 @@ import java.util.Objects; public class BearerToken { - private static final ApiClient apiClient = new ApiClient(); - private static final AuthenticationApi authenticationApi = new AuthenticationApi(apiClient); + private static final Gson gson = new GsonBuilder().serializeNulls().create(); + private static final ApiClientBuilder apiClientBuilder = new ApiClientBuilder(); private final File credentialsFile; private final String credentialsString; private final String ctx; @@ -125,23 +123,24 @@ private static V1GetAuthTokenResponse getBearerTokenFromCredentials( ); String basePath = Utils.getBaseURL(tokenURI.getAsString()); - apiClient.setBasePath(basePath); + apiClientBuilder.url(basePath); + ApiClient apiClient = apiClientBuilder.token("token").build(); + AuthenticationClient authenticationApi = apiClient.authentication(); - V1GetAuthTokenRequest body = new V1GetAuthTokenRequest(); - body.setGrantType(Constants.GRANT_TYPE); - body.setAssertion(signedUserJWT); + V1GetAuthTokenRequest._FinalStage authTokenBuilder = V1GetAuthTokenRequest.builder().grantType(Constants.GRANT_TYPE).assertion(signedUserJWT); if (roles != null) { String scopedRoles = getScopeUsingRoles(roles); - body.setScope(scopedRoles); + authTokenBuilder.scope(scopedRoles); } - return authenticationApi.authenticationServiceGetAuthToken(body); + return authenticationApi.authenticationServiceGetAuthToken(authTokenBuilder.build()); } catch (MalformedURLException e) { LogUtil.printErrorLog(ErrorLogs.INVALID_TOKEN_URI.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidTokenUri.getMessage()); - } catch (ApiException e) { + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); LogUtil.printErrorLog(ErrorLogs.BEARER_TOKEN_REJECTED.getLog()); - throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); } } @@ -177,10 +176,10 @@ public synchronized String getBearerToken() throws SkyflowException { String accessToken = null; if (this.credentialsFile != null && Objects.equals(this.credentialsType, "FILE")) { response = generateBearerTokenFromCredentials(this.credentialsFile, this.ctx, this.roles); - accessToken = response.getAccessToken(); + accessToken = response.getAccessToken().get(); } else if (this.credentialsString != null && Objects.equals(this.credentialsType, "STRING")) { response = generateBearerTokenFromCredentialString(this.credentialsString, this.ctx, this.roles); - accessToken = response.getAccessToken(); + accessToken = response.getAccessToken().get(); } LogUtil.printInfoLog(InfoLogs.GET_BEARER_TOKEN_SUCCESS.getLog()); return accessToken; diff --git a/src/main/java/com/skyflow/utils/Constants.java b/src/main/java/com/skyflow/utils/Constants.java index 500d8c94..b9264a22 100644 --- a/src/main/java/com/skyflow/utils/Constants.java +++ b/src/main/java/com/skyflow/utils/Constants.java @@ -25,5 +25,7 @@ public final class Constants { public static final String SDK_AUTH_HEADER_KEY = "x-skyflow-authorization"; public static final String SDK_METRICS_HEADER_KEY = "sky-metadata"; public static final String REQUEST_ID_HEADER_KEY = "x-request-id"; - public static final String ERROR_FROM_CLIENT_HEADER_KEY = "error-from-client"; + public static final String PROCESSED_FILE_NAME_PREFIX = "processed-"; + public static final String ERROR_FROM_CLIENT_HEADER_KEY = "eror-from-client"; + public static final String DEIDENTIFIED_FILE_PREFIX = "deidentified";; } diff --git a/src/main/java/com/skyflow/utils/validations/Validations.java b/src/main/java/com/skyflow/utils/validations/Validations.java index 5e192349..841c03b6 100644 --- a/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/src/main/java/com/skyflow/utils/validations/Validations.java @@ -17,11 +17,13 @@ import com.skyflow.utils.logger.LogUtil; import com.skyflow.vault.connection.InvokeConnectionRequest; import com.skyflow.vault.data.*; +import com.skyflow.vault.detect.*; import com.skyflow.vault.tokens.ColumnValue; import com.skyflow.vault.tokens.DetokenizeData; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.TokenizeRequest; +import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; @@ -183,12 +185,12 @@ public static void validateCredentials(Credentials credentials) throws SkyflowEx LogUtil.printErrorLog(ErrorLogs.EMPTY_API_KEY_VALUE.getLog()); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyApikey.getMessage()); } else { - Pattern pattern = Pattern.compile(Constants.API_KEY_REGEX); - Matcher matcher = pattern.matcher(apiKey); - if (!matcher.matches()) { - LogUtil.printErrorLog(ErrorLogs.INVALID_API_KEY.getLog()); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidApikey.getMessage()); - } + Pattern pattern = Pattern.compile(Constants.API_KEY_REGEX); + Matcher matcher = pattern.matcher(apiKey); + if (!matcher.matches()) { + LogUtil.printErrorLog(ErrorLogs.INVALID_API_KEY.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidApikey.getMessage()); + } } } else if (roles != null) { if (roles.isEmpty()) { @@ -685,6 +687,28 @@ public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) thro } } + public static void validateDeidentifyTextRequest(DeidentifyTextRequest deidentifyTextRequest) throws SkyflowException { + // Validate required fields + String deidentifyText = deidentifyTextRequest.getText(); + if (deidentifyText == null || deidentifyText.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_TEXT_IN_DEIDENTIFY.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidTextInDeIdentify.getMessage()); + } + } + + public static void validateReidentifyTextRequest(ReidentifyTextRequest reidentifyTextRequest) throws SkyflowException { + // Validate required fields + String reidentifyText = reidentifyTextRequest.getText(); + if (reidentifyText == null || reidentifyText.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_TEXT_IN_REIDENTIFY.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidTextInReIdentify.getMessage()); + } + } + private static boolean isInvalidURL(String configURL) { try { URL url = new URL(configURL); @@ -755,4 +779,114 @@ private static void validateTokensMapWithTokenStrict( } } } + + public static void validateDeidentifyFileRequest(DeidentifyFileRequest request) throws SkyflowException { + if (request == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_REQUEST_BODY.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestBody.getMessage()); + } + + File file = request.getFileInput().getFile(); + String filePath = request.getFileInput().getFilePath(); + + if (file == null && filePath == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_FILE_AND_FILE_PATH_IN_DEIDENTIFY_FILE.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyFileAndFilePathInDeIdentifyFile.getMessage()); + } + + if (filePath != null && file != null) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.BothFileAndFilePathProvided.getMessage()); + } + + if (filePath != null && filePath.trim().isEmpty()){ + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidFilePath.getMessage()); + } + + if (file != null && (!file.exists() || !file.isFile())) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.FILE_NOT_FOUND_TO_DEIDENTIFY.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FileNotFoundToDeidentify.getMessage()); + } + if (file != null && !file.canRead()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.FILE_NOT_READABLE_TO_DEIDENTIFY.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FileNotReadableToDeidentify.getMessage()); + } + + + // Validate pixelDensity and maxResolution + if (request.getPixelDensity() != null && request.getPixelDensity().doubleValue() <= 0) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_PIXEL_DENSITY_TO_DEIDENTIFY_FILE.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidPixelDensityToDeidentifyFile.getMessage()); + } + if (request.getMaxResolution() != null && request.getMaxResolution().doubleValue() <= 0) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_MAX_RESOLUTION.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidMaxResolution.getMessage()); + } + + // Validate AudioBleep + if (request.getBleep() != null) { + if (request.getBleep().getFrequency() == null || request.getBleep().getFrequency() <= 0) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_BLEEP_TO_DEIDENTIFY_AUDIO.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); + } + if (request.getBleep().getGain() == null) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); + } + if (request.getBleep().getStartPadding() == null || request.getBleep().getStartPadding() < 0) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); + } + if (request.getBleep().getStopPadding() == null || request.getBleep().getStopPadding() < 0) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); + } + } + + // Validate outputDirectory if provided + if (request.getOutputDirectory() != null) { + File outDir = new File(request.getOutputDirectory()); + if (!outDir.exists() || !outDir.isDirectory()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.OUTPUT_DIRECTORY_NOT_FOUND.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.OutputDirectoryNotFound.getMessage()); + } + if (!outDir.canWrite()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_PERMISSIONS_FOR_OUTPUT_DIRECTORY.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidPermission.getMessage()); + } + } + + // Validate waitTime if provided + if (request.getWaitTime() != null && request.getWaitTime() <= 0) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidWaitTime.getMessage()); + } + if(request.getWaitTime() > 64) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.WaitTimeExceedsLimit.getMessage()); + } + } + + public static void validateGetDetectRunRequest(GetDetectRunRequest request) throws SkyflowException { + if (request == null) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestBody.getMessage()); + } + + String runId = request.getRunId(); + if (runId == null || runId.trim().isEmpty()) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidOrEmptyRunId.getMessage()); + } + } } diff --git a/src/main/java/com/skyflow/vault/controller/AuditController.java b/src/main/java/com/skyflow/vault/controller/AuditController.java index 9d605e6c..2faa04a6 100644 --- a/src/main/java/com/skyflow/vault/controller/AuditController.java +++ b/src/main/java/com/skyflow/vault/controller/AuditController.java @@ -1,15 +1,13 @@ package com.skyflow.vault.controller; import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.api.AuditApi; import com.skyflow.vault.audit.ListEventRequest; import com.skyflow.vault.audit.ListEventResponse; public class AuditController { - private final AuditApi auditApi; public AuditController(ApiClient apiClient) { - this.auditApi = new AuditApi(apiClient); + } // Check for correct return type in python interfaces diff --git a/src/main/java/com/skyflow/vault/controller/BinLookupController.java b/src/main/java/com/skyflow/vault/controller/BinLookupController.java index e5d9cc62..4eb7a1c8 100644 --- a/src/main/java/com/skyflow/vault/controller/BinLookupController.java +++ b/src/main/java/com/skyflow/vault/controller/BinLookupController.java @@ -1,15 +1,12 @@ package com.skyflow.vault.controller; import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.api.BinLookupApi; import com.skyflow.vault.bin.GetBinRequest; import com.skyflow.vault.bin.GetBinResponse; public class BinLookupController { - private BinLookupApi binLookupApi; public BinLookupController(ApiClient apiClient) { - this.binLookupApi = new BinLookupApi(apiClient); } public GetBinResponse get(GetBinRequest getBinRequest) { diff --git a/src/main/java/com/skyflow/vault/controller/DetectController.java b/src/main/java/com/skyflow/vault/controller/DetectController.java index 5b507d89..411658ae 100644 --- a/src/main/java/com/skyflow/vault/controller/DetectController.java +++ b/src/main/java/com/skyflow/vault/controller/DetectController.java @@ -1,26 +1,375 @@ package com.skyflow.vault.controller; -import com.skyflow.generated.rest.ApiClient; -import com.skyflow.vault.detect.DeIdentifyRequest; -import com.skyflow.vault.detect.DeIdentifyResponse; +import com.google.gson.*; +import com.skyflow.VaultClient; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.DeidentifyFileStatus; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.resources.files.requests.*; +import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; +import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; +import com.skyflow.generated.rest.types.*; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.Constants; +import com.skyflow.utils.logger.LogUtil; +import com.skyflow.utils.validations.Validations; +import com.skyflow.vault.detect.*; +import com.skyflow.vault.detect.DeidentifyFileRequest; +import com.skyflow.vault.detect.DeidentifyFileResponse; +import com.skyflow.vault.detect.DeidentifyTextRequest; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.*; + +public final class DetectController extends VaultClient { + private static final Gson gson = new GsonBuilder().serializeNulls().create(); + + public DetectController(VaultConfig vaultConfig, Credentials credentials) { + super(vaultConfig, credentials); + } + + public DeidentifyTextResponse deidentifyText(DeidentifyTextRequest deidentifyTextRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_TEXT_TRIGGERED.getLog()); + DeidentifyStringResponse deidentifyStringResponse = null; + DeidentifyTextResponse deidentifyTextResponse = null; + try { + // Validate the request + LogUtil.printInfoLog(InfoLogs.VALIDATE_DEIDENTIFY_TEXT_REQUEST.getLog()); + Validations.validateDeidentifyTextRequest(deidentifyTextRequest); + setBearerToken(); + + // Parse the request to DeidentifyStringRequest + String vaultId = super.getVaultConfig().getVaultId(); + DeidentifyStringRequest request = getDeidentifyStringRequest(deidentifyTextRequest, vaultId); + + // Call the API to de-identify the string + deidentifyStringResponse = super.getDetectTextApi().deidentifyString(request); + + // Parse the response to DeIdentifyTextResponse + deidentifyTextResponse = getDeIdentifyTextResponse(deidentifyStringResponse); + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_TEXT_REQUEST_RESOLVED.getLog()); + } catch (ApiClientApiException ex) { + String bodyString = gson.toJson(ex.body()); + LogUtil.printErrorLog(ErrorLogs.DEIDENTIFY_TEXT_REQUEST_REJECTED.getLog()); + throw new SkyflowException(ex.statusCode(), ex, ex.headers(), bodyString); + } + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_TEXT_SUCCESS.getLog()); + return deidentifyTextResponse; + } + + public ReidentifyTextResponse reidentifyText(ReidentifyTextRequest reidentifyTextRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.REIDENTIFY_TEXT_TRIGGERED.getLog()); + ReidentifyTextResponse reidentifyTextResponse = null; + try { + // Validate the request + LogUtil.printInfoLog(InfoLogs.VALIDATE_REIDENTIFY_TEXT_REQUEST.getLog()); + Validations.validateReidentifyTextRequest(reidentifyTextRequest); + setBearerToken(); + // Parse the request to ReidentifyTextRequest + String vaultId = super.getVaultConfig().getVaultId(); + ReidentifyStringRequest request = getReidentifyStringRequest(reidentifyTextRequest, vaultId); + + // Call the API to re-identify the string + ReidentifyStringResponse reidentifyStringResponse = super.getDetectTextApi().reidentifyString(request); + + // Parse the response to ReidentifyTextResponse + reidentifyTextResponse = new ReidentifyTextResponse(reidentifyStringResponse.getText().orElse(null)); + LogUtil.printInfoLog(InfoLogs.REIDENTIFY_TEXT_REQUEST_RESOLVED.getLog()); + } catch (ApiClientApiException ex) { + String bodyString = gson.toJson(ex.body()); + LogUtil.printErrorLog(ErrorLogs.REIDENTIFY_TEXT_REQUEST_REJECTED.getLog()); + throw new SkyflowException(ex.statusCode(), ex, ex.headers(), bodyString); + } + LogUtil.printInfoLog(InfoLogs.REIDENTIFY_TEXT_SUCCESS.getLog()); + return reidentifyTextResponse; + } + + public DeidentifyFileResponse deidentifyFile(DeidentifyFileRequest request) throws SkyflowException { + DeidentifyFileResponse response; + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_FILE_TRIGGERED.getLog()); + try { + LogUtil.printInfoLog(InfoLogs.VALIDATE_DEIDENTIFY_FILE_REQUEST.getLog()); + Validations.validateDeidentifyFileRequest(request); + setBearerToken(); + + String vaultId = super.getVaultConfig().getVaultId(); + + File file; + if (request.getFileInput().getFilePath() != null) { + file = new File(request.getFileInput().getFilePath()); + } else { + file = request.getFileInput().getFile(); + } + String fileName = file.getName(); + String fileExtension = getFileExtension(fileName); + String base64Content; + + try { + base64Content = encodeFileToBase64(file); + } catch (IOException ioe) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FailedToEncodeFile.getMessage()); + } + + + com.skyflow.generated.rest.types.DeidentifyFileResponse apiResponse = processFileByType(fileExtension, base64Content, request, vaultId); + try { + response = pollForResults(apiResponse.getRunId(), request.getWaitTime()); + } catch (Exception ex) { + throw new SkyflowException(ErrorCode.SERVER_ERROR.getCode(), ErrorMessage.PollingForResultsFailed.getMessage()); + } + + if (DeidentifyFileStatus.SUCCESS.value().equalsIgnoreCase(response.getStatus())) { + String base64File = response.getFileBase64(); + if (base64File != null) { + byte[] decodedBytes = Base64.getDecoder().decode(base64File); + String outputDir = request.getOutputDirectory(); + String outputFileName = Constants.PROCESSED_FILE_NAME_PREFIX + fileName; + File outputFile; + if (outputDir != null && !outputDir.isEmpty()) { + outputFile = new File(outputDir, outputFileName); + } else { + outputFile = new File(outputFileName); + } + try { + java.nio.file.Files.write(outputFile.toPath(), decodedBytes); + } catch (IOException ioe) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FailedtoSaveProcessedFile.getMessage()); + } + + } + } + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.DEIDENTIFY_FILE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } + return response; + } + + private String getFileExtension(String fileName) { + return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); + } + + private String encodeFileToBase64(File file) throws IOException { + byte[] fileContent = Files.readAllBytes(file.toPath()); + return Base64.getEncoder().encodeToString(fileContent); + } + + private DeidentifyFileResponse pollForResults(String runId, Integer maxWaitTime) throws Exception { + int currentWaitTime = 1; + maxWaitTime = maxWaitTime == null ? 64 : maxWaitTime; + + DeidentifyStatusResponse response = null; + + while (true) { + try { + GetRunRequest getRunRequest = GetRunRequest.builder() + .vaultId(super.getVaultConfig().getVaultId()) + .build(); + response = super.getDetectFileAPi() + .getRun(runId, getRunRequest); + + DeidentifyStatusResponseStatus status = response.getStatus(); + + if (DeidentifyFileStatus.IN_PROGRESS.value().equalsIgnoreCase(String.valueOf(status))) { + if (currentWaitTime >= maxWaitTime) { + return new DeidentifyFileResponse(runId, DeidentifyFileStatus.IN_PROGRESS.value()); + } + + int nextWaitTime = currentWaitTime * 2; + int waitTime; + + if (nextWaitTime >= maxWaitTime) { + waitTime = maxWaitTime - currentWaitTime; + currentWaitTime = maxWaitTime; + } else { + waitTime = nextWaitTime; + currentWaitTime = nextWaitTime; + } + + Thread.sleep(waitTime * 1000); + + } else if (status == DeidentifyStatusResponseStatus.SUCCESS || + status == DeidentifyStatusResponseStatus.FAILED) { + return parseDeidentifyFileResponse(response, runId, status.toString()); + } + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.GET_DETECT_RUN_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } + } -public class DetectController { - public DetectController(ApiClient apiClient) { } - // should return detect controller - public DetectController deIdentify() { - // return detect controller - return null; + private static synchronized DeidentifyFileResponse parseDeidentifyFileResponse(DeidentifyStatusResponse response, + String runId, String status) throws SkyflowException { + DeidentifyFileOutput firstOutput = getFirstOutput(response); + + Object wordCharObj = response.getAdditionalProperties().get("word_character_count"); + Integer wordCount = null; + Integer charCount = null; + + if (wordCharObj instanceof Map) { + Map wordCharMap = (Map) wordCharObj; + Object wc = wordCharMap.get("word_count"); + Object cc = wordCharMap.get("character_count"); + if (wc instanceof Number) { + wordCount = ((Number) wc).intValue(); + } + if (cc instanceof Number) { + charCount = ((Number) cc).intValue(); + } + } + + File processedFileObject = null; + FileInfo fileInfo = null; + Optional processedFileBase64 = firstOutput != null ? firstOutput.getProcessedFile() : Optional.empty(); + Optional processedFileExtension = firstOutput != null ? firstOutput.getProcessedFileExtension() : Optional.empty(); + + if (processedFileBase64.isPresent() && processedFileExtension.isPresent()) { + try { + byte[] decodedBytes = Base64.getDecoder().decode(processedFileBase64.get()); + String suffix = "." + processedFileExtension.get(); + String fileName = Constants.DEIDENTIFIED_FILE_PREFIX + suffix; + processedFileObject = new File(System.getProperty("java.io.tmpdir"), fileName); + Files.write(processedFileObject.toPath(), decodedBytes); + fileInfo = new FileInfo(processedFileObject); + processedFileObject.deleteOnExit(); + } catch (IOException ioe) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FailedToEncodeFile.getMessage()); + } + } + + return new DeidentifyFileResponse( + fileInfo, + firstOutput.getProcessedFile().orElse(null), + firstOutput.getProcessedFileType().get().toString(), + firstOutput.getProcessedFileExtension().get(), + wordCount, + charCount, + response.getSize().map(Double::valueOf).orElse(null), + response.getDuration().map(Double::valueOf).orElse(null), + response.getPages().orElse(null), + response.getSlides().orElse(null), + getEntities(response), + runId, + status, + null + ); + } + + private static synchronized DeidentifyFileOutput getFirstOutput(DeidentifyStatusResponse response) { + List outputs = response.getOutput(); + return outputs != null && !outputs.isEmpty() ? outputs.get(0) : null; } - public DeIdentifyResponse text(DeIdentifyRequest deIdentifyRequest) { - // return detect response - return null; + private static synchronized List getEntities(DeidentifyStatusResponse response) { + List entities = new ArrayList<>(); + + List outputs = response.getOutput(); + DeidentifyFileOutput deidentifyFileOutput = outputs != null && !outputs.isEmpty() ? outputs.get(1) : null; + + if (deidentifyFileOutput != null) { + entities.add(new FileEntityInfo( + deidentifyFileOutput.getProcessedFile().orElse(null), + deidentifyFileOutput.getProcessedFileType().orElse(null), + deidentifyFileOutput.getProcessedFileExtension().orElse(null) + )); + } + + return entities; } - public DeIdentifyResponse file(DeIdentifyRequest deIdentifyRequest) { - // return detect response - return null; + private com.skyflow.generated.rest.types.DeidentifyFileResponse processFileByType(String fileExtension, String base64Content, DeidentifyFileRequest request, String vaultId) throws SkyflowException { + switch (fileExtension.toLowerCase()) { + case "txt": + com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest textFileRequest = + super.getDeidentifyTextFileRequest(request, vaultId, base64Content); + return super.getDetectFileAPi().deidentifyText(textFileRequest); + + case "mp3": + case "wav": + DeidentifyAudioRequest audioRequest = + super.getDeidentifyAudioRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifyAudio(audioRequest); + + case "pdf": + DeidentifyPdfRequest pdfRequest = + super.getDeidentifyPdfRequest(request, vaultId, base64Content); + + return super.getDetectFileAPi().deidentifyPdf(pdfRequest); + + case "jpg": + case "jpeg": + case "png": + case "bmp": + case "tif": + case "tiff": + DeidentifyImageRequest imageRequest = + super.getDeidentifyImageRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifyImage(imageRequest); + + case "ppt": + case "pptx": + DeidentifyPresentationRequest presentationRequest = + super.getDeidentifyPresentationRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifyPresentation(presentationRequest); + + case "csv": + case "xls": + case "xlsx": + DeidentifySpreadsheetRequest spreadsheetRequest = + super.getDeidentifySpreadsheetRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifySpreadsheet(spreadsheetRequest); + + case "doc": + case "docx": + DeidentifyDocumentRequest documentRequest = + super.getDeidentifyDocumentRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifyDocument(documentRequest); + + case "json": + case "xml": + DeidentifyStructuredTextRequest structuredTextRequest = + super.getDeidentifyStructuredTextRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifyStructuredText(structuredTextRequest); + + default: + com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest genericFileRequest = + super.getDeidentifyGenericFileRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifyFile(genericFileRequest); + } + } + + public DeidentifyFileResponse getDetectRun(GetDetectRunRequest request) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.GET_DETECT_RUN_TRIGGERED.getLog()); + try { + LogUtil.printInfoLog(InfoLogs.VALIDATE_GET_DETECT_RUN_REQUEST.getLog()); + Validations.validateGetDetectRunRequest(request); + setBearerToken(); + String runId = request.getRunId(); + String vaultId = super.getVaultConfig().getVaultId(); + + GetRunRequest getRunRequest = + GetRunRequest.builder() + .vaultId(vaultId) + .build(); + + com.skyflow.generated.rest.types.DeidentifyStatusResponse apiResponse = + super.getDetectFileAPi().getRun(runId, getRunRequest); + + return parseDeidentifyFileResponse(apiResponse, runId, apiResponse.getStatus().toString()); + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.GET_DETECT_RUN_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } } } diff --git a/src/main/java/com/skyflow/vault/controller/VaultController.java b/src/main/java/com/skyflow/vault/controller/VaultController.java index f2130706..84e528b0 100644 --- a/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -6,9 +6,15 @@ import com.skyflow.config.VaultConfig; import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; -import com.skyflow.generated.rest.ApiException; -import com.skyflow.generated.rest.ApiResponse; -import com.skyflow.generated.rest.models.*; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.resources.query.requests.QueryServiceExecuteQueryBody; +import com.skyflow.generated.rest.resources.records.requests.*; +import com.skyflow.generated.rest.resources.records.types.RecordServiceBulkGetRecordRequestOrderBy; +import com.skyflow.generated.rest.resources.records.types.RecordServiceBulkGetRecordRequestRedaction; +import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; +import com.skyflow.generated.rest.types.*; import com.skyflow.logs.ErrorLogs; import com.skyflow.logs.InfoLogs; import com.skyflow.utils.Constants; @@ -16,23 +22,13 @@ import com.skyflow.utils.validations.Validations; import com.skyflow.vault.data.*; import com.skyflow.vault.tokens.*; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; public final class VaultController extends VaultClient { private static final Gson gson = new GsonBuilder().serializeNulls().create(); - private DetectController detectController; - private AuditController auditController; - private BinLookupController binLookupController; public VaultController(VaultConfig vaultConfig, Credentials credentials) { super(vaultConfig, credentials); - this.auditController = null; - this.binLookupController = null; - this.detectController = null; } private static synchronized HashMap getFormattedBatchInsertRecord(Object record, int requestIndex) { @@ -62,41 +58,38 @@ private static synchronized HashMap getFormattedBatchInsertRecor private static synchronized HashMap getFormattedBulkInsertRecord(V1RecordMetaProperties record) { HashMap insertRecord = new HashMap<>(); - String skyflowId = record.getSkyflowId(); - Object tokens = record.getTokens(); - insertRecord.put("skyflowId", skyflowId); - if (tokens != null) { - String tokensString = gson.toJson(tokens); - JsonObject tokensObject = JsonParser.parseString(tokensString).getAsJsonObject(); - insertRecord.putAll(tokensObject.asMap()); + if (record.getSkyflowId().isPresent()) { + insertRecord.put("skyflowId", record.getSkyflowId().get()); + } + + if (record.getTokens().isPresent()) { + Map tokensMap = record.getTokens().get(); + insertRecord.putAll(tokensMap); } return insertRecord; } private static synchronized HashMap getFormattedGetRecord(V1FieldRecords record) { HashMap getRecord = new HashMap<>(); - Object fields = record.getFields(); - Object tokens = record.getTokens(); - if (fields != null) { - String fieldsString = gson.toJson(fields); - JsonObject fieldsObject = JsonParser.parseString(fieldsString).getAsJsonObject(); - getRecord.putAll(fieldsObject.asMap()); - } else if (tokens != null) { - String tokensString = gson.toJson(tokens); - JsonObject tokensObject = JsonParser.parseString(tokensString).getAsJsonObject(); - getRecord.putAll(tokensObject.asMap()); + + Optional> fieldsOpt = record.getFields(); + Optional> tokensOpt = record.getTokens(); + + if (fieldsOpt.isPresent()) { + getRecord.putAll(fieldsOpt.get()); + } else if (tokensOpt.isPresent()) { + getRecord.putAll(tokensOpt.get()); } return getRecord; } private static synchronized HashMap getFormattedUpdateRecord(V1UpdateRecordResponse record) { HashMap updateTokens = new HashMap<>(); - Object tokens = record.getTokens(); - if (tokens != null) { - String tokensString = gson.toJson(tokens); - JsonObject tokensObject = JsonParser.parseString(tokensString).getAsJsonObject(); - updateTokens.putAll(tokensObject.asMap()); - } + + record.getSkyflowId().ifPresent(skyflowId -> updateTokens.put("skyflowId", skyflowId)); + + record.getTokens().ifPresent(tokensMap -> updateTokens.putAll(tokensMap)); + return updateTokens; } @@ -114,7 +107,7 @@ private static synchronized HashMap getFormattedQueryRecord(V1Fi public InsertResponse insert(InsertRequest insertRequest) throws SkyflowException { LogUtil.printInfoLog(InfoLogs.INSERT_TRIGGERED.getLog()); V1InsertRecordResponse bulkInsertResult = null; - ApiResponse batchInsertResult = null; + ApiClientHttpResponse batchInsertResult = null; ArrayList> insertedFields = new ArrayList<>(); ArrayList> errorFields = new ArrayList<>(); Boolean continueOnError = insertRequest.getContinueOnError(); @@ -124,19 +117,23 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio setBearerToken(); if (continueOnError) { RecordServiceBatchOperationBody insertBody = super.getBatchInsertRequestBody(insertRequest); - batchInsertResult = super.getRecordsApi().recordServiceBatchOperationWithHttpInfo(super.getVaultConfig().getVaultId(), insertBody); + batchInsertResult = super.getRecordsApi().withRawResponse().recordServiceBatchOperation(super.getVaultConfig().getVaultId(), insertBody); LogUtil.printInfoLog(InfoLogs.INSERT_REQUEST_RESOLVED.getLog()); - Map> responseHeaders = batchInsertResult.getHeaders(); - String requestId = responseHeaders.get(Constants.REQUEST_ID_HEADER_KEY).get(0); - List records = batchInsertResult.getData().getResponses(); - for (int index = 0; index < records.size(); index++) { - Object record = records.get(index); - HashMap insertRecord = getFormattedBatchInsertRecord(record, index); - if (insertRecord.containsKey("skyflowId")) { - insertedFields.add(insertRecord); - } else { - insertRecord.put("requestId", requestId); - errorFields.add(insertRecord); + Optional>> records = batchInsertResult.body().getResponses(); + + if (records.isPresent()) { + List> recordList = records.get(); + + for (int index = 0; index < recordList.size(); index++) { + Map record = recordList.get(index); + HashMap insertRecord = getFormattedBatchInsertRecord(record, index); + + if (insertRecord.containsKey("skyflowId")) { + insertedFields.add(insertRecord); + } else { + insertRecord.put("requestId", batchInsertResult.headers().get("x-request-id").get(0)); + errorFields.add(insertRecord); + } } } } else { @@ -144,25 +141,32 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio bulkInsertResult = super.getRecordsApi().recordServiceInsertRecord( super.getVaultConfig().getVaultId(), insertRequest.getTable(), insertBody); LogUtil.printInfoLog(InfoLogs.INSERT_REQUEST_RESOLVED.getLog()); - List records = bulkInsertResult.getRecords(); - if (records != null) { - for (V1RecordMetaProperties record : records) { + Optional> records = bulkInsertResult.getRecords(); + if (records.isPresent()) { + for (V1RecordMetaProperties record : records.get()) { HashMap insertRecord = getFormattedBulkInsertRecord(record); insertedFields.add(insertRecord); } } } - } catch (ApiException e) { + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); LogUtil.printErrorLog(ErrorLogs.INSERT_RECORDS_REJECTED.getLog()); - throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); } LogUtil.printInfoLog(InfoLogs.INSERT_SUCCESS.getLog()); + if (insertedFields.isEmpty()) { + return new InsertResponse(null, errorFields.isEmpty() ? null : errorFields); + } + if (errorFields.isEmpty()) { + return new InsertResponse(insertedFields.isEmpty() ? null : insertedFields, null); + } return new InsertResponse(insertedFields, errorFields); } public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws SkyflowException { LogUtil.printInfoLog(InfoLogs.DETOKENIZE_TRIGGERED.getLog()); - ApiResponse result = null; + ApiClientHttpResponse result = null; ArrayList detokenizedFields = new ArrayList<>(); ArrayList errorRecords = new ArrayList<>(); try { @@ -170,15 +174,17 @@ public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws Validations.validateDetokenizeRequest(detokenizeRequest); setBearerToken(); V1DetokenizePayload payload = super.getDetokenizePayload(detokenizeRequest); - result = super.getTokensApi().recordServiceDetokenizeWithHttpInfo(super.getVaultConfig().getVaultId(), payload); + result = super.getTokensApi().withRawResponse().recordServiceDetokenize(super.getVaultConfig().getVaultId(), payload); LogUtil.printInfoLog(InfoLogs.DETOKENIZE_REQUEST_RESOLVED.getLog()); - Map> responseHeaders = result.getHeaders(); + Map> responseHeaders = result.headers(); String requestId = responseHeaders.get(Constants.REQUEST_ID_HEADER_KEY).get(0); - List records = result.getData().getRecords(); + Optional> records = result.body().getRecords(); - if (records != null) { - for (V1DetokenizeRecordResponse record : records) { - if (record.getError() != null) { + if (records.isPresent()) { + List recordList = records.get(); + + for (V1DetokenizeRecordResponse record : recordList) { + if (record.getError().isPresent()) { DetokenizeRecordResponse recordResponse = new DetokenizeRecordResponse(record, requestId); errorRecords.add(recordResponse); } else { @@ -187,9 +193,10 @@ public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws } } } - } catch (ApiException e) { + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); LogUtil.printErrorLog(ErrorLogs.DETOKENIZE_REQUEST_REJECTED.getLog()); - throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); } if (!errorRecords.isEmpty()) { @@ -197,6 +204,12 @@ public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws } else { LogUtil.printInfoLog(InfoLogs.DETOKENIZE_SUCCESS.getLog()); } + if (detokenizedFields.isEmpty()) { + return new DetokenizeResponse(null, errorRecords.isEmpty() ? null : errorRecords); + } + if (errorRecords.isEmpty()) { + return new DetokenizeResponse(detokenizedFields, null); + } return new DetokenizeResponse(detokenizedFields, errorRecords); } @@ -210,33 +223,38 @@ public GetResponse get(GetRequest getRequest) throws SkyflowException { Validations.validateGetRequest(getRequest); setBearerToken(); RedactionType redactionType = getRequest.getRedactionType(); + RecordServiceBulkGetRecordRequest recordServiceBulkGetRecordRequest = RecordServiceBulkGetRecordRequest.builder() + .skyflowIds(getRequest.getIds()) + .redaction(redactionType != null ? RecordServiceBulkGetRecordRequestRedaction.valueOf(redactionType.toString()) : null) + .tokenization(getRequest.getReturnTokens()) + .offset(getRequest.getOffset()) + .limit(getRequest.getLimit()) + .downloadUrl(getRequest.getDownloadURL()) + .columnName(getRequest.getColumnName()) + .columnValues(getRequest.getColumnValues()) + .orderBy(RecordServiceBulkGetRecordRequestOrderBy.valueOf(getRequest.getOrderBy())) + .build(); + + result = super.getRecordsApi().recordServiceBulkGetRecord( super.getVaultConfig().getVaultId(), getRequest.getTable(), - getRequest.getIds(), - redactionType != null ? redactionType.toString() : null, - getRequest.getReturnTokens(), - getRequest.getFields(), - getRequest.getOffset(), - getRequest.getLimit(), - getRequest.getDownloadURL(), - getRequest.getColumnName(), - getRequest.getColumnValues(), - getRequest.getOrderBy() + recordServiceBulkGetRecordRequest ); LogUtil.printInfoLog(InfoLogs.GET_REQUEST_RESOLVED.getLog()); - List records = result.getRecords(); + List records = result.getRecords().get(); if (records != null) { for (V1FieldRecords record : records) { data.add(getFormattedGetRecord(record)); } } - } catch (ApiException e) { + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); LogUtil.printErrorLog(ErrorLogs.GET_REQUEST_REJECTED.getLog()); - throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); } LogUtil.printInfoLog(InfoLogs.GET_SUCCESS.getLog()); - return new GetResponse(data, errors); + return new GetResponse(data, null); } public UpdateResponse update(UpdateRequest updateRequest) throws SkyflowException { @@ -256,11 +274,12 @@ public UpdateResponse update(UpdateRequest updateRequest) throws SkyflowExceptio updateBody ); LogUtil.printInfoLog(InfoLogs.UPDATE_REQUEST_RESOLVED.getLog()); - skyflowId = result.getSkyflowId(); + skyflowId = String.valueOf(result.getSkyflowId()); tokensMap = getFormattedUpdateRecord(result); - } catch (ApiException e) { + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); LogUtil.printErrorLog(ErrorLogs.UPDATE_REQUEST_REJECTED.getLog()); - throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); } LogUtil.printInfoLog(InfoLogs.UPDATE_SUCCESS.getLog()); return new UpdateResponse(skyflowId, tokensMap); @@ -273,23 +292,19 @@ public DeleteResponse delete(DeleteRequest deleteRequest) throws SkyflowExceptio LogUtil.printInfoLog(InfoLogs.VALIDATING_DELETE_REQUEST.getLog()); Validations.validateDeleteRequest(deleteRequest); setBearerToken(); - RecordServiceBulkDeleteRecordBody deleteBody = new RecordServiceBulkDeleteRecordBody(); - for (String id : deleteRequest.getIds()) { - deleteBody.addSkyflowIdsItem(id); - } + RecordServiceBulkDeleteRecordBody deleteBody = RecordServiceBulkDeleteRecordBody.builder().skyflowIds(deleteRequest.getIds()) + .build(); + result = super.getRecordsApi().recordServiceBulkDeleteRecord( super.getVaultConfig().getVaultId(), deleteRequest.getTable(), deleteBody); LogUtil.printInfoLog(InfoLogs.DELETE_REQUEST_RESOLVED.getLog()); - } catch (ApiException e) { + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); LogUtil.printErrorLog(ErrorLogs.DELETE_REQUEST_REJECTED.getLog()); - throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); } LogUtil.printInfoLog(InfoLogs.DELETE_SUCCESS.getLog()); - return new DeleteResponse((ArrayList) result.getRecordIDResponse()); - } - - public Object uploadFile(Object uploadFileRequest) { - return null; + return new DeleteResponse(result.getRecordIdResponse().get()); } public QueryResponse query(QueryRequest queryRequest) throws SkyflowException { @@ -301,16 +316,18 @@ public QueryResponse query(QueryRequest queryRequest) throws SkyflowException { Validations.validateQueryRequest(queryRequest); setBearerToken(); result = super.getQueryApi().queryServiceExecuteQuery( - super.getVaultConfig().getVaultId(), new QueryServiceExecuteQueryBody().query(queryRequest.getQuery())); + super.getVaultConfig().getVaultId(), QueryServiceExecuteQueryBody.builder().query(queryRequest.getQuery()).build()); LogUtil.printInfoLog(InfoLogs.QUERY_REQUEST_RESOLVED.getLog()); - if (result.getRecords() != null) { - for (V1FieldRecords record : result.getRecords()) { + if (result.getRecords().isPresent()) { + List records = result.getRecords().get(); // Extract the List from Optional + for (V1FieldRecords record : records) { fields.add(getFormattedQueryRecord(record)); } } - } catch (ApiException e) { + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); LogUtil.printErrorLog(ErrorLogs.QUERY_REQUEST_REJECTED.getLog()); - throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); } LogUtil.printInfoLog(InfoLogs.QUERY_SUCCESS.getLog()); return new QueryResponse(fields); @@ -327,39 +344,19 @@ public TokenizeResponse tokenize(TokenizeRequest tokenizeRequest) throws Skyflow V1TokenizePayload payload = super.getTokenizePayload(tokenizeRequest); result = super.getTokensApi().recordServiceTokenize(super.getVaultConfig().getVaultId(), payload); LogUtil.printInfoLog(InfoLogs.TOKENIZE_REQUEST_RESOLVED.getLog()); - if (result != null && result.getRecords().size() > 0) { - for (V1TokenizeRecordResponse response : result.getRecords()) { - if (response.getToken() != null) { - list.add(response.getToken()); + if (result != null && result.getRecords().isPresent() && !result.getRecords().get().isEmpty()) { + for (V1TokenizeRecordResponse response : result.getRecords().get()) { + if (response.getToken().isPresent()) { + list.add(response.getToken().get()); } } } - } catch (ApiException e) { + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); LogUtil.printErrorLog(ErrorLogs.TOKENIZE_REQUEST_REJECTED.getLog()); - throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); } LogUtil.printInfoLog(InfoLogs.TOKENIZE_SUCCESS.getLog()); return new TokenizeResponse(list); } - - public BinLookupController lookUpBin() { - if (this.binLookupController == null) { - this.binLookupController = new BinLookupController(super.getApiClient()); - } - return this.binLookupController; - } - - public AuditController audit() { - if (this.auditController == null) { - this.auditController = new AuditController(super.getApiClient()); - } - return this.auditController; - } - - public DetectController detect() { - if (this.detectController == null) { - this.detectController = new DetectController(super.getApiClient()); - } - return this.detectController; - } } diff --git a/src/main/java/com/skyflow/vault/data/DeleteResponse.java b/src/main/java/com/skyflow/vault/data/DeleteResponse.java index 7b245bf1..f34d219a 100644 --- a/src/main/java/com/skyflow/vault/data/DeleteResponse.java +++ b/src/main/java/com/skyflow/vault/data/DeleteResponse.java @@ -1,20 +1,19 @@ package com.skyflow.vault.data; import com.google.gson.Gson; -import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import java.util.ArrayList; +import java.util.List; public class DeleteResponse { - private final ArrayList deletedIds; + private final List deletedIds; - public DeleteResponse(ArrayList deletedIds) { + public DeleteResponse(List deletedIds) { this.deletedIds = deletedIds; } - public ArrayList getDeletedIds() { + public List getDeletedIds() { return deletedIds; } @@ -22,7 +21,7 @@ public ArrayList getDeletedIds() { public String toString() { Gson gson = new Gson(); JsonObject responseObject = JsonParser.parseString(gson.toJson(this)).getAsJsonObject(); - responseObject.add("errors", new JsonArray()); + responseObject.add("errors", null); return responseObject.toString(); } } diff --git a/src/main/java/com/skyflow/vault/data/GetRequest.java b/src/main/java/com/skyflow/vault/data/GetRequest.java index 12aef7fa..04626e35 100644 --- a/src/main/java/com/skyflow/vault/data/GetRequest.java +++ b/src/main/java/com/skyflow/vault/data/GetRequest.java @@ -76,7 +76,6 @@ public static final class GetRequestBuilder { private GetRequestBuilder() { this.downloadURL = true; this.orderBy = Constants.ORDER_ASCENDING; - this.redactionType = RedactionType.PLAIN_TEXT; } public GetRequestBuilder table(String table) { diff --git a/src/main/java/com/skyflow/vault/data/QueryResponse.java b/src/main/java/com/skyflow/vault/data/QueryResponse.java index 1906a218..7a1bca51 100644 --- a/src/main/java/com/skyflow/vault/data/QueryResponse.java +++ b/src/main/java/com/skyflow/vault/data/QueryResponse.java @@ -25,7 +25,7 @@ public String toString() { for (JsonElement fieldElement : fieldsArray) { fieldElement.getAsJsonObject().add("tokenizedData", new JsonObject()); } - responseObject.add("errors", new JsonArray()); + responseObject.add("errors", null); responseObject.remove("tokenizedData"); return responseObject.toString(); } diff --git a/src/main/java/com/skyflow/vault/data/UpdateResponse.java b/src/main/java/com/skyflow/vault/data/UpdateResponse.java index 4dd32f1b..068b29be 100644 --- a/src/main/java/com/skyflow/vault/data/UpdateResponse.java +++ b/src/main/java/com/skyflow/vault/data/UpdateResponse.java @@ -34,7 +34,7 @@ public String toString() { } JsonObject finalResponseObject = new JsonObject(); finalResponseObject.add("updatedField", responseObject); - finalResponseObject.add("errors", new JsonArray()); + finalResponseObject.add("errors", null); return finalResponseObject.toString(); } } diff --git a/src/main/java/com/skyflow/vault/detect/AudioBleep.java b/src/main/java/com/skyflow/vault/detect/AudioBleep.java new file mode 100644 index 00000000..1a75f93b --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/AudioBleep.java @@ -0,0 +1,64 @@ +package com.skyflow.vault.detect; + +public class AudioBleep { + private final AudioBleepBuilder builder; + + private AudioBleep(AudioBleepBuilder builder) { + this.builder = builder; + } + + public static AudioBleepBuilder builder() { + return new AudioBleepBuilder(); + } + + public Double getGain() { + return this.builder.gain; + } + + public Double getFrequency() { + return this.builder.frequency; + } + + public Double getStartPadding() { + return this.builder.startPadding; + } + + public Double getStopPadding() { + return this.builder.stopPadding; + } + + public static final class AudioBleepBuilder { + private Double gain; + private Double frequency; + private Double startPadding; + private Double stopPadding; + + private AudioBleepBuilder() { + // Default constructor + } + + public AudioBleepBuilder gain(Double gain) { + this.gain = gain; + return this; + } + + public AudioBleepBuilder frequency(Double frequency) { + this.frequency = frequency; + return this; + } + + public AudioBleepBuilder startPadding(Double startPadding) { + this.startPadding = startPadding; + return this; + } + + public AudioBleepBuilder stopPadding(Double stopPadding) { + this.stopPadding = stopPadding; + return this; + } + + public AudioBleep build() { + return new AudioBleep(this); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/DateTransformation.java b/src/main/java/com/skyflow/vault/detect/DateTransformation.java new file mode 100644 index 00000000..819927d2 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/DateTransformation.java @@ -0,0 +1,30 @@ +package com.skyflow.vault.detect; + + +import com.skyflow.enums.DetectEntities; + +import java.util.List; + +public class DateTransformation { + private final int max; + private final int min; + private final List entities; + + public DateTransformation(int max, int min, List entities) { + this.max = max; + this.min = min; + this.entities = entities; + } + + public int getMax() { + return max; + } + + public int getMin() { + return min; + } + + public List getEntities() { + return entities; + } +} diff --git a/src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java b/src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java deleted file mode 100644 index 92be4962..00000000 --- a/src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.skyflow.vault.detect; - -public class DeIdentifyRequest { - // members - - public DeIdentifyRequest() { - } - - // getters ans setters -} diff --git a/src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java b/src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java deleted file mode 100644 index 05fe9a6e..00000000 --- a/src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.skyflow.vault.detect; - -public class DeIdentifyResponse { - // members - - public DeIdentifyResponse() { - } - - // getters ans setters -} diff --git a/src/main/java/com/skyflow/vault/detect/DeidentifyFileRequest.java b/src/main/java/com/skyflow/vault/detect/DeidentifyFileRequest.java new file mode 100644 index 00000000..3ebc450e --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/DeidentifyFileRequest.java @@ -0,0 +1,192 @@ +package com.skyflow.vault.detect; + +import com.skyflow.enums.DetectEntities; +import com.skyflow.enums.DetectOutputTranscriptions; +import com.skyflow.enums.MaskingMethod; +import java.util.List; + +public class DeidentifyFileRequest { + private final DeidentifyFileRequestBuilder builder; + + private DeidentifyFileRequest(DeidentifyFileRequestBuilder builder) { + this.builder = builder; + } + + public static DeidentifyFileRequestBuilder builder() { + return new DeidentifyFileRequestBuilder(); + } + + public FileInput getFileInput() { + return this.builder.fileInput; + } + + public List getEntities() { + return this.builder.entities; + } + + public List getAllowRegexList() { + return this.builder.allowRegexList; + } + + public List getRestrictRegexList() { + return this.builder.restrictRegexList; + } + + public TokenFormat getTokenFormat() { + return this.builder.tokenFormat; + } + + public Transformations getTransformations() { + return this.builder.transformations; + } + + public Boolean getOutputProcessedImage() { + return this.builder.outputProcessedImage; + } + + public Boolean getOutputOcrText() { + return this.builder.outputOcrText; + } + + public MaskingMethod getMaskingMethod() { + return this.builder.maskingMethod; + } + + public Number getPixelDensity() { + return this.builder.pixelDensity; + } + + public Number getMaxResolution() { + return this.builder.maxResolution; + } + + public Boolean getOutputProcessedAudio() { + return this.builder.outputProcessedAudio; + } + + public DetectOutputTranscriptions getOutputTranscription() { + return this.builder.outputTranscription; + } + + public AudioBleep getBleep() { + return this.builder.bleep; + } + + public String getOutputDirectory() { + return this.builder.outputDirectory; + } + + public Integer getWaitTime() { + return this.builder.waitTime; + } + + public static final class DeidentifyFileRequestBuilder { + private List entities; + private List allowRegexList; + private List restrictRegexList; + private TokenFormat tokenFormat; + private Transformations transformations; + private Boolean outputProcessedImage; + private Boolean outputOcrText; + private MaskingMethod maskingMethod; + private Number pixelDensity; + private Number maxResolution; + private Boolean outputProcessedAudio; + private DetectOutputTranscriptions outputTranscription; + private AudioBleep bleep; + private FileInput fileInput; + private String outputDirectory; + private Integer waitTime; + + private DeidentifyFileRequestBuilder() { + // Set default values + this.outputProcessedImage = false; + this.outputOcrText = false; + this.outputProcessedAudio = false; + } + + public DeidentifyFileRequestBuilder file(FileInput fileInput) { + this.fileInput = fileInput; + return this; + } + + public DeidentifyFileRequestBuilder entities(List entities) { + this.entities = entities; + return this; + } + + public DeidentifyFileRequestBuilder allowRegexList(List allowRegexList) { + this.allowRegexList = allowRegexList; + return this; + } + + public DeidentifyFileRequestBuilder restrictRegexList(List restrictRegexList) { + this.restrictRegexList = restrictRegexList; + return this; + } + + public DeidentifyFileRequestBuilder tokenFormat(TokenFormat tokenFormat) { + this.tokenFormat = tokenFormat; + return this; + } + + public DeidentifyFileRequestBuilder transformations(Transformations transformations) { + this.transformations = transformations; + return this; + } + + public DeidentifyFileRequestBuilder outputProcessedImage(Boolean outputProcessedImage) { + this.outputProcessedImage = outputProcessedImage != null ? outputProcessedImage : false; + return this; + } + + public DeidentifyFileRequestBuilder outputOcrText(Boolean outputOcrText) { + this.outputOcrText = outputOcrText != null ? outputOcrText : false; + return this; + } + + public DeidentifyFileRequestBuilder maskingMethod(MaskingMethod maskingMethod) { + this.maskingMethod = maskingMethod; + return this; + } + + public DeidentifyFileRequestBuilder pixelDensity(Number pixelDensity) { + this.pixelDensity = pixelDensity; + return this; + } + + public DeidentifyFileRequestBuilder maxResolution(Number maxResolution) { + this.maxResolution = maxResolution; + return this; + } + + public DeidentifyFileRequestBuilder outputProcessedAudio(Boolean outputProcessedAudio) { + this.outputProcessedAudio = outputProcessedAudio != null ? outputProcessedAudio : false; + return this; + } + + public DeidentifyFileRequestBuilder outputTranscription(DetectOutputTranscriptions outputTranscription) { + this.outputTranscription = outputTranscription; + return this; + } + + public DeidentifyFileRequestBuilder bleep(AudioBleep bleep) { + this.bleep = bleep; + return this; + } + + public DeidentifyFileRequestBuilder outputDirectory(String outputDirectory) { + this.outputDirectory = outputDirectory; + return this; + } + + public DeidentifyFileRequestBuilder waitTime(Integer waitTime) { + this.waitTime = waitTime; + return this; + } + + public DeidentifyFileRequest build() { + return new DeidentifyFileRequest(this); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java b/src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java new file mode 100644 index 00000000..95effea0 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java @@ -0,0 +1,112 @@ +package com.skyflow.vault.detect; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.io.File; +import java.util.List; + +public class DeidentifyFileResponse { + private final FileInfo file; + private final String fileBase64; + private final String type; + private final String extension; + private final Integer wordCount; + private final Integer charCount; + private final Double sizeInKb; + private final Double durationInSeconds; + private final Integer pageCount; + private final Integer slideCount; + private final List entities; + private final String runId; + private final String status; + private final List errors; + + + public DeidentifyFileResponse(FileInfo file, String fileBase64, String type, String extension, + Integer wordCount, Integer charCount, Double sizeInKb, + Double durationInSeconds, Integer pageCount, Integer slideCount, + List entities, String runId, String status, List errors) { + this.file = file; + this.fileBase64 = fileBase64; + this.type = type; + this.extension = extension; + this.wordCount = wordCount; + this.charCount = charCount; + this.sizeInKb = sizeInKb; + this.durationInSeconds = durationInSeconds; + this.pageCount = pageCount; + this.slideCount = slideCount; + this.entities = entities; + this.runId = runId; + this.status = status; + this.errors = errors; + } + + public DeidentifyFileResponse(String runId, String status) { + this(null, null, null, null, null, null, null, null, null, null, null, runId, status, null); + } + + public FileInfo getFile() { + return file; + } + + public String getFileBase64(){ + return fileBase64; + } + + public String getType() { + return type; + } + + public String getExtension() { + return extension; + } + + public Integer getWordCount() { + return wordCount; + } + + public Integer getCharCount() { + return charCount; + } + + public Double getSizeInKb() { + return sizeInKb; + } + + public Double getDurationInSeconds() { + return durationInSeconds; + } + + public Integer getPageCount() { + return pageCount; + } + + public Integer getSlideCount() { + return slideCount; + } + + public List getEntities() { + return entities; + } + + public String getRunId() { + return runId; + } + + public String getStatus() { + return status; + } + + public List getErrors() { + return errors; + } + + @Override + public String toString() { + Gson gson = new GsonBuilder().serializeNulls().create(); + return gson.toJson(this); + } + +} diff --git a/src/main/java/com/skyflow/vault/detect/DeidentifyTextRequest.java b/src/main/java/com/skyflow/vault/detect/DeidentifyTextRequest.java new file mode 100644 index 00000000..5f57e3a9 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/DeidentifyTextRequest.java @@ -0,0 +1,88 @@ +package com.skyflow.vault.detect; + + +import com.skyflow.enums.DetectEntities; + +import java.util.List; + +public class DeidentifyTextRequest { + private final DeidentifyTextRequestBuilder builder; + + private DeidentifyTextRequest(DeidentifyTextRequestBuilder builder) { + this.builder = builder; + } + + public static DeidentifyTextRequestBuilder builder() { + return new DeidentifyTextRequestBuilder(); + } + + public String getText() { + return this.builder.text; + } + + public List getEntities() { + return this.builder.entities; + } + + public List getAllowRegexList() { + return this.builder.allowRegexList; + } + + public List getRestrictRegexList() { + return this.builder.restrictRegexList; + } + + public TokenFormat getTokenFormat() { + return this.builder.tokenFormat; + } + + public Transformations getTransformations() { + return this.builder.transformations; + } + + public static final class DeidentifyTextRequestBuilder { + private String text; + private List entities; + private List allowRegexList; + private List restrictRegexList; + private TokenFormat tokenFormat; + private Transformations transformations; + + private DeidentifyTextRequestBuilder() { + } + + public DeidentifyTextRequestBuilder text(String text) { + this.text = text; + return this; + } + + public DeidentifyTextRequestBuilder entities(List entities) { + this.entities = entities; + return this; + } + + public DeidentifyTextRequestBuilder allowRegexList(List allowRegexList) { + this.allowRegexList = allowRegexList; + return this; + } + + public DeidentifyTextRequestBuilder restrictRegexList(List restrictRegexList) { + this.restrictRegexList = restrictRegexList; + return this; + } + + public DeidentifyTextRequestBuilder tokenFormat(TokenFormat tokenFormat) { + this.tokenFormat = tokenFormat; + return this; + } + + public DeidentifyTextRequestBuilder transformations(Transformations transformations) { + this.transformations = transformations; + return this; + } + + public DeidentifyTextRequest build() { + return new DeidentifyTextRequest(this); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/DeidentifyTextResponse.java b/src/main/java/com/skyflow/vault/detect/DeidentifyTextResponse.java new file mode 100644 index 00000000..6b6118e0 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/DeidentifyTextResponse.java @@ -0,0 +1,44 @@ +package com.skyflow.vault.detect; + + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.util.List; + +public class DeidentifyTextResponse { + private final String processedText; + private final List entities; + private final int wordCount; + private final int charCount; + + public DeidentifyTextResponse(String processedText, List entities, int wordCount, int charCount) { + this.processedText = processedText; + this.entities = entities; + this.wordCount = wordCount; + this.charCount = charCount; + } + + public String getProcessedText() { + return processedText; + } + + public List getEntities() { + return entities; + } + + public int getWordCount() { + return wordCount; + } + + public int getCharCount() { + return charCount; + } + + @Override + public String toString() { + Gson gson = new GsonBuilder().serializeNulls().create(); + return gson.toJson(this); + } + +} diff --git a/src/main/java/com/skyflow/vault/detect/EntityInfo.java b/src/main/java/com/skyflow/vault/detect/EntityInfo.java new file mode 100644 index 00000000..4a84acf9 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/EntityInfo.java @@ -0,0 +1,46 @@ +package com.skyflow.vault.detect; + + +import java.util.Map; + +public class EntityInfo { + private final String token; + private final String value; + private final TextIndex textIndex; + private final TextIndex processedIndex; + private final String entity; + private final Map scores; + + public EntityInfo(String token, String value, TextIndex textIndex, TextIndex processedIndex, String entity, java.util.Map scores) { + this.token = token; + this.value = value; + this.textIndex = textIndex; + this.processedIndex = processedIndex; + this.entity = entity; + this.scores = scores; + } + + public String getToken() { + return token; + } + + public String getValue() { + return value; + } + + public TextIndex getTextIndex() { + return textIndex; + } + + public TextIndex getProcessedIndex() { + return processedIndex; + } + + public String getEntity() { + return entity; + } + + public Map getScores() { + return scores; + } +} diff --git a/src/main/java/com/skyflow/vault/detect/FileEntityInfo.java b/src/main/java/com/skyflow/vault/detect/FileEntityInfo.java new file mode 100644 index 00000000..e177a99a --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/FileEntityInfo.java @@ -0,0 +1,19 @@ +package com.skyflow.vault.detect; + +import com.skyflow.generated.rest.types.DeidentifyFileOutputProcessedFileType; + +public class FileEntityInfo { + private final String file; + private final String type; + private final String extension; + + public FileEntityInfo(String file, DeidentifyFileOutputProcessedFileType type, String extension) { + this.file = file; + this.type = String.valueOf(type); + this.extension = extension; + } + + public String getFile() { return file; } + public String getType() { return type; } + public String getExtension() { return extension; } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/FileInfo.java b/src/main/java/com/skyflow/vault/detect/FileInfo.java new file mode 100644 index 00000000..2f13c4f2 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/FileInfo.java @@ -0,0 +1,33 @@ +package com.skyflow.vault.detect; + +import java.io.File; + +public class FileInfo { + private String name; + private long size; + private String type; + private long lastModified; + + public FileInfo(File file) { + this.name = file.getName(); + this.size = file.length(); + this.type = ""; + this.lastModified = file.lastModified(); + } + + public String getName() { + return name; + } + + public long getSize() { + return size; + } + + public String getType() { + return type; + } + + public long getLastModified() { + return lastModified; + } +} diff --git a/src/main/java/com/skyflow/vault/detect/FileInput.java b/src/main/java/com/skyflow/vault/detect/FileInput.java new file mode 100644 index 00000000..3ff1a77e --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/FileInput.java @@ -0,0 +1,46 @@ +package com.skyflow.vault.detect; + +import java.io.File; + +public class FileInput { + private final FileInputBuilder builder; + + private FileInput(FileInputBuilder builder) { + this.builder = builder; + } + + public static FileInputBuilder builder() { + return new FileInputBuilder(); + } + + public File getFile() { + return this.builder.file; + } + + public String getFilePath() { + return this.builder.filePath; + } + + public static final class FileInputBuilder { + private File file; + private String filePath; + + private FileInputBuilder() { + // Default constructor + } + + public FileInputBuilder file(File file) { + this.file = file; + return this; + } + + public FileInputBuilder filePath(String filePath) { + this.filePath = filePath; + return this; + } + + public FileInput build() { + return new FileInput(this); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/GetDetectRunRequest.java b/src/main/java/com/skyflow/vault/detect/GetDetectRunRequest.java new file mode 100644 index 00000000..cebec9f2 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/GetDetectRunRequest.java @@ -0,0 +1,33 @@ +package com.skyflow.vault.detect; + +public class GetDetectRunRequest { + private final String runId; + + private GetDetectRunRequest(GetDetectRunRequestBuilder builder) { + this.runId = builder.runId; + } + + public static GetDetectRunRequestBuilder builder() { + return new GetDetectRunRequestBuilder(); + } + + public String getRunId() { + return this.runId; + } + + public static final class GetDetectRunRequestBuilder { + private String runId; + + private GetDetectRunRequestBuilder() { + } + + public GetDetectRunRequestBuilder runId(String runId) { + this.runId = runId; + return this; + } + + public GetDetectRunRequest build() { + return new GetDetectRunRequest(this); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/ReidentifyTextRequest.java b/src/main/java/com/skyflow/vault/detect/ReidentifyTextRequest.java new file mode 100644 index 00000000..cc0e216a --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/ReidentifyTextRequest.java @@ -0,0 +1,68 @@ +package com.skyflow.vault.detect; + + +import com.skyflow.enums.DetectEntities; + +import java.util.List; + +public class ReidentifyTextRequest { + private final ReidentifyTextRequestBuilder builder; + + private ReidentifyTextRequest(ReidentifyTextRequestBuilder builder) { + this.builder = builder; + } + + public static ReidentifyTextRequestBuilder builder() { + return new ReidentifyTextRequestBuilder(); + } + + public String getText() { + return this.builder.text; + } + + public List getRedactedEntities() { + return this.builder.redactedEntities; + } + + public List getMaskedEntities() { + return this.builder.maskedEntities; + } + + public List getPlainTextEntities() { + return this.builder.plainTextEntities; + } + + public static final class ReidentifyTextRequestBuilder { + private String text; + private List redactedEntities; + private List maskedEntities; + private List plainTextEntities; + + private ReidentifyTextRequestBuilder() { + } + + public ReidentifyTextRequestBuilder text(String text) { + this.text = text; + return this; + } + + public ReidentifyTextRequestBuilder redactedEntities(List redactedEntities) { + this.redactedEntities = redactedEntities; + return this; + } + + public ReidentifyTextRequestBuilder maskedEntities(List maskedEntities) { + this.maskedEntities = maskedEntities; + return this; + } + + public ReidentifyTextRequestBuilder plainTextEntities(List plainTextEntities) { + this.plainTextEntities = plainTextEntities; + return this; + } + + public ReidentifyTextRequest build() { + return new ReidentifyTextRequest(this); + } + } +} diff --git a/src/main/java/com/skyflow/vault/detect/ReidentifyTextResponse.java b/src/main/java/com/skyflow/vault/detect/ReidentifyTextResponse.java new file mode 100644 index 00000000..3a517968 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/ReidentifyTextResponse.java @@ -0,0 +1,23 @@ +package com.skyflow.vault.detect; + + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class ReidentifyTextResponse { + private final String processedText; + + public ReidentifyTextResponse(String processedText) { + this.processedText = processedText; + } + + public String getProcessedText() { + return processedText; + } + + @Override + public String toString() { + Gson gson = new GsonBuilder().serializeNulls().create(); + return gson.toJson(this); + } +} diff --git a/src/main/java/com/skyflow/vault/detect/TextIndex.java b/src/main/java/com/skyflow/vault/detect/TextIndex.java new file mode 100644 index 00000000..6fe99c1d --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/TextIndex.java @@ -0,0 +1,29 @@ +package com.skyflow.vault.detect; + + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class TextIndex { + private final Integer start; + private final Integer end; + + public TextIndex(Integer start, Integer end) { + this.start = start; + this.end = end; + } + + public int getStart() { + return start; + } + + public int getEnd() { + return end; + } + + @Override + public String toString() { + Gson gson = new GsonBuilder().serializeNulls().create(); + return gson.toJson(this); + } +} diff --git a/src/main/java/com/skyflow/vault/detect/TokenFormat.java b/src/main/java/com/skyflow/vault/detect/TokenFormat.java new file mode 100644 index 00000000..8809d0a3 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/TokenFormat.java @@ -0,0 +1,71 @@ +package com.skyflow.vault.detect; + + +import com.skyflow.enums.DetectEntities; +import com.skyflow.enums.TokenType; + +import java.util.List; + + +public class TokenFormat { + private final TokenFormatBuilder builder; + + private TokenFormat(TokenFormatBuilder builder) { + this.builder = builder; + } + + public static TokenFormatBuilder builder() { + return new TokenFormatBuilder(); + } + + public TokenType getDefault() { + return this.builder.defaultType; + } + + public List getVaultToken() { + return this.builder.vaultToken; + } + + public List getEntityUniqueCounter() { + return this.builder.entityUniqueCounter; + } + + public List getEntityOnly() { + return this.builder.entityOnly; + } + + public static final class TokenFormatBuilder { + private TokenType defaultType; + private List vaultToken; + private List entityUniqueCounter; + private List entityOnly; + + private TokenFormatBuilder() { + this.defaultType = TokenType.ENTITY_UNIQUE_COUNTER; + } + + public TokenFormatBuilder defaultType(TokenType defaultType) { + this.defaultType = defaultType != null ? defaultType : TokenType.ENTITY_UNIQUE_COUNTER; + return this; + } + + public TokenFormatBuilder vaultToken(List vaultToken) { + this.vaultToken = vaultToken; + return this; + } + + public TokenFormatBuilder entityUniqueCounter(List entityUniqueCounter) { + this.entityUniqueCounter = entityUniqueCounter; + return this; + } + + public TokenFormatBuilder entityOnly(List entityOnly) { + this.entityOnly = entityOnly; + return this; + } + + public TokenFormat build() { + return new TokenFormat(this); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/Transformations.java b/src/main/java/com/skyflow/vault/detect/Transformations.java new file mode 100644 index 00000000..2e219101 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/Transformations.java @@ -0,0 +1,14 @@ +package com.skyflow.vault.detect; + + +public class Transformations { + private final DateTransformation shiftDates; + + public Transformations(DateTransformation shiftDates) { + this.shiftDates = shiftDates; + } + + public DateTransformation getShiftDates() { + return shiftDates; + } +} diff --git a/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java index 0904d6b6..7d2ae73c 100644 --- a/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java @@ -1,6 +1,7 @@ package com.skyflow.vault.tokens; -import com.skyflow.generated.rest.models.V1DetokenizeRecordResponse; + +import com.skyflow.generated.rest.types.V1DetokenizeRecordResponse; public class DetokenizeRecordResponse { private final String token; @@ -14,13 +15,23 @@ public DetokenizeRecordResponse(V1DetokenizeRecordResponse record) { } public DetokenizeRecordResponse(V1DetokenizeRecordResponse record, String requestId) { - this.token = record.getToken(); - this.value = record.getValue().isEmpty() ? null : record.getValue(); - this.type = record.getValueType().getValue().equals("NONE") ? null : record.getValueType().getValue(); - this.error = record.getError(); + this.token = record.getToken().orElse(null); + + this.value = record.getValue() + .filter(val -> val != null && !val.toString().isEmpty()) + .orElse(null); + + this.type = record.getValueType() + .map(Enum::toString) + .filter(val -> !"NONE".equals(val)) + .orElse(null); + + this.error = record.getError().orElse(null); + this.requestId = requestId; } + public String getError() { return error; } diff --git a/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java b/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java index a0e48273..d8d8072b 100644 --- a/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java +++ b/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java @@ -27,7 +27,7 @@ public String toString() { newTokensArray.add(jsonObject); } responseObject.add("tokens", newTokensArray); - responseObject.add("errors", new JsonArray()); + responseObject.add("errors", null); return responseObject.toString(); } } diff --git a/src/test/java/com/skyflow/SkyflowTests.java b/src/test/java/com/skyflow/SkyflowTests.java index 8ccff81d..0b44c0b4 100644 --- a/src/test/java/com/skyflow/SkyflowTests.java +++ b/src/test/java/com/skyflow/SkyflowTests.java @@ -440,4 +440,130 @@ public void testUpdateLogLevel() { } } + @Test + public void testVaultMethodWithNoConfig() { + try { + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.vault(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testVaultMethodWithValidConfig() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().addVaultConfig(config).build(); + Assert.assertNotNull(skyflowClient.vault()); + Assert.assertNotNull(skyflowClient.vault(vaultID)); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testVaultMethodWithInvalidVaultId() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().addVaultConfig(config).build(); + skyflowClient.vault("invalid_vault_id"); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testConnectionMethodWithNoConfig() { + try { + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.connection(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.ConnectionIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testConnectionMethodWithValidConfig() { + try { + ConnectionConfig config = new ConnectionConfig(); + config.setConnectionId(connectionID); + config.setConnectionUrl(connectionURL); + Skyflow skyflowClient = Skyflow.builder().addConnectionConfig(config).build(); + Assert.assertNotNull(skyflowClient.connection()); + Assert.assertNotNull(skyflowClient.connection(connectionID)); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testConnectionMethodWithInvalidConnectionId() { + try { + ConnectionConfig config = new ConnectionConfig(); + config.setConnectionId(connectionID); + config.setConnectionUrl(connectionURL); + Skyflow skyflowClient = Skyflow.builder().addConnectionConfig(config).build(); + skyflowClient.connection("invalid_connection_id"); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.ConnectionIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testDetectMethodWithNoConfig() { + try { + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.detect(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testDetectMethodWithValidConfig() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().addVaultConfig(config).build(); + Assert.assertNotNull(skyflowClient.detect()); + Assert.assertNotNull(skyflowClient.detect(vaultID)); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testDetectMethodWithInvalidVaultId() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().addVaultConfig(config).build(); + skyflowClient.detect("invalid_vault_id"); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } } diff --git a/src/test/java/com/skyflow/VaultClientTests.java b/src/test/java/com/skyflow/VaultClientTests.java index 0cd99614..1ebb1b23 100644 --- a/src/test/java/com/skyflow/VaultClientTests.java +++ b/src/test/java/com/skyflow/VaultClientTests.java @@ -2,12 +2,31 @@ import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; -import com.skyflow.enums.Env; -import com.skyflow.enums.TokenMode; -import com.skyflow.generated.rest.auth.HttpBearerAuth; -import com.skyflow.generated.rest.models.*; +import com.skyflow.enums.*; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.resources.files.FilesClient; +import com.skyflow.generated.rest.resources.files.requests.*; +import com.skyflow.generated.rest.resources.query.QueryClient; +import com.skyflow.generated.rest.resources.records.RecordsClient; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.resources.strings.StringsClient; +import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; +import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; +import com.skyflow.generated.rest.resources.tokens.TokensClient; +import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; +import com.skyflow.generated.rest.types.DeidentifyStringResponse; +import com.skyflow.generated.rest.types.DetectedEntity; +import com.skyflow.generated.rest.types.EntityLocation; +import com.skyflow.generated.rest.types.V1Byot; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.UpdateRequest; +import com.skyflow.vault.detect.*; +import com.skyflow.vault.detect.DeidentifyFileRequest; +import com.skyflow.vault.detect.DeidentifyTextRequest; import com.skyflow.vault.tokens.ColumnValue; import com.skyflow.vault.tokens.DetokenizeData; import com.skyflow.vault.tokens.DetokenizeRequest; @@ -17,13 +36,11 @@ import org.junit.BeforeClass; import org.junit.Test; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; +import java.io.File; +import java.util.*; public class VaultClientTests { private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; - private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; private static VaultClient vaultClient; private static String vaultID = null; private static String clusterID = null; @@ -31,7 +48,7 @@ public class VaultClientTests { private static String table = null; private static String value = null; private static String columnGroup = null; - private static String apiKey = null; + private static String apiKey = "sky-ab123-abcd1234cdef1234abcd4321cdef4321"; private static ArrayList detokenizeData = null; private static ArrayList> insertValues = null; private static ArrayList> insertTokens = null; @@ -40,7 +57,7 @@ public class VaultClientTests { private static VaultConfig vaultConfig; @BeforeClass - public static void setup() { + public static void setup() throws SkyflowException { vaultID = "vault123"; clusterID = "cluster123"; token = "test_token"; @@ -48,44 +65,62 @@ public static void setup() { table = "test_table"; value = "test_value"; columnGroup = "test_column_group"; - apiKey = "sky-ab123-abcd1234cdef1234abcd4321cdef4321"; + apiKey = null; insertValues = new ArrayList<>(); insertTokens = new ArrayList<>(); valueMap = new HashMap<>(); tokenMap = new HashMap<>(); - Credentials credentials = new Credentials(); - credentials.setApiKey(apiKey); - vaultConfig = new VaultConfig(); vaultConfig.setVaultId(vaultID); vaultConfig.setClusterId(clusterID); vaultConfig.setEnv(Env.PROD); + + Credentials credentials = new Credentials(); + credentials.setApiKey("sky-ab123-abcd1234cdef1234abcd4321cdef4321"); + vaultConfig.setCredentials(credentials); vaultClient = new VaultClient(vaultConfig, credentials); + vaultClient.setBearerToken(); } @Test - public void testVaultClientGetApiClient() { + public void testVaultClientGetRecordsAPI() { try { - Assert.assertNotNull(vaultClient.getApiClient()); + RecordsClient recordsClient = vaultClient.getRecordsApi(); + Assert.assertNotNull(recordsClient); } catch (Exception e) { - Assert.fail(INVALID_EXCEPTION_THROWN); + e.printStackTrace(); + Assert.fail(INVALID_EXCEPTION_THROWN + e.getMessage()); } } @Test - public void testVaultClientGetRecordsAPI() { + public void testVaultClientDetectAPI() { try { - Assert.assertNotNull(vaultClient.getRecordsApi()); + FilesClient filesClient = vaultClient.getDetectFileAPi(); + Assert.assertNotNull(filesClient); } catch (Exception e) { - Assert.fail(INVALID_EXCEPTION_THROWN); + e.printStackTrace(); + Assert.fail(INVALID_EXCEPTION_THROWN + e.getMessage()); + } + } + + @Test + public void testVaultClientDetectTextAPI() { + try { + StringsClient stringsClient = vaultClient.getDetectTextApi(); + Assert.assertNotNull(stringsClient); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(INVALID_EXCEPTION_THROWN + e.getMessage()); } } @Test public void testVaultClientGetTokensAPI() { try { - Assert.assertNotNull(vaultClient.getTokensApi()); + TokensClient tokensClient = vaultClient.getTokensApi(); + Assert.assertNotNull(tokensClient); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } @@ -94,7 +129,8 @@ public void testVaultClientGetTokensAPI() { @Test public void testVaultClientGetQueryAPI() { try { - Assert.assertNotNull(vaultClient.getQueryApi()); + QueryClient queryClient = vaultClient.getQueryApi(); + Assert.assertNotNull(queryClient); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } @@ -121,11 +157,14 @@ public void testGetDetokenizePayload() { detokenizeData.add(detokenizeDataRecord1); detokenizeData.add(detokenizeDataRecord2); DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() - .detokenizeData(detokenizeData).downloadURL(true).build(); + .detokenizeData(detokenizeData) + .downloadURL(true) + .continueOnError(false) + .build(); V1DetokenizePayload payload = vaultClient.getDetokenizePayload(detokenizeRequest); - Assert.assertFalse(payload.getContinueOnError()); - Assert.assertTrue(payload.getDownloadURL()); - Assert.assertEquals(2, payload.getDetokenizationParameters().size()); + Assert.assertFalse(payload.getContinueOnError().get()); + Assert.assertTrue(payload.getDownloadUrl().get()); + Assert.assertEquals(2, payload.getDetokenizationParameters().get().size()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } @@ -152,13 +191,16 @@ public void testGetBulkInsertRequestBody() { .returnTokens(true) .build(); RecordServiceInsertRecordBody body1 = vaultClient.getBulkInsertRequestBody(insertRequest1); - Assert.assertTrue(body1.getTokenization()); - Assert.assertNull(body1.getUpsert()); - Assert.assertEquals(2, body1.getRecords().size()); + Assert.assertTrue(body1.getTokenization().get()); + Assert.assertEquals(V1Byot.ENABLE, body1.getByot().get()); + Assert.assertEquals(2, body1.getRecords().get().size()); - InsertRequest insertRequest2 = InsertRequest.builder().table(table).values(insertValues).build(); + InsertRequest insertRequest2 = InsertRequest.builder() + .table(table) + .values(insertValues) + .build(); RecordServiceInsertRecordBody body2 = vaultClient.getBulkInsertRequestBody(insertRequest2); - Assert.assertEquals(2, body2.getRecords().size()); + Assert.assertEquals(2, body2.getRecords().get().size()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } @@ -185,12 +227,12 @@ public void testGetBatchInsertRequestBody() { .returnTokens(false) .build(); RecordServiceBatchOperationBody body1 = vaultClient.getBatchInsertRequestBody(insertRequest1); - Assert.assertTrue(body1.getContinueOnError()); - Assert.assertEquals(2, body1.getRecords().size()); + Assert.assertTrue(body1.getContinueOnError().get()); + Assert.assertEquals(2, body1.getRecords().get().size()); InsertRequest insertRequest2 = InsertRequest.builder().table(table).values(insertValues).build(); RecordServiceBatchOperationBody body2 = vaultClient.getBatchInsertRequestBody(insertRequest2); - Assert.assertEquals(2, body2.getRecords().size()); + Assert.assertEquals(2, body2.getRecords().get().size()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } @@ -211,7 +253,7 @@ public void testGetUpdateRequestBodyWithTokens() { .returnTokens(true) .build(); RecordServiceUpdateRecordBody body = vaultClient.getUpdateRequestBody(updateRequest); - Assert.assertTrue(body.getTokenization()); + Assert.assertTrue(body.getTokenization().get()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } @@ -231,7 +273,7 @@ public void testGetUpdateRequestBodyWithoutTokens() { .returnTokens(false) .build(); RecordServiceUpdateRecordBody body = vaultClient.getUpdateRequestBody(updateRequest); - Assert.assertFalse(body.getTokenization()); + Assert.assertFalse(body.getTokenization().get()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } @@ -245,7 +287,7 @@ public void testGetTokenizePayload() { columnValues.add(columnValue); TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); V1TokenizePayload payload = vaultClient.getTokenizePayload(tokenizeRequest); - Assert.assertEquals(1, payload.getTokenizationParameters().size()); + Assert.assertEquals(1, payload.getTokenizationParameters().get().size()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } @@ -254,22 +296,18 @@ public void testGetTokenizePayload() { @Test public void testSetBearerToken() { try { - Dotenv dotenv = Dotenv.load(); - String bearerToken = dotenv.get("TEST_REUSABLE_TOKEN"); Credentials credentials = new Credentials(); - credentials.setToken(bearerToken); + credentials.setApiKey("sky-ab123-abcd1234cdef1234abcd4321cdef4321"); vaultConfig.setCredentials(credentials); - vaultClient.updateVaultConfig(); - - // regular scenario + vaultClient = new VaultClient(vaultConfig, credentials); vaultClient.setBearerToken(); - // re-use scenario + Assert.assertNotNull(vaultClient.getTokensApi()); + vaultClient.setBearerToken(); - HttpBearerAuth auth = (HttpBearerAuth) vaultClient.getApiClient().getAuthentication("Bearer"); - Assert.assertEquals(bearerToken, auth.getBearerToken()); + Assert.assertNotNull(vaultClient.getTokensApi()); } catch (Exception e) { - Assert.fail(INVALID_EXCEPTION_THROWN); + Assert.fail(INVALID_EXCEPTION_THROWN + ": " + e.getMessage()); } } @@ -277,8 +315,8 @@ public void testSetBearerToken() { public void testSetBearerTokenWithApiKey() { try { Credentials credentials = new Credentials(); - credentials.setApiKey(apiKey); - vaultConfig.setCredentials(null); + credentials.setApiKey("sky-ab123-abcd1234cdef1234abcd4321cdef4321"); // Use a non-null dummy API key + vaultConfig.setCredentials(credentials); vaultClient.updateVaultConfig(); vaultClient.setCommonCredentials(credentials); @@ -287,22 +325,609 @@ public void testSetBearerTokenWithApiKey() { // re-use scenario vaultClient.setBearerToken(); - HttpBearerAuth auth = (HttpBearerAuth) vaultClient.getApiClient().getAuthentication("Bearer"); - Assert.assertEquals(apiKey, auth.getBearerToken()); + + // If no exception is thrown, the test passes + Assert.assertTrue(true); } catch (Exception e) { - Assert.fail(INVALID_EXCEPTION_THROWN); + Assert.fail(INVALID_EXCEPTION_THROWN + ": " + e.getMessage()); } } @Test public void testSetBearerTokenWithEnvCredentials() { try { + Dotenv dotenv = Dotenv.load(); vaultConfig.setCredentials(null); vaultClient.updateVaultConfig(); vaultClient.setCommonCredentials(null); + vaultClient.setBearerToken(); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); Assert.assertNull(vaultClient.getVaultConfig().getCredentials()); } catch (Exception e) { Assert.fail(INVALID_EXCEPTION_THROWN); } } + + @Test + public void testGetDeIdentifyTextResponse() { + List entities = new ArrayList<>(); + EntityLocation location = EntityLocation.builder() + .startIndex(2) + .endIndex(10) + .startIndexProcessed(3) + .endIndexProcessed(8) + .build(); + + DetectedEntity detectedEntity = DetectedEntity.builder() + .token("token123") + .value("value123") + .location(location) + .build(); + entities.add(detectedEntity); + + DeidentifyStringResponse response = DeidentifyStringResponse.builder() + .processedText("processed text") + .wordCount(2) + .characterCount(13) + .entities(entities) + .build(); + + + DeidentifyTextResponse result = vaultClient.getDeIdentifyTextResponse(response); + + Assert.assertNotNull(result); + Assert.assertEquals("processed text", result.getProcessedText()); + Assert.assertEquals(2, result.getWordCount()); + Assert.assertEquals(13, result.getCharCount()); + Assert.assertNotNull(result.getEntities()); + Assert.assertEquals(1, result.getEntities().size()); + Assert.assertEquals("token123", result.getEntities().get(0).getToken()); + Assert.assertEquals("value123", result.getEntities().get(0).getValue()); + Assert.assertEquals(2, result.getEntities().get(0).getTextIndex().getStart()); + Assert.assertEquals(10, result.getEntities().get(0).getTextIndex().getEnd()); + Assert.assertEquals(3, result.getEntities().get(0).getProcessedIndex().getStart()); + Assert.assertEquals(8, result.getEntities().get(0).getProcessedIndex().getEnd()); + } + + @Test + public void testGetDeidentifyStringRequest() { + + List detectEntitiesList = new ArrayList<>(); + detectEntitiesList.add(DetectEntities.NAME); + + List vaultTokenList = new ArrayList<>(); + vaultTokenList.add(DetectEntities.SSN); + + + List entityOnlyList = new ArrayList<>(); + entityOnlyList.add(DetectEntities.DOB); + + List entityUniqueCounterList = new ArrayList<>(); + entityUniqueCounterList.add(DetectEntities.NAME); + + + List restrictRegexList = new ArrayList<>(); + restrictRegexList.add("([0-9]{3}-[0-9]{2}-[0-9]{4})"); + + TokenFormat tokenFormat = TokenFormat.builder() + .vaultToken(vaultTokenList) + .entityOnly(entityOnlyList) + .entityUniqueCounter(entityUniqueCounterList) + .build(); + + + List detectEntitiesTransformationList = new ArrayList<>(); + detectEntitiesTransformationList.add(DetectEntities.DOB); + detectEntitiesTransformationList.add(DetectEntities.DATE); + + DateTransformation dateTransformation = new DateTransformation(20, 5, detectEntitiesTransformationList); + Transformations transformations = new Transformations(dateTransformation); + + + DeidentifyTextRequest req = DeidentifyTextRequest.builder() + .text("Sensitive data to deidentify, like Name: Joy SSN 123-45-6789 and DOB 01-01-2000.") + .entities(detectEntitiesList) + .restrictRegexList(restrictRegexList) + .tokenFormat(tokenFormat) + .transformations(transformations) + .build(); + + } + + @Test + public void testDeidentifyFileRequestBuilderAndGetters() { + File file = new File("testfile.txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + DetectEntities entity = DetectEntities.NAME; + String allowRegex = "^[A-Za-z]+$"; + String restrictRegex = "\\d+"; + TokenFormat tokenFormat = TokenFormat.builder().vaultToken(Collections.singletonList(entity)).build(); + Boolean outputProcessedImage = true; + Boolean outputOcrText = true; + MaskingMethod maskingMethod = MaskingMethod.BLACKBOX; + Double pixelDensity = 300.0; + Double maxResolution = 1024.0; + Boolean outputProcessedAudio = false; + DetectOutputTranscriptions outputTranscription = DetectOutputTranscriptions.TRANSCRIPTION; + AudioBleep bleep = AudioBleep.builder().gain(20.0).build(); + String outputDirectory = "/tmp"; + Integer waitTime = 10; + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(Arrays.asList(entity)) + .allowRegexList(Collections.singletonList(allowRegex)) + .restrictRegexList(Collections.singletonList(restrictRegex)) + .tokenFormat(tokenFormat) + .outputProcessedImage(outputProcessedImage) + .outputOcrText(outputOcrText) + .maskingMethod(maskingMethod) + .pixelDensity(pixelDensity) + .maxResolution(maxResolution) + .outputProcessedAudio(outputProcessedAudio) + .outputTranscription(outputTranscription) + .bleep(bleep) + .outputDirectory(outputDirectory) + .waitTime(waitTime) + .build(); + + Assert.assertEquals(file, request.getFileInput().getFile()); + Assert.assertEquals(1, request.getEntities().size()); + Assert.assertEquals(allowRegex, request.getAllowRegexList().get(0)); + Assert.assertEquals(restrictRegex, request.getRestrictRegexList().get(0)); + Assert.assertEquals(tokenFormat, request.getTokenFormat()); + Assert.assertEquals(outputProcessedImage, request.getOutputProcessedImage()); + Assert.assertEquals(outputOcrText, request.getOutputOcrText()); + Assert.assertEquals(maskingMethod, request.getMaskingMethod()); + Assert.assertEquals(pixelDensity, request.getPixelDensity()); + Assert.assertEquals(maxResolution, request.getMaxResolution()); + Assert.assertEquals(outputProcessedAudio, request.getOutputProcessedAudio()); + Assert.assertEquals(outputTranscription, request.getOutputTranscription()); + Assert.assertEquals(bleep, request.getBleep()); + Assert.assertEquals(outputDirectory, request.getOutputDirectory()); + Assert.assertEquals(waitTime, request.getWaitTime()); + } + + @Test + public void testDeidentifyFileRequestBuilderDefaults() { + DeidentifyFileRequest request = DeidentifyFileRequest.builder().build(); + Assert.assertNull(request.getEntities()); + Assert.assertNull(request.getAllowRegexList()); + Assert.assertNull(request.getRestrictRegexList()); + Assert.assertNull(request.getTokenFormat()); + Assert.assertNull(request.getTransformations()); + Assert.assertEquals(false, request.getOutputProcessedImage()); + Assert.assertEquals(false, request.getOutputOcrText()); + Assert.assertNull(request.getMaskingMethod()); + Assert.assertNull(request.getPixelDensity()); + Assert.assertNull(request.getMaxResolution()); + Assert.assertEquals(false, request.getOutputProcessedAudio()); + Assert.assertNull(request.getOutputTranscription()); + Assert.assertNull(request.getBleep()); + Assert.assertNull(request.getOutputDirectory()); + Assert.assertNull(request.getWaitTime()); + } + + @Test + public void testGetDeidentifyImageRequest() { + File file = new File("test.jpg"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME, DetectEntities.DOB); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .outputProcessedImage(true) + .outputOcrText(true) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String format = "jpg"; + + DeidentifyImageRequest imageRequest = vaultClient.getDeidentifyImageRequest(request, vaultId, base64Content, format); + + Assert.assertEquals(vaultId, imageRequest.getVaultId()); + Assert.assertEquals(base64Content, imageRequest.getFile().getBase64()); + Assert.assertEquals(format.toUpperCase(), imageRequest.getFile().getDataFormat().name()); + } + + @Test + public void testGetDeidentifyPresentationRequest() { + File file = new File("test.pptx"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String format = "pptx"; + + DeidentifyPresentationRequest presRequest = vaultClient.getDeidentifyPresentationRequest(request, vaultId, base64Content, format); + + Assert.assertEquals(vaultId, presRequest.getVaultId()); + Assert.assertEquals(base64Content, presRequest.getFile().getBase64()); + Assert.assertEquals(format.toUpperCase(), presRequest.getFile().getDataFormat().name()); + } + + @Test + public void testGetDeidentifySpreadsheetRequest() { + File file = new File("test.csv"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String format = "csv"; + + DeidentifySpreadsheetRequest spreadsheetRequest = vaultClient.getDeidentifySpreadsheetRequest(request, vaultId, base64Content, format); + + Assert.assertEquals(vaultId, spreadsheetRequest.getVaultId()); + Assert.assertEquals(base64Content, spreadsheetRequest.getFile().getBase64()); + Assert.assertEquals(format.toUpperCase(), spreadsheetRequest.getFile().getDataFormat().name()); + } + + @Test + public void testGetDeidentifyStructuredTextRequest() { + File file = new File("test.json"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String format = "json"; + + DeidentifyStructuredTextRequest structuredTextRequest = vaultClient.getDeidentifyStructuredTextRequest(request, vaultId, base64Content, format); + + Assert.assertEquals(vaultId, structuredTextRequest.getVaultId()); + Assert.assertEquals(base64Content, structuredTextRequest.getFile().getBase64()); + Assert.assertEquals(format.toUpperCase(), structuredTextRequest.getFile().getDataFormat().name()); + } + + @Test + public void testGetDeidentifyDocumentRequest() { + File file = new File("test.docx"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String format = "docx"; + + DeidentifyDocumentRequest documentRequest = vaultClient.getDeidentifyDocumentRequest(request, vaultId, base64Content, format); + + Assert.assertEquals(vaultId, documentRequest.getVaultId()); + Assert.assertEquals(base64Content, documentRequest.getFile().getBase64()); + Assert.assertEquals(format.toUpperCase(), documentRequest.getFile().getDataFormat().name()); + } + + @Test + public void testGetDeidentifyPdfRequest() { + File file = new File("test.pdf"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .pixelDensity(200) + .maxResolution(300) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + + DeidentifyPdfRequest pdfRequest = vaultClient.getDeidentifyPdfRequest(request, vaultId, base64Content); + + Assert.assertEquals(vaultId, pdfRequest.getVaultId()); + Assert.assertEquals(base64Content, pdfRequest.getFile().getBase64()); + } + + @Test + public void testGetDeidentifyAudioRequest() throws SkyflowException { + File file = new File("test.mp3"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + AudioBleep bleep = AudioBleep.builder().frequency(1000.0).gain(10.0).startPadding(1.0).stopPadding(1.0).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .bleep(bleep) + .outputProcessedAudio(true) + .outputTranscription(DetectOutputTranscriptions.PLAINTEXT_TRANSCRIPTION) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String dataFormat = "mp3"; + + DeidentifyAudioRequest audioRequest = vaultClient.getDeidentifyAudioRequest(request, vaultId, base64Content, dataFormat); + + Assert.assertEquals(vaultId, audioRequest.getVaultId()); + Assert.assertEquals(base64Content, audioRequest.getFile().getBase64()); + Assert.assertEquals(dataFormat, audioRequest.getFile().getDataFormat().toString()); + } + + @Test + public void testGetDeidentifyTextFileRequest() { + File file = new File("test.txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME, DetectEntities.DOB); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + + com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest textRequest = + vaultClient.getDeidentifyTextFileRequest(request, vaultId, base64Content); + + Assert.assertEquals(vaultId, textRequest.getVaultId()); + Assert.assertEquals(base64Content, textRequest.getFile().getBase64()); + } + + @Test + public void testGetDeidentifyStringRequest_AllTokenFormatFields() throws Exception { + List entities = Arrays.asList(DetectEntities.DOB); + List vaultToken = Collections.singletonList(DetectEntities.SSN); + List entityOnly = Collections.singletonList(DetectEntities.DOB); + List entityUniqueCounter = Collections.singletonList(DetectEntities.NAME); + + TokenFormat tokenFormat = TokenFormat.builder() + .vaultToken(vaultToken) + .entityOnly(entityOnly) + .entityUniqueCounter(entityUniqueCounter) + .build(); + + List allowRegex = Collections.singletonList("a.*"); + List restrictRegex = Collections.singletonList("b.*"); + + DateTransformation dateTransformation = new DateTransformation(10, 5, entities); + Transformations transformations = new Transformations(dateTransformation); + + DeidentifyTextRequest req = DeidentifyTextRequest.builder() + .text("Sensitive data") + .entities(entities) + .allowRegexList(allowRegex) + .restrictRegexList(restrictRegex) + .tokenFormat(tokenFormat) + .transformations(transformations) + .build(); + + DeidentifyStringRequest result = vaultClient.getDeidentifyStringRequest(req, "vaultId"); + Assert.assertNotNull(result); + Assert.assertEquals("vaultId", result.getVaultId()); + Assert.assertEquals("Sensitive data", result.getText()); + Assert.assertTrue(result.getAllowRegex().isPresent()); + Assert.assertTrue(result.getRestrictRegex().isPresent()); + Assert.assertTrue(result.getTransformations().isPresent()); + } + + @Test + public void testGetDeidentifyStringRequest_NullTokenFormatAndEntities() throws Exception { + DeidentifyTextRequest req = DeidentifyTextRequest.builder() + .text("No entities or tokenFormat") + .build(); + + DeidentifyStringRequest result = vaultClient.getDeidentifyStringRequest(req, "vaultId"); + Assert.assertNotNull(result); + Assert.assertEquals("vaultId", result.getVaultId()); + Assert.assertEquals("No entities or tokenFormat", result.getText()); + } + + @Test + public void testGetReidentifyStringRequest_AllFields() throws Exception { + List masked = Arrays.asList(DetectEntities.NAME, DetectEntities.DOB); + List plaintext = Collections.singletonList(DetectEntities.SSN); + List redacted = Collections.singletonList(DetectEntities.DATE); + + ReidentifyTextRequest req = ReidentifyTextRequest.builder() + .text("Sensitive data") + .maskedEntities(masked) + .plainTextEntities(plaintext) + .redactedEntities(redacted) + .build(); + + ReidentifyStringRequest result = vaultClient.getReidentifyStringRequest(req, "vaultId"); + Assert.assertNotNull(result); + Assert.assertEquals("vaultId", result.getVaultId()); + Assert.assertEquals("Sensitive data", result.getText()); + Assert.assertNotNull(result.getFormat()); + } + + @Test + public void testGetReidentifyStringRequest_NullFields() throws Exception { + ReidentifyTextRequest req = ReidentifyTextRequest.builder() + .text("No entities") + .build(); + + ReidentifyStringRequest result = vaultClient.getReidentifyStringRequest(req, "vaultId"); + Assert.assertNotNull(result); + Assert.assertEquals("vaultId", result.getVaultId()); + Assert.assertEquals("No entities", result.getText()); + Assert.assertNotNull(result.getFormat()); + } + + @Test + public void testGetTransformations_NullInput() throws Exception { + // Should return null if input is null + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("getTransformations", Transformations.class); + method.setAccessible(true); + Object result = method.invoke(vaultClient, new Object[]{null}); + Assert.assertNull(result); + } + + @Test + public void testGetTransformations_NullShiftDates() throws Exception { + Transformations transformations = new Transformations(null); + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("getTransformations", Transformations.class); + method.setAccessible(true); + Object result = method.invoke(vaultClient, transformations); + Assert.assertNull(result); + } + + @Test + public void testGetTransformations_EmptyEntities() throws Exception { + DateTransformation dateTransformation = new DateTransformation(10, 5, new ArrayList<>()); + Transformations transformations = new Transformations(dateTransformation); + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("getTransformations", Transformations.class); + method.setAccessible(true); + Object result = method.invoke(vaultClient, transformations); + Assert.assertNotNull(result); + // Should have empty entityTypes list + com.skyflow.generated.rest.types.Transformations restTransform = (com.skyflow.generated.rest.types.Transformations) result; + Assert.assertTrue(restTransform.getShiftDates().get().getEntityTypes().get().isEmpty()); + } + + @Test + public void testGetTransformations_WithEntities() throws Exception { + List entities = Arrays.asList(DetectEntities.DOB, DetectEntities.DATE); + DateTransformation dateTransformation = new DateTransformation(20, 5, entities); + Transformations transformations = new Transformations(dateTransformation); + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("getTransformations", Transformations.class); + method.setAccessible(true); + Object result = method.invoke(vaultClient, transformations); + Assert.assertNotNull(result); + com.skyflow.generated.rest.types.Transformations restTransform = (com.skyflow.generated.rest.types.Transformations) result; + Assert.assertEquals(2, restTransform.getShiftDates().get().getEntityTypes().get().size()); + } + + @Test + public void testGetDeidentifyGenericFileRequest_AllFields() { + File file = new File("test.custom"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME, DetectEntities.DOB); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .allowRegexList(Arrays.asList("a.*")) + .restrictRegexList(Arrays.asList("b.*")) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String fileExtension = "txt"; + + com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest genericRequest = + vaultClient.getDeidentifyGenericFileRequest(request, vaultId, base64Content, fileExtension); + + Assert.assertEquals(vaultId, genericRequest.getVaultId()); + Assert.assertEquals(base64Content, genericRequest.getFile().getBase64()); + Assert.assertNotNull(genericRequest.getEntityTypes()); + Assert.assertNotNull(genericRequest.getTokenType()); + Assert.assertTrue(genericRequest.getAllowRegex().isPresent()); + Assert.assertTrue(genericRequest.getRestrictRegex().isPresent()); + } + + @Test + public void testMapAudioDataFormat_mp3() throws Exception { + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("mapAudioDataFormat", String.class); + method.setAccessible(true); + Object result = method.invoke(vaultClient, "mp3"); + Assert.assertEquals(com.skyflow.generated.rest.resources.files.types.DeidentifyAudioRequestFileDataFormat.MP_3, result); + } + + @Test + public void testMapAudioDataFormat_wav() throws Exception { + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("mapAudioDataFormat", String.class); + method.setAccessible(true); + Object result = method.invoke(vaultClient, "wav"); + Assert.assertEquals(com.skyflow.generated.rest.resources.files.types.DeidentifyAudioRequestFileDataFormat.WAV, result); + } + + @Test + public void testMapAudioDataFormat_invalid() throws Exception { + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("mapAudioDataFormat", String.class); + method.setAccessible(true); + try { + method.invoke(vaultClient, "ogg"); + Assert.fail("Should throw SkyflowException for invalid audio type"); + } catch (Exception e) { + Throwable cause = e.getCause(); + Assert.assertTrue(cause instanceof SkyflowException); + } + } + + @Test + public void testPrioritiseCredentials_VaultConfigCredentials() throws Exception { + Credentials creds = new Credentials(); + creds.setApiKey("test_api_key"); + vaultConfig.setCredentials(creds); + + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("prioritiseCredentials"); + method.setAccessible(true); + method.invoke(vaultClient); + + Assert.assertEquals(creds, getPrivateField(vaultClient, "finalCredentials")); + } + + @Test + public void testPrioritiseCredentials_CommonCredentials() throws Exception { + vaultConfig.setCredentials(null); + Credentials creds = new Credentials(); + creds.setApiKey("common_api_key"); + setPrivateField(vaultClient, "commonCredentials", creds); + + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("prioritiseCredentials"); + method.setAccessible(true); + method.invoke(vaultClient); + + Assert.assertEquals(creds, getPrivateField(vaultClient, "finalCredentials")); + } + + // Helper methods for reflection field access + private Object getPrivateField(Object obj, String fieldName) throws Exception { + java.lang.reflect.Field field = obj.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + return field.get(obj); + } + + private void setPrivateField(Object obj, String fieldName, Object value) throws Exception { + java.lang.reflect.Field field = obj.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + field.set(obj, value); + } } diff --git a/src/test/java/com/skyflow/errors/SkyflowExceptionTest.java b/src/test/java/com/skyflow/errors/SkyflowExceptionTest.java new file mode 100644 index 00000000..89e0643b --- /dev/null +++ b/src/test/java/com/skyflow/errors/SkyflowExceptionTest.java @@ -0,0 +1,98 @@ +package com.skyflow.errors; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class SkyflowExceptionTest { + + @Test + public void testConstructorWithMessage() { + SkyflowException ex = new SkyflowException("Test message"); + Assert.assertEquals("Test message", ex.getMessage()); + Assert.assertNull(ex.getHttpStatus()); + Assert.assertNull(ex.getGrpcCode()); + } + + @Test + public void testConstructorWithThrowable() { + Throwable cause = new RuntimeException("Root cause"); + SkyflowException ex = new SkyflowException(cause); + Assert.assertEquals("Root cause", ex.getMessage()); + } + + @Test + public void testConstructorWithMessageAndCause() { + Throwable cause = new RuntimeException("Root cause"); + SkyflowException ex = new SkyflowException("Test message", cause); + Assert.assertEquals("Test message", ex.getMessage()); + } + + @Test + public void testConstructorWithCodeAndMessage() { + SkyflowException ex = new SkyflowException(400, "Bad Request"); + Assert.assertEquals(Integer.valueOf(400), Integer.valueOf(ex.getHttpCode())); + Assert.assertEquals("Bad Request", ex.getMessage()); + Assert.assertEquals("Bad Request", ex.toString().contains("Bad Request") ? "Bad Request" : null); + } + + @Test + public void testToStringFormat() { + SkyflowException ex = new SkyflowException(404, "Not Found"); + String str = ex.toString(); + Assert.assertTrue(str.contains("httpCode: 404")); + Assert.assertTrue(str.contains("message: Not Found")); + } + + @Test + public void testConstructorWithJsonErrorBody() { + String json = "{\"error\":{\"message\":\"json error\",\"grpc_code\":7,\"http_status\":\"NOT_FOUND\",\"details\":[{\"info\":\"detail1\"}]}}"; + Map> headers = new HashMap<>(); + headers.put("x-request-id", Collections.singletonList("req-123")); + SkyflowException ex = new SkyflowException(404, new RuntimeException("fail"), headers, json); + Assert.assertEquals("json error", ex.getMessage()); + Assert.assertEquals(Integer.valueOf(7), ex.getGrpcCode()); + Assert.assertEquals("NOT_FOUND", ex.getHttpStatus()); + Assert.assertEquals("req-123", ex.getRequestId()); + Assert.assertNotNull(ex.getDetails()); + Assert.assertTrue(ex.getDetails().size() > 0); + } + + + @Test + public void testConstructorWithNullErrorBody() { + Map> headers = new HashMap<>(); + SkyflowException ex = new SkyflowException(500, new RuntimeException("fail"), headers, null); + Assert.assertNull(ex.getMessage()); + Assert.assertNull(ex.getGrpcCode()); + Assert.assertNull(ex.getHttpStatus()); + } + + @Test + public void testGettersAndSetters() { + SkyflowException ex = new SkyflowException("msg"); + // Simulate setting fields via reflection or constructor + // (getters are already tested above) + Assert.assertNull(ex.getRequestId()); + Assert.assertNull(ex.getDetails()); + Assert.assertNull(ex.getGrpcCode()); + Assert.assertNull(ex.getHttpStatus()); + } + + @Test + public void testSetDetailsWithErrorFromClientHeader() { + String json = "{\"error\":{\"message\":\"test error\",\"grpc_code\":13,\"details\":[]}}"; + Map> headers = new HashMap<>(); + headers.put("error-from-client", Collections.singletonList("client error")); + + SkyflowException ex = new SkyflowException(500, new RuntimeException("fail"), headers, json); + + Assert.assertNotNull(ex.getDetails()); + Assert.assertEquals(1, ex.getDetails().size()); + Assert.assertEquals("client error", ex.getDetails().get(0).getAsJsonObject().get("errorFromClient").getAsString()); + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/controller/DetectControllerFileTests.java b/src/test/java/com/skyflow/vault/controller/DetectControllerFileTests.java new file mode 100644 index 00000000..da8494e1 --- /dev/null +++ b/src/test/java/com/skyflow/vault/controller/DetectControllerFileTests.java @@ -0,0 +1,409 @@ +package com.skyflow.vault.controller; + +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.detect.AudioBleep; +import com.skyflow.vault.detect.DeidentifyFileRequest; +import com.skyflow.vault.detect.FileInput; +import com.skyflow.vault.detect.GetDetectRunRequest; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.nio.file.Files; +import java.util.ArrayList; + +public class DetectControllerFileTests { + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static VaultConfig vaultConfig = null; + private static DetectController detectController = null; + + @BeforeClass + public static void setup() { + vaultID = "vault123"; + clusterID = "cluster123"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(com.skyflow.enums.Env.DEV); + vaultConfig.setCredentials(credentials); + + detectController = new DetectController(vaultConfig, credentials); + } + + @Test + public void testUnreadableFileInDeidentifyFileRequest() { + try { + File file = new File("unreadable.txt") { + @Override + public boolean exists() { return true; } + @Override + public boolean isFile() { return true; } + @Override + public boolean canRead() { return false; } + }; + FileInput fileInput = FileInput.builder().file(file).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException | RuntimeException e) { + // Depending on implementation, could be SkyflowException or RuntimeException + Assert.assertTrue(e.getMessage().contains("not readable") || e.getMessage().contains("unreadable.txt")); + } + } + + @Test + public void testNullEntitiesInDeidentifyFileRequest() { + try { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(new ArrayList<>()) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testNullRequest() { + try { + detectController.deidentifyFile(null); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testFileInputBothFileAndFilePathNull() { + try { + FileInput fileInput = FileInput.builder().build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail("Should have thrown an exception for both file and filePath being null"); + } catch (Exception e) { + Assert.assertTrue(e.getMessage().contains(ErrorMessage.EmptyFileAndFilePathInDeIdentifyFile.getMessage())); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testFileInputBothFileAndFilePathProvided() { + try { + java.io.File file = java.io.File.createTempFile("test", ".txt"); + String filePath = file.getAbsolutePath(); + FileInput fileInput = FileInput.builder().file(file).filePath(filePath).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail("Should have thrown an exception for both file and filePath being provided"); + } catch (Exception e) { + Assert.assertTrue(e.getMessage().contains(ErrorMessage.BothFileAndFilePathProvided.getMessage())); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testFileInputEmptyFilePath() { + try { + FileInput fileInput = FileInput.builder().filePath("").build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail("Should have thrown an exception for empty filePath"); + } catch (Exception e) { + Assert.assertTrue(e.getMessage().contains(ErrorMessage.InvalidFilePath.getMessage())); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testFileInputNonExistentFile() { + try { + java.io.File file = new java.io.File("nonexistent.txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail("Should have thrown an exception for non-existent file"); + } catch (Exception e) { + Assert.assertTrue(e.getMessage().contains(ErrorMessage.FileNotFoundToDeidentify.getMessage())); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testFileInputUnreadableFile() { + try { + java.io.File file = new java.io.File("unreadable.txt") { + @Override + public boolean exists() { return true; } + @Override + public boolean isFile() { return true; } + @Override + public boolean canRead() { return false; } + }; + FileInput fileInput = FileInput.builder().file(file).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail("Should have thrown an exception for unreadable file"); + } catch (Exception e) { + Assert.assertTrue(e.getMessage().contains(ErrorMessage.FileNotReadableToDeidentify.getMessage())); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testNonExistentFileInDeidentifyFileRequest() { + try { + File file = new File("nonexistent.txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testInvalidPixelDensity() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .pixelDensity(-1) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testInvalidMaxResolution() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .maxResolution(-1) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testInvalidBleepFrequency() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + AudioBleep bleep = AudioBleep.builder().build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .bleep(bleep) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testInvalidOutputDirectory() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .outputDirectory("not/a/real/dir") + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testInvalidWaitTime() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .waitTime(-1) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testWaitTimeExceedsLimit() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .waitTime(100) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testNullGetDetectRunRequest() { + try { + detectController.getDetectRun(null); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testEmptyRunIdInGetDetectRunRequest() { + try { + GetDetectRunRequest request = GetDetectRunRequest.builder().build(); + detectController.getDetectRun(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testNullRunIdInGetDetectRunRequest() { + try { + GetDetectRunRequest request = GetDetectRunRequest.builder().runId(null).build(); + detectController.getDetectRun(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testInvalidBleepGain() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + AudioBleep bleep = AudioBleep.builder().frequency(440.0).gain(-1.0).startPadding(0.1).stopPadding(0.1).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .bleep(bleep) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testInvalidBleepStartPadding() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + AudioBleep bleep = AudioBleep.builder().frequency(440.0).gain(0.5).startPadding(-0.1).stopPadding(0.1).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .bleep(bleep) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testInvalidBleepStopPadding() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + AudioBleep bleep = AudioBleep.builder().frequency(440.0).gain(0.5).startPadding(0.1).stopPadding(-0.1).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .bleep(bleep) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testOutputDirectoryNotDirectory() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + File notADir = File.createTempFile("notadir", ".txt"); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .outputDirectory(notADir.getAbsolutePath()) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + notADir.delete(); + } + + @Test + public void testOutputDirectoryNotWritable() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + File dir = Files.createTempDirectory("notwritabledir").toFile(); + dir.setWritable(false); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .outputDirectory(dir.getAbsolutePath()) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } finally { + dir.setWritable(true); + file.delete(); + dir.delete(); + } + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/controller/DetectControllerTests.java b/src/test/java/com/skyflow/vault/controller/DetectControllerTests.java new file mode 100644 index 00000000..aae713b1 --- /dev/null +++ b/src/test/java/com/skyflow/vault/controller/DetectControllerTests.java @@ -0,0 +1,121 @@ +package com.skyflow.vault.controller; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.HttpStatus; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.vault.detect.DeidentifyTextRequest; +import com.skyflow.vault.detect.ReidentifyTextRequest; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class DetectControllerTests { + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static VaultConfig vaultConfig = null; + private static Skyflow skyflowClient = null; + + @BeforeClass + public static void setup() throws SkyflowException, NoSuchMethodException { + vaultID = "vault123"; + clusterID = "cluster123"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.DEV); + vaultConfig.setCredentials(credentials); + + + skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addVaultConfig(vaultConfig) + .build(); + } + + + @Test + public void testNullTextInRequestInDeidentifyStringMethod() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder().text(null).build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.detect(vaultID).deidentifyText(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.InvalidTextInDeIdentify.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertNull(e.getRequestId()); + Assert.assertNull(e.getGrpcCode()); + Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + } + } + + @Test + public void testEmptyTextInRequestInDeidentifyStringMethod() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder().text("").build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.detect(vaultID).deidentifyText(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.InvalidTextInDeIdentify.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertNull(e.getRequestId()); + Assert.assertNull(e.getGrpcCode()); + Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + } + } + + @Test + public void testNullTextInRequestInReidentifyStringMethod() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder().text(null).build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.detect(vaultID).reidentifyText(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.InvalidTextInReIdentify.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertNull(e.getRequestId()); + Assert.assertNull(e.getGrpcCode()); + Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + } + } + + @Test + public void testEmptyTextInRequestInReidentifyStringMethod() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder().text("").build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.detect(vaultID).reidentifyText(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.InvalidTextInReIdentify.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertNull(e.getRequestId()); + Assert.assertNull(e.getGrpcCode()); + Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + } + } + +} + diff --git a/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java index 6084e9c3..5f3ae771 100644 --- a/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java +++ b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java @@ -10,7 +10,6 @@ import com.skyflow.errors.HttpStatus; import com.skyflow.errors.SkyflowException; import com.skyflow.generated.rest.ApiClient; -import com.skyflow.generated.rest.api.TokensApi; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.vault.data.*; @@ -28,7 +27,6 @@ public class VaultControllerTests { private static VaultConfig vaultConfig = null; private static Skyflow skyflowClient = null; private ApiClient mockApiClient; - private TokensApi mockTokensApi; @BeforeClass public static void setup() throws SkyflowException, NoSuchMethodException { @@ -43,13 +41,19 @@ public static void setup() throws SkyflowException, NoSuchMethodException { vaultConfig.setClusterId(clusterID); vaultConfig.setEnv(Env.DEV); vaultConfig.setCredentials(credentials); + + + skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addVaultConfig(vaultConfig) + .build(); + } @Test public void testInvalidRequestInInsertMethod() { try { InsertRequest request = InsertRequest.builder().build(); - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); skyflowClient.vault().insert(request); Assert.fail(EXCEPTION_NOT_THROWN); } catch (SkyflowException e) { @@ -161,37 +165,4 @@ public void testInvalidRequestInTokenizeMethod() { } } - @Test - public void testLookUpBin() { - try { - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - skyflowClient.vault().lookUpBin(); - skyflowClient.vault().lookUpBin(); - } catch (SkyflowException e) { - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - public void testAudit() { - try { - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - skyflowClient.vault().audit(); - skyflowClient.vault().audit(); - } catch (SkyflowException e) { - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - - @Test - public void testDetect() { - try { - skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); - skyflowClient.vault().detect(); - skyflowClient.vault().detect(); - } catch (SkyflowException e) { - Assert.fail(INVALID_EXCEPTION_THROWN); - } - } - } diff --git a/src/test/java/com/skyflow/vault/data/DeleteTests.java b/src/test/java/com/skyflow/vault/data/DeleteTests.java index 6749e31d..befc3d26 100644 --- a/src/test/java/com/skyflow/vault/data/DeleteTests.java +++ b/src/test/java/com/skyflow/vault/data/DeleteTests.java @@ -163,7 +163,7 @@ public void testDeleteResponse() { try { ids.add(skyflowID); DeleteResponse response = new DeleteResponse(ids); - String responseString = "{\"deletedIds\":[\"" + skyflowID + "\"],\"errors\":[]}"; + String responseString = "{\"deletedIds\":[\"" + skyflowID + "\"],\"errors\":null}"; Assert.assertEquals(1, response.getDeletedIds().size()); Assert.assertEquals(responseString, response.toString()); } catch (Exception e) { diff --git a/src/test/java/com/skyflow/vault/data/QueryTests.java b/src/test/java/com/skyflow/vault/data/QueryTests.java index 7a8cca5e..c8e453f5 100644 --- a/src/test/java/com/skyflow/vault/data/QueryTests.java +++ b/src/test/java/com/skyflow/vault/data/QueryTests.java @@ -97,7 +97,7 @@ public void testQueryResponse() { String responseString = "{\"fields\":" + "[{\"card_number\":\"test_card_number\",\"name\":\"test_name\",\"tokenizedData\":{}}," + "{\"card_number\":\"test_card_number\",\"name\":\"test_name\",\"tokenizedData\":{}}]," + - "\"errors\":[]}"; + "\"errors\":null}"; Assert.assertEquals(2, response.getFields().size()); Assert.assertEquals(responseString, response.toString()); } catch (Exception e) { diff --git a/src/test/java/com/skyflow/vault/data/UpdateTests.java b/src/test/java/com/skyflow/vault/data/UpdateTests.java index 7032fcb0..be702d4e 100644 --- a/src/test/java/com/skyflow/vault/data/UpdateTests.java +++ b/src/test/java/com/skyflow/vault/data/UpdateTests.java @@ -448,7 +448,7 @@ public void testUpdateResponse() { UpdateResponse response = new UpdateResponse(skyflowID, tokenMap); String responseString = "{\"updatedField\":{\"skyflowId\":\"" + skyflowID + "\"," + "\"test_column_1\":\"test_token_1\",\"test_column_2\":\"test_token_2\"}" + - ",\"errors\":[]}"; + ",\"errors\":null}"; Assert.assertEquals(skyflowID, response.getSkyflowId()); Assert.assertEquals(2, response.getTokens().size()); Assert.assertEquals(responseString, response.toString()); diff --git a/src/test/java/com/skyflow/vault/detect/DeidentifyFileRequestTest.java b/src/test/java/com/skyflow/vault/detect/DeidentifyFileRequestTest.java new file mode 100644 index 00000000..1b19d9d9 --- /dev/null +++ b/src/test/java/com/skyflow/vault/detect/DeidentifyFileRequestTest.java @@ -0,0 +1,99 @@ +package com.skyflow.vault.detect; + +import com.skyflow.enums.DetectEntities; +import com.skyflow.enums.DetectOutputTranscriptions; +import com.skyflow.enums.MaskingMethod; +import org.junit.Assert; +import org.junit.Test; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; + +public class DeidentifyFileRequestTest { + + @Test + public void testBuilderAndGetters() { + File file = new File("test.txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + DetectEntities entity = DetectEntities.DOB; + MaskingMethod maskingMethod = MaskingMethod.BLACKBOX; + DetectOutputTranscriptions transcription = DetectOutputTranscriptions.TRANSCRIPTION; + String outputDir = "/tmp/output"; + int waitTime = 42; + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(Arrays.asList(entity)) + .allowRegexList(Arrays.asList("a.*")) + .restrictRegexList(Arrays.asList("b.*")) + .maskingMethod(maskingMethod) + .outputProcessedImage(true) + .outputOcrText(true) + .outputProcessedAudio(true) + .outputTranscription(transcription) + .outputDirectory(outputDir) + .waitTime(waitTime) + .build(); + + Assert.assertEquals(entity, request.getEntities().get(0)); + Assert.assertEquals("a.*", request.getAllowRegexList().get(0)); + Assert.assertEquals("b.*", request.getRestrictRegexList().get(0)); + Assert.assertEquals(maskingMethod, request.getMaskingMethod()); + Assert.assertTrue(request.getOutputProcessedImage()); + Assert.assertTrue(request.getOutputOcrText()); + Assert.assertTrue(request.getOutputProcessedAudio()); + Assert.assertEquals(transcription, request.getOutputTranscription()); + Assert.assertEquals(outputDir, request.getOutputDirectory()); + Assert.assertEquals(Integer.valueOf(waitTime), request.getWaitTime()); + } + + @Test + public void testBuilderDefaults() { + DeidentifyFileRequest request = DeidentifyFileRequest.builder().build(); + Assert.assertFalse(request.getOutputProcessedImage()); + Assert.assertFalse(request.getOutputOcrText()); + Assert.assertFalse(request.getOutputProcessedAudio()); + Assert.assertNull(request.getOutputDirectory()); + Assert.assertNull(request.getWaitTime()); + } + + @Test + public void testBuilderWithFilePath() { + String filePath = "/tmp/test.txt"; + FileInput fileInput = FileInput.builder().filePath(filePath).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(Collections.singletonList(DetectEntities.DOB)) + .build(); + + Assert.assertEquals(filePath, request.getFileInput().getFilePath()); + Assert.assertNull(request.getFileInput().getFile()); + } + + @Test + public void testBuilderWithFileAndFilePath() { + File file = new File("test.txt"); + String filePath = "/tmp/test.txt"; + FileInput fileInput = FileInput.builder().file(file).filePath(filePath).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(Collections.singletonList(DetectEntities.DOB)) + .build(); + + Assert.assertEquals(file, request.getFileInput().getFile()); + Assert.assertEquals(filePath, request.getFileInput().getFilePath()); + } + + @Test + public void testBuilderWithNullFileAndFilePath() { + FileInput fileInput = FileInput.builder().build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(Collections.singletonList(DetectEntities.DOB)) + .build(); + + Assert.assertNull(request.getFileInput().getFile()); + Assert.assertNull(request.getFileInput().getFilePath()); + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java b/src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java new file mode 100644 index 00000000..a1243eea --- /dev/null +++ b/src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java @@ -0,0 +1,60 @@ +package com.skyflow.vault.detect; + +import com.skyflow.generated.rest.types.DeidentifyFileOutputProcessedFileType; +import org.junit.Assert; +import org.junit.Test; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; + +public class DeidentifyFileResponseTest { + + @Test + public void testAllGettersAndToString() { + File fileObject = new File("test-path.txt"); + String file = "test-path.txt"; + String type = "pdf"; + String extension = ".pdf"; + Integer wordCount = 100; + Integer charCount = 500; + Double sizeInKb = 123.45; + Double durationInSeconds = 12.3; + Integer pageCount = 5; + Integer slideCount = 0; + FileEntityInfo entityInfo = new FileEntityInfo("PERSON", DeidentifyFileOutputProcessedFileType.ENTITIES, "John Doe"); + java.util.List entities = Collections.singletonList(entityInfo); + String runId = "run-123"; + String status = "SUCCESS"; + java.util.List errors = Arrays.asList("error1", "error2"); + FileInfo fileInfo = new FileInfo(fileObject); + + DeidentifyFileResponse response = new DeidentifyFileResponse( + fileInfo, file, type, extension, wordCount, charCount, sizeInKb, + durationInSeconds, pageCount, slideCount, entities, runId, status, errors + ); + + Assert.assertEquals(type, response.getType()); + Assert.assertEquals(extension, response.getExtension()); + Assert.assertEquals(wordCount, response.getWordCount()); + Assert.assertEquals(charCount, response.getCharCount()); + Assert.assertEquals(sizeInKb, response.getSizeInKb()); + Assert.assertEquals(durationInSeconds, response.getDurationInSeconds()); + Assert.assertEquals(pageCount, response.getPageCount()); + Assert.assertEquals(slideCount, response.getSlideCount()); + Assert.assertEquals(entities, response.getEntities()); + Assert.assertEquals(runId, response.getRunId()); + Assert.assertEquals(status, response.getStatus()); + Assert.assertEquals(errors, response.getErrors()); + + // toString should return a JSON string containing all fields + String json = response.toString(); + Assert.assertTrue(json.contains(file)); + Assert.assertTrue(json.contains(type)); + Assert.assertTrue(json.contains(extension)); + Assert.assertTrue(json.contains(runId)); + Assert.assertTrue(json.contains(status)); + Assert.assertTrue(json.contains("error1")); + Assert.assertTrue(json.contains("PERSON")); + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/detect/DeidentifyTextTests.java b/src/test/java/com/skyflow/vault/detect/DeidentifyTextTests.java new file mode 100644 index 00000000..08cde4c3 --- /dev/null +++ b/src/test/java/com/skyflow/vault/detect/DeidentifyTextTests.java @@ -0,0 +1,217 @@ +package com.skyflow.vault.detect; + +import com.skyflow.enums.DetectEntities; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static com.skyflow.errors.ErrorMessage.InvalidTextInDeIdentify; + +public class DeidentifyTextTests { + + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + + private static final String text = "Sensitive data to deidentify"; + private static final List detectEntities = new ArrayList<>(); + private static final List allowRegexList = new ArrayList<>(); + private static final List restrictRegexList = new ArrayList<>(); + private static final TokenFormat tokenFormat = TokenFormat.builder() + .vaultToken(detectEntities) + .entityUniqueCounter(detectEntities) + .entityOnly(detectEntities) + .build(); + + private static Transformations transformations = null; + + + @BeforeClass + public static void setup() { + detectEntities.add(DetectEntities.NAME); + detectEntities.add(DetectEntities.DOB); + + allowRegexList.add("^[A-Za-z]+$"); + restrictRegexList.add("([0-9]{3}-[0-9]{2}-[0-9]{4})"); + + transformations = new Transformations( + new DateTransformation(20, 5, detectEntities) + ); + } + + + @Test + public void testValidInputInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .entities(detectEntities) + .allowRegexList(allowRegexList) + .restrictRegexList(restrictRegexList) + .tokenFormat(tokenFormat) + .transformations(transformations) + .build(); + + Validations.validateDeidentifyTextRequest(request); + Assert.assertEquals(detectEntities, request.getEntities()); + Assert.assertEquals(allowRegexList, request.getAllowRegexList()); + Assert.assertEquals(restrictRegexList, request.getRestrictRegexList()); + Assert.assertEquals(tokenFormat, request.getTokenFormat()); + Assert.assertEquals(transformations, request.getTransformations()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + + @Test + public void testNullTextInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder().text(null).build(); + Validations.validateDeidentifyTextRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(InvalidTextInDeIdentify.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyTextInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder().text("").build(); + Validations.validateDeidentifyTextRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(InvalidTextInDeIdentify.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyEntitiesInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .entities(new ArrayList<>()) + .build(); + Validations.validateDeidentifyTextRequest(request); + Assert.assertTrue(request.getEntities().isEmpty()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + + @Test + public void testNoEntitiesInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder().text("").build(); + Validations.validateDeidentifyTextRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + + @Test + public void testEmptyAllowRegexListInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .allowRegexList(new ArrayList<>()) + .build(); + Validations.validateDeidentifyTextRequest(request); + Assert.assertTrue(request.getAllowRegexList().isEmpty()); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + @Test + public void testEmptyRestrictRegexListInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .restrictRegexList(new ArrayList<>()) + .build(); + Validations.validateDeidentifyTextRequest(request); + Assert.assertTrue(request.getRestrictRegexList().isEmpty()); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + + @Test + public void testNullTokenFormatInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .entities(detectEntities) + .allowRegexList(allowRegexList) + .restrictRegexList(restrictRegexList) + .tokenFormat(null) + .build(); + Validations.validateDeidentifyTextRequest(request); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + @Test + public void testNoTransformationsInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .entities(detectEntities) + .allowRegexList(allowRegexList) + .restrictRegexList(restrictRegexList) + .tokenFormat(tokenFormat) + .build(); + Validations.validateDeidentifyTextRequest(request); + Assert.assertNull(request.getTransformations()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNullOrEmptyTransformationsInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .entities(detectEntities) + .allowRegexList(allowRegexList) + .restrictRegexList(restrictRegexList) + .tokenFormat(tokenFormat) + .transformations(null) + .build(); + Validations.validateDeidentifyTextRequest(request); + Assert.assertNull(request.getTransformations()); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + @Test + public void testDeidentifyResponse() { + try { + List entityInfos = new ArrayList<>(); + int wordCount = 5; + int charCount = 30; + DeidentifyTextResponse response = new DeidentifyTextResponse(text, entityInfos, wordCount, charCount); + Assert.assertEquals(text, response.getProcessedText()); + Assert.assertEquals(wordCount, response.getWordCount()); + Assert.assertEquals(charCount, response.getCharCount()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} diff --git a/src/test/java/com/skyflow/vault/detect/FileEntityInfoTest.java b/src/test/java/com/skyflow/vault/detect/FileEntityInfoTest.java new file mode 100644 index 00000000..e1f1e152 --- /dev/null +++ b/src/test/java/com/skyflow/vault/detect/FileEntityInfoTest.java @@ -0,0 +1,21 @@ +package com.skyflow.vault.detect; + +import com.skyflow.generated.rest.types.DeidentifyFileOutputProcessedFileType; +import org.junit.Assert; +import org.junit.Test; + +public class FileEntityInfoTest { + + @Test + public void testConstructorAndGetters() { + String file = "entity.pdf"; + DeidentifyFileOutputProcessedFileType type = DeidentifyFileOutputProcessedFileType.ENTITIES; + String extension = ".pdf"; + + FileEntityInfo info = new FileEntityInfo(file, type, extension); + + Assert.assertEquals(file, info.getFile()); + Assert.assertEquals(type.toString(), info.getType()); + Assert.assertEquals(extension, info.getExtension()); + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/detect/FileInfoTest.java b/src/test/java/com/skyflow/vault/detect/FileInfoTest.java new file mode 100644 index 00000000..29a81f6a --- /dev/null +++ b/src/test/java/com/skyflow/vault/detect/FileInfoTest.java @@ -0,0 +1,41 @@ +package com.skyflow.vault.detect; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +public class FileInfoTest { + + @Test + public void testFileInfoFields() throws IOException { + // Create a temp file + File tempFile = File.createTempFile("testfileinfo", ".txt"); + tempFile.deleteOnExit(); + + // Write some content to ensure size > 0 + FileWriter writer = new FileWriter(tempFile); + writer.write("Hello Skyflow!"); + writer.close(); + + FileInfo fileInfo = new FileInfo(tempFile); + + Assert.assertEquals(tempFile.getName(), fileInfo.getName()); + Assert.assertEquals(tempFile.length(), fileInfo.getSize()); + Assert.assertEquals("", fileInfo.getType()); + Assert.assertEquals(tempFile.lastModified(), fileInfo.getLastModified()); + } + + @Test + public void testFileInfoWithNonExistentFile() { + File fakeFile = new File("nonexistentfile.txt"); + FileInfo fileInfo = new FileInfo(fakeFile); + + Assert.assertEquals("nonexistentfile.txt", fileInfo.getName()); + Assert.assertEquals(0, fileInfo.getSize()); + Assert.assertEquals("", fileInfo.getType()); + Assert.assertEquals(0, fileInfo.getLastModified()); + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/detect/ReidentifyTextTests.java b/src/test/java/com/skyflow/vault/detect/ReidentifyTextTests.java new file mode 100644 index 00000000..e96a6422 --- /dev/null +++ b/src/test/java/com/skyflow/vault/detect/ReidentifyTextTests.java @@ -0,0 +1,149 @@ +package com.skyflow.vault.detect; + +import com.skyflow.enums.DetectEntities; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static com.skyflow.errors.ErrorMessage.InvalidTextInReIdentify; + +public class ReidentifyTextTests { + + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + + private static final String text = "Sensitive data to reidentify"; + private static final List redactedEntities = new ArrayList<>(); + private static final List maskedEntities = new ArrayList<>(); + private static final List plainTextEntities = new ArrayList<>(); + + @BeforeClass + public static void setup() { + redactedEntities.add(DetectEntities.NAME); + redactedEntities.add(DetectEntities.DOB); + + maskedEntities.add(DetectEntities.USERNAME); + + plainTextEntities.add(DetectEntities.PHONE_NUMBER); + } + + @Test + public void testValidInputInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder() + .text(text) + .redactedEntities(redactedEntities) + .maskedEntities(maskedEntities) + .plainTextEntities(plainTextEntities) + .build(); + + Validations.validateReidentifyTextRequest(request); + Assert.assertEquals(text, request.getText()); + Assert.assertEquals(redactedEntities, request.getRedactedEntities()); + Assert.assertEquals(maskedEntities, request.getMaskedEntities()); + Assert.assertEquals(plainTextEntities, request.getPlainTextEntities()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoTextInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder().build(); + Validations.validateReidentifyTextRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + @Test + public void testNullTextInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder() + .text(null) + .build(); + Validations.validateReidentifyTextRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(InvalidTextInReIdentify.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyTextInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder() + .text("") + .build(); + Validations.validateReidentifyTextRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(InvalidTextInReIdentify.getMessage(), e.getMessage()); + } + } + + + @Test + public void testEmptyRedactedEntitiesInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder() + .text(text) + .redactedEntities(new ArrayList<>()) + .build(); + Validations.validateReidentifyTextRequest(request); + Assert.assertTrue(request.getRedactedEntities().isEmpty()); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + + @Test + public void testEmptyMaskedEntitiesInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder() + .text(text) + .maskedEntities(new ArrayList<>()) + .build(); + Validations.validateReidentifyTextRequest(request); + Assert.assertTrue(request.getMaskedEntities().isEmpty()); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + @Test + public void testEmptyPlainTextEntitiesInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder() + .text(text) + .plainTextEntities(new ArrayList<>()) + .build(); + Validations.validateReidentifyTextRequest(request); + Assert.assertTrue(request.getPlainTextEntities().isEmpty()); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + + @Test + public void testReidentifyResponse() { + try { + ReidentifyTextResponse response = new ReidentifyTextResponse(text); + Assert.assertEquals(text, response.getProcessedText()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index 44bcf2a5..ed6804b5 100644 --- a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -4,8 +4,8 @@ import com.skyflow.errors.ErrorCode; import com.skyflow.errors.ErrorMessage; import com.skyflow.errors.SkyflowException; -import com.skyflow.generated.rest.models.DetokenizeRecordResponseValueType; -import com.skyflow.generated.rest.models.V1DetokenizeRecordResponse; +import com.skyflow.generated.rest.types.DetokenizeRecordResponseValueType; +import com.skyflow.generated.rest.types.V1DetokenizeRecordResponse; import com.skyflow.utils.Constants; import com.skyflow.utils.Utils; import com.skyflow.utils.validations.Validations; @@ -147,16 +147,19 @@ public void testRedactionAndContinueOnErrorInDetokenizeRequestValidations() { @Test public void testDetokenizeResponse() { try { - V1DetokenizeRecordResponse record1 = new V1DetokenizeRecordResponse(); - record1.setToken("1234-5678-9012-3456"); - record1.setValue("4111111111111111"); - record1.setValueType(DetokenizeRecordResponseValueType.STRING); + V1DetokenizeRecordResponse record1 = V1DetokenizeRecordResponse.builder() + .token("1234-5678-9012-3456") + .value("4111111111111111") + .valueType(DetokenizeRecordResponseValueType.STRING) + .build(); DetokenizeRecordResponse field = new DetokenizeRecordResponse(record1); - V1DetokenizeRecordResponse record2 = new V1DetokenizeRecordResponse(); - record2.setToken("3456-7890-1234-5678"); - record2.setValue(""); - record2.setError("Invalid token"); + V1DetokenizeRecordResponse record2 = V1DetokenizeRecordResponse.builder() + .token("3456-7890-1234-5678") + .value("") + .error("Invalid token") + .build(); + DetokenizeRecordResponse error = new DetokenizeRecordResponse(record2, requestId); ArrayList fields = new ArrayList<>(); diff --git a/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java index 821ad844..4c279fde 100644 --- a/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java @@ -159,7 +159,7 @@ public void testTokenizeResponse() { TokenizeResponse response = new TokenizeResponse(tokens); String responseString = "{\"tokens\":[" + "{\"token\":\"1234-5678-9012-3456\"},{\"token\":\"5678-9012-3456-7890\"}]" + - ",\"errors\":[]}"; + ",\"errors\":null}"; Assert.assertEquals(2, response.getTokens().size()); Assert.assertEquals(responseString, response.toString()); } catch (Exception e) { From f8d093fb13fa9fb472bf439f79eb1ef6fc7b57b9 Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow Date: Mon, 30 Jun 2025 13:24:25 +0000 Subject: [PATCH 118/126] [AUTOMATED] Public Release - 2.0.0-beta.2 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7802501d..832fd901 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 2.0.0-beta.1-dev.e14bd74 + 2.0.0-beta.2 jar ${project.groupId}:${project.artifactId} From 02e622d0886d4c0f9d3026759fe937adf22e6ca2 Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow <156889717+saileshwar-skyflow@users.noreply.github.com> Date: Tue, 1 Jul 2025 14:01:15 +0530 Subject: [PATCH 119/126] SK-1759: Detect support README and samples. (#183) * SK-1759: readme and samples for detect --- README.md | 652 ++++++++++++++++++ .../example/detect/DeidentifyFileExample.java | 114 +++ .../example/detect/DeidentifyTextExample.java | 142 ++++ .../example/detect/GetDetectRunExample.java | 55 ++ 4 files changed, 963 insertions(+) create mode 100644 samples/src/main/java/com/example/detect/DeidentifyFileExample.java create mode 100644 samples/src/main/java/com/example/detect/DeidentifyTextExample.java create mode 100644 samples/src/main/java/com/example/detect/GetDetectRunExample.java diff --git a/README.md b/README.md index cee75d31..7c80d174 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,11 @@ The Skyflow Java SDK is designed to help with integrating Skyflow into a Java ba - [Update](#update) - [Delete](#delete) - [Query](#query) +- [Detect](#detect) + - [Deidentify Text](#deidentify-text) + - [Reidentify Text](#reidentify-text) + - [Deidentify File](#deidentify-file) + - [Get Run](#get-run) - [Connections](#connections) - [Invoke a connection](#invoke-a-connection) - [Authenticate with bearer tokens](#authenticate-with-bearer-tokens) @@ -1756,6 +1761,653 @@ Sample response: } ``` +# Detect +Skyflow Detect enables you to deidentify and reidentify sensitive data in text and files, supporting advanced privacy-preserving workflows. The Detect API supports the following operations: + +## Deidentify Text +To deidentify text, use the `deidentifyText` method. The `DeidentifyTextRequest` class creates a deidentify text request, which includes the text to be deidentified. Additionally, you can provide optional parameters using the `DeidentifyTextOptions` class. + +### Construct an deidentify text request + +```java +import com.skyflow.enums.DetectEntities; +import com.skyflow.vault.detect.DateTransformation; +import com.skyflow.vault.detect.DeidentifyTextRequest; +import com.skyflow.vault.detect.TokenFormat; +import com.skyflow.vault.detect.Transformations; +import com.skyflow.vault.detect.DeidentifyTextResponse; + +import java.util.ArrayList; +import java.util.List; + +/** + * This example demonstrate to build deidentify text request. + */ +public class DeidentifyTextSchema { + + public static void main(String[] args) { + + // Step 1: Initialise the Skyflow client by configuring the credentials & vault config. + + // Step 2: Configure the options for deidentify text + + // Replace with the entity you want to detect + List detectEntitiesList = new ArrayList<>(); + detectEntitiesList.add(DetectEntities.SSN); + + // Replace with the entity you want to detect with vault token + List vaultTokenList = new ArrayList<>(); + vaultTokenList.add(DetectEntities.CREDIT_CARD); + + // Replace with the entity you want to detect with entity only + List entityOnlyList = new ArrayList<>(); + entityOnlyList.add(DetectEntities.SSN); + + // Replace with the entity you want to detect with entity unique counter + List entityUniqueCounterList = new ArrayList<>(); + entityUniqueCounterList.add(DetectEntities.SSN); + + // Replace with the regex patterns you want to allow during deidentification + List allowRegexList = new ArrayList<>(); + allowRegexList.add(""); + + // Replace with the regex patterns you want to restrict during deidentification + List restrictRegexList = new ArrayList<>(); + restrictRegexList.add("YOUR_RESTRICT_REGEX_LIST"); + + // Configure Token Format + TokenFormat tokenFormat = TokenFormat.builder() + .vaultToken(vaultTokenList) + .entityOnly(entityOnlyList) + .entityUniqueCounter(entityUniqueCounterList) + .build(); + + // Configure Transformation + List detectEntitiesTransformationList = new ArrayList<>(); + detectEntitiesTransformationList.add(DetectEntities.DOB); // Replace with the entity you want to transform + + DateTransformation dateTransformation = new DateTransformation(20, 5, detectEntitiesTransformationList); + Transformations transformations = new Transformations(dateTransformation); + + // Step 3: Create a deidentify text request for the vault + DeidentifyTextRequest deidentifyTextRequest = DeidentifyTextRequest.builder() + .text("") // Replace with the text you want to deidentify + .entities(detectEntitiesList) + .allowRegexList(allowRegexList) + .restrictRegexList(restrictRegexList) + .tokenFormat(tokenFormat) + .transformations(transformations) + .build(); + + // Step 4: Use the Skyflow client to perform the deidentifyText operation + // Replace with your actual vault ID + DeidentifyTextResponse deidentifyTextResponse = skyflowClient.detect("").deidentifyText(deidentifyTextRequest); + + // Step 5: Print the response + System.out.println("Deidentify text Response: " + deidentifyTextResponse); + } +} + +``` + +## An [example](https://github.com/skyflowapi/skyflow-java/blob/beta-release/25.6.2/samples/src/main/java/com/example/detect/DeidentifyTextExample.java) of deidentify text: +```java +import java.util.ArrayList; +import java.util.List; + +import com.skyflow.enums.DetectEntities; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.detect.DateTransformation; +import com.skyflow.vault.detect.DeidentifyTextRequest; +import com.skyflow.vault.detect.DeidentifyTextResponse; +import com.skyflow.vault.detect.TokenFormat; +import com.skyflow.vault.detect.Transformations; + +/** + * Skyflow Deidentify Text Example + *

+ * This example demonstrates how to use the Skyflow SDK to deidentify text data + * across multiple vaults. It includes: + * 1. Setting up credentials and vault configurations. + * 2. Creating a Skyflow client with multiple vaults. + * 3. Performing deidentify of text with various options. + * 4. Handling responses and errors. + */ + +public class DeidentifyTextExample { + public static void main(String[] args) throws SkyflowException { + + // Step 1: Initialise the Skyflow client by configuring the credentials & vault config. + + // Step 2: Configuring the different options for deidentify + + // Replace with the entity you want to detect + List detectEntitiesList = new ArrayList<>(); + detectEntitiesList.add(DetectEntities.SSN); + detectEntitiesList.add(DetectEntities.CREDIT_CARD); + + // Replace with the entity you want to detect with vault token + List vaultTokenList = new ArrayList<>(); + vaultTokenList.add(DetectEntities.SSN); + vaultTokenList.add(DetectEntities.CREDIT_CARD); + + // Configure Token Format + TokenFormat tokenFormat = TokenFormat.builder() + .vaultToken(vaultTokenList) + .build(); + + // Configure Transformation for deidentified entities + List detectEntitiesTransformationList = new ArrayList<>(); + detectEntitiesTransformationList.add(DetectEntities.DOB); // Replace with the entity you want to transform + + DateTransformation dateTransformation = new DateTransformation(20, 5, detectEntitiesTransformationList); + Transformations transformations = new Transformations(dateTransformation); + + // Step 3: invoking Deidentify text on the vault + try { + // Create a deidentify text request for the vault + DeidentifyTextRequest deidentifyTextRequest = DeidentifyTextRequest.builder() + .text("My SSN is 123-45-6789 and my card is 4111 1111 1111 1111.") // Replace with your deidentify text + .entities(detectEntitiesList) + .tokenFormat(tokenFormat) + .transformations(transformations) + .build(); + // Replace `9f27764a10f7946fe56b3258e117` with the acutal vault id + DeidentifyTextResponse deidentifyTextResponse = skyflowClient.detect("9f27764a10f7946fe56b3258e117").deidentifyText(deidentifyTextRequest); + + System.out.println("Deidentify text Response: " + deidentifyTextResponse); + } catch (SkyflowException e) { + System.err.println("Error occurred during deidentify: "); + e.printStackTrace(); // Print the exception for debugging purposes + } + } +} +``` + +Sample Response: +```json +{ + "processedText": "My SSN is [SSN_IWdexZe] and my card is [CREDIT_CARD_rUzMjdQ].", + "entities": [ + { + "token": "SSN_IWdexZe", + "value": "123-45-6789", + "textIndex": { + "start": 10, + "end": 21 + }, + "processedIndex": { + "start": 10, + "end": 23 + }, + "entity": "SSN", + "scores": { + "SSN": 0.9384 + } + }, + { + "token": "CREDIT_CARD_rUzMjdQ", + "value": "4111 1111 1111 1111", + "textIndex": { + "start": 37, + "end": 56 + }, + "processedIndex": { + "start": 39, + "end": 60 + }, + "entity": "CREDIT_CARD", + "scores": { + "CREDIT_CARD": 0.9051 + } + } + ], + "wordCount": 9, + "charCount": 57 +} +``` + +## Reidentify Text +To reidentify text, use the `reidentifyText` method. The `ReidentifyTextRequest` class creates a reidentify text request, which includes the redacted or deidentified text to be reidentified. Additionally, you can provide optional parameters using the ReidentifyTextOptions class to control how specific entities are returned (as redacted, masked, or plain text). + +### Construct an reidentify text request + +```java +import com.skyflow.enums.DetectEntities; +import com.skyflow.vault.detect.ReidentifyTextRequest; +import com.skyflow.vault.detect.ReidentifyTextResponse; + +import java.util.ArrayList; +import java.util.List; + +/** + * This example demonstrates how to build a reidentify text request. + */ +public class ReidentifyTextSchema { + public static void main(String[] args) { + // Step 1: Initialise the Skyflow client by configuring the credentials & vault config. + + // Step 2: Configuring the different options for reidentify + List maskedEntity = new ArrayList<>(); + maskedEntity.add(DetectEntities.CREDIT_CARD); // Replace with the entity you want to mask + + List plainTextEntity = new ArrayList<>(); + plainTextEntity.add(DetectEntities.SSN); // Replace with the entity you want to keep in plain text + + // List redactedEntity = new ArrayList<>(); + // redactedEntity.add(DetectEntities.SSN); // Replace with the entity you want to redact + + + // Step 3: Create a reidentify text request with the configured entities + ReidentifyTextRequest reidentifyTextRequest = ReidentifyTextRequest.builder() + .text("My SSN is [SSN_IWdexZe] and my card is [CREDIT_CARD_rUzMjdQ].") // Replace with your deidentify text + .maskedEntities(maskedEntity) +// .redactedEntities(redactedEntity) + .plainTextEntities(plainTextEntity) + .build(); + + // Step 4: Invoke reidentify text on the vault + ReidentifyTextResponse reidentifyTextResponse = skyflowClient.detect("").reidentifyText(reidentifyTextRequest); + System.out.println("Reidentify text Response: " + reidentifyTextResponse); + } +} +``` + +## An [example](https://github.com/skyflowapi/skyflow-java/blob/beta-release/25.6.2/samples/src/main/java/com/example/detect/ReidentifyTextExample.java) of Reidentify text + +```java +import com.skyflow.enums.DetectEntities; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.detect.ReidentifyTextRequest; +import com.skyflow.vault.detect.ReidentifyTextResponse; + +import java.util.ArrayList; +import java.util.List; + +/** + * Skyflow Reidentify Text Example + *

+ * This example demonstrates how to use the Skyflow SDK to reidentify text data + * across multiple vaults. It includes: + * 1. Setting up credentials and vault configurations. + * 2. Creating a Skyflow client with multiple vaults. + * 3. Performing reidentify of text with various options. + * 4. Handling responses and errors. + */ + +public class ReidentifyTextExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Initialise the Skyflow client by configuring the credentials & vault config. + + // Step 2: Configuring the different options for reidentify + List maskedEntity = new ArrayList<>(); + maskedEntity.add(DetectEntities.CREDIT_CARD); // Replace with the entity you want to mask + + List plainTextEntity = new ArrayList<>(); + plainTextEntity.add(DetectEntities.SSN); // Replace with the entity you want to keep in plain text + + try { + // Step 3: Create a reidentify text request with the configured options + ReidentifyTextRequest reidentifyTextRequest = ReidentifyTextRequest.builder() + .text("My SSN is [SSN_IWdexZe] and my card is [CREDIT_CARD_rUzMjdQ].") // Replace with your deidentify text + .maskedEntities(maskedEntity) + .plainTextEntities(plainTextEntity) + .build(); + + // Step 4: Invoke Reidentify text on the vault + // Replace `9f27764a10f7946fe56b3258e117` with the acutal vault id + ReidentifyTextResponse reidentifyTextResponse = skyflowClient.detect("9f27764a10f7946fe56b3258e117").reidentifyText(reidentifyTextRequest); + + // Handle the response from the reidentify text request + System.out.println("Reidentify text Response: " + reidentifyTextResponse); + } catch (SkyflowException e) { + System.err.println("Error occurred during reidentify : "); + e.printStackTrace(); + } + } +} +``` + +Sample Response: + +```json +{ + "processedText":"My SSN is 123-45-6789 and my card is XXXXX1111." +} +``` + +## Deidentify file +To deidentify files, use the `deidentifyFile` method. The `DeidentifyFileRequest` class creates a deidentify file request, which includes the file to be deidentified (such as images, PDFs, audio, documents, spreadsheets, or presentations). Additionally, you can provide optional parameters using the DeidentifyFileOptions class to control how entities are detected and deidentified, as well as how the output is generated for different file types. + +### Construct an deidentify file request + +```java +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.enums.MaskingMethod; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.detect.DeidentifyFileRequest; +import com.skyflow.vault.detect.DeidentifyFileResponse; + +import java.io.File; + +/** + * This example demonstrates how to build a deidentify file request. + */ + +public class DeidentifyFileSchema { + + public static void main(String[] args) { + // Step 1: Initialise the Skyflow client by configuring the credentials & vault config. + + // Step 2: Create a deidentify file request with all options + + // Create file object + File file = new File(""); // Replace with the path to the file you want to deidentify + + // Create file input using the file object + FileInput fileInput = FileInput.builder() + .file(file) + // .filePath("") // Alternatively, you can use .filePath() + .build(); + + // Output configuration + String outputDirectory = ""; // Replace with the desired output directory to save the deidentified file + + // Entities to detect + // List detectEntities = new ArrayList<>(); + // detectEntities.add(DetectEntities.IP_ADDRESS); // Replace with the entities you want to detect + + // Image-specific options + // Boolean outputProcessedImage = true; // Include processed image in output + // Boolean outputOcrText = true; // Include OCR text in output + MaskingMethod maskingMethod = MaskingMethod.BLACKBOX; // Masking method for images + + // PDF-specific options + // Integer pixelDensity = 15; // Pixel density for PDF processing + // Integer maxResolution = 2000; // Max resolution for PDF + + // Audio-specific options + // Boolean outputProcessedAudio = true; // Include processed audio + // DetectOutputTranscriptions outputTanscription = DetectOutputTranscriptions.PLAINTEXT_TRANSCRIPTION; // Transcription type + + // Audio bleep configuration + // AudioBleep audioBleep = AudioBleep.builder() + // .frequency(5D) // Pitch in Hz + // .startPadding(7D) // Padding at start (seconds) + // .stopPadding(8D) // Padding at end (seconds) + // .build(); + + Integer waitTime = 20; // Max wait time for response (max 64 seconds) + + DeidentifyFileRequest deidentifyFileRequest = DeidentifyFileRequest.builder() + .file(fileInput) + .waitTime(waitTime) + .entities(detectEntities) + .outputDirectory(outputDirectory) + .maskingMethod(maskingMethod) + // .outputProcessedImage(outputProcessedImage) + // .outputOcrText(outputOcrText) + // .pixelDensity(pixelDensity) + // .maxResolution(maxResolution) + // .outputProcessedAudio(outputProcessedAudio) + // .outputTranscription(outputTanscription) + // .bleep(audioBleep) + .build(); + + + DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect("").deidentifyFile(deidentifyFileRequest); + System.out.println("Deidentify file response: " + deidentifyFileResponse.toString()); + } +} +``` + +## An [example](https://github.com/skyflowapi/skyflow-java/blob/beta-release/25.6.2/samples/src/main/java/com/example/detect/DeidentifyFileExample.java) of Deidentify file + +```java +import java.io.File; + +import com.skyflow.enums.MaskingMethod; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.detect.DeidentifyFileRequest; +import com.skyflow.vault.detect.DeidentifyFileResponse; + +/** + * Skyflow Deidentify File Example + *

+ * This example demonstrates how to use the Skyflow SDK to deidentify file + * It has all available options for deidentifying files. + * Supported file types: images (jpg, png, etc.), pdf, audio (mp3, wav), documents, spreadsheets, presentations, structured text. + * It includes: + * 1. Configure credentials + * 2. Set up vault configuration + * 3. Create a deidentify file request with all options + * 4. Call deidentifyFile to deidentify file. + * 5. Handle response and errors + */ +public class DeidentifyFileExample { + + public static void main(String[] args) throws SkyflowException { + // Step 1: Initialise the Skyflow client by configuring the credentials & vault config. + try { + // Step 2: Create a deidentify file request with all options + + + // Create file object + File file = new File("sensitive-folder/personal-info.txt"); // Replace with the path to the file you want to deidentify + + // Create file input using the file object + FileInput fileInput = FileInput.builder() + .file(file) + // .filePath("") // Alternatively, you can use .filePath() + .build(); + + // Output configuration + String outputDirectory = "deidenfied-file/"; // Replace with the desired output directory to save the deidentified file + + // Entities to detect + // List detectEntities = new ArrayList<>(); + // detectEntities.add(DetectEntities.IP_ADDRESS); // Replace with the entities you want to detect + + // Image-specific options + // Boolean outputProcessedImage = true; // Include processed image in output + // Boolean outputOcrText = true; // Include OCR text in output + MaskingMethod maskingMethod = MaskingMethod.BLACKBOX; // Masking method for images + + Integer waitTime = 20; // Max wait time for response (max 64 seconds) + + DeidentifyFileRequest deidentifyFileRequest = DeidentifyFileRequest.builder() + .file(fileInput) + .waitTime(waitTime) + .outputDirectory(outputDirectory) + .maskingMethod(maskingMethod) + .build(); + + // Step 3: Invoking deidentifyFile + // Replace `9f27764a10f7946fe56b3258e117` with the acutal vault id + DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect("9f27764a10f7946fe56b3258e117").deidentifyFile(deidentifyFileRequest); + System.out.println("Deidentify file response: " + deidentifyFileResponse.toString()); + } catch (SkyflowException e) { + System.err.println("Error occurred during deidentify file: "); + e.printStackTrace(); + } + } +} + +``` + +Sample response: + +```json +{ + "file": { + "name": "deidentified.txt", + "size": 33, + "type": "", + "lastModified": 1751355183039 + }, + "fileBase64": "bXkgY2FyZCBudW1iZXIgaXMgW0NSRURJVF", + "type": "redacted_file", + "extension": "txt", + "wordCount": 11, + "charCount": 61, + "sizeInKb": 0, + "entities": [ + { + "file": "bmFtZTogW05BTUVfMV0gCm==", + "type": "entities", + "extension": "json" + } + ], + "runId": "undefined", + "status": "success" +} + +``` + +**Supported file types:** +- Documents: `doc`, `docx`, `pdf` +- PDFs: `pdf` +- Images: `bmp`, `jpeg`, `jpg`, `png`, `tif`, `tiff` +- Structured text: `json`, `xml` +- Spreadsheets: `csv`, `xls`, `xlsx` +- Presentations: `ppt`, `pptx` +- Audio: `mp3`, `wav` + +**Note:** +- Transformations cannot be applied to Documents, Images, or PDFs file formats. + +- The `waitTime` option must be ≤ 64 seconds; otherwise, an error is thrown. + +- If the API takes more than 64 seconds to process the file, it will return only the run ID in the response. + +Sample response (when the API takes more than 64 seconds): +```json +{ + "file": null, + "fileBase64": null, + "type": null, + "extension": null, + "wordCount": null, + "charCount": null, + "sizeInKb": null, + "durationInSeconds": null, + "pageCount": null, + "slideCount": null, + "entities": null, + "runId": "1273a8c6-c498-4293-a9d6-389864cd3a44", + "status": "IN_PROGRESS", + "errors": null +} +``` + +## Get run: +To retrieve the results of a previously started file `deidentification operation`, use the `getDetectRun` method. +The `GetDetectRunRequest` class is initialized with the `runId` returned from a prior deidentifyFile call. +This method allows you to fetch the final results of the file processing operation once they are available. + +### Construct an get run request + +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.detect.DeidentifyFileResponse; +import com.skyflow.vault.detect.GetDetectRunRequest; + +/** + * Skyflow Get Detect Run Example + */ + +public class GetDetectRunSchema { + + public static void main(String[] args) { + try { + // Step 1: Initialise the Skyflow client by configuring the credentials & vault config. + + // Step 2: Create a get detect run request + GetDetectRunRequest getDetectRunRequest = GetDetectRunRequest.builder() + .runId("") // Replace with the runId from deidentifyFile call + .build(); + + // Step 3: Call getDetectRun to poll for file processing results + // Replace with your actual vault ID + DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect("").getDetectRun(getDetectRunRequest); + System.out.println("Get Detect Run Response: " + deidentifyFileResponse); + } catch (SkyflowException e) { + System.err.println("Error occurred during get detect run: "); + e.printStackTrace(); + } + } +} + +``` + +## An [example](https://github.com/skyflowapi/skyflow-java/blob/beta-release/25.6.2/samples/src/main/java/com/example/detect/GetDetectRunExample.java) of get run +```java +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.detect.DeidentifyFileResponse; +import com.skyflow.vault.detect.GetDetectRunRequest; + +/** + * Skyflow Get Detect Run Example + *

+ * This example demonstrates how to: + * 1. Configure credentials + * 2. Set up vault configuration + * 3. Create a get detect run request + * 4. Call getDetectRun to poll for file processing results + * 5. Handle response and errors + */ +public class GetDetectRunExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Initialise the Skyflow client by configuring the credentials & vault config. + try { + + // Step 2: Create a get detect run request + GetDetectRunRequest getDetectRunRequest = GetDetectRunRequest.builder() + .runId("e0038196-4a20-422b-bad7-e0477117f9bb") // Replace with the runId from deidentifyFile call + .build(); + + // Step 3: Call getDetectRun to poll for file processing results + // Replace `9f27764a10f7946fe56b3258e117` with the acutal vault id + DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect("9f27764a10f7946fe56b3258e117").getDetectRun(getDetectRunRequest); + System.out.println("Get Detect Run Response: " + deidentifyFileResponse); + } catch (SkyflowException e) { + System.err.println("Error occurred during get detect run: "); + e.printStackTrace(); + } + } +} +``` + +Sample Response: + +```json +{ + "file": "bmFtZTogW05BTET0JfMV0K", + "type": "redacted_file", + "extension": "txt", + "wordCount": 11, + "charCount": 61, + "sizeInKb": 0.0, + "entities": [ + { + "file": "gW05BTUVfMV0gCmNhcmQ0K", + "type": "entities", + "extension": "json" + } + ], + "runId": "e0038196-4a20-422b-bad7-e0477117f9bb", + "status": "success" +} + +``` + # Connections Skyflow Connections is a gateway service that uses tokenization to securely send and receive data between your systems and first- or third-party services. The [connections](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault/connection) module invokes both inbound and/or outbound connections. diff --git a/samples/src/main/java/com/example/detect/DeidentifyFileExample.java b/samples/src/main/java/com/example/detect/DeidentifyFileExample.java new file mode 100644 index 00000000..7f573d33 --- /dev/null +++ b/samples/src/main/java/com/example/detect/DeidentifyFileExample.java @@ -0,0 +1,114 @@ +package com.example.detect; + +import java.io.File; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.enums.MaskingMethod; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.detect.DeidentifyFileRequest; +import com.skyflow.vault.detect.DeidentifyFileResponse; +import com.skyflow.vault.detect.FileInput; + +/** + * Skyflow Deidentify File Example + *

+ * This example demonstrates how to use the Skyflow SDK to deidentify file + * It has all available options for deidentifying files. + * Supported file types: images (jpg, png, etc.), pdf, audio (mp3, wav), documents, spreadsheets, presentations, structured text. + * It includes: + * 1. Configure credentials + * 2. Set up vault configuration + * 3. Create a deidentify file request with all options + * 4. Call deidentifyFile to deidentify file. + * 5. Handle response and errors + */ +public class DeidentifyFileExample { + + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the first vault configuration + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + // Step 2: Configure the vault config + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the ID of the vault + vaultConfig.setClusterId(""); // Replace with the cluster ID of the vault + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate the credentials with the vault + + // Step 3: Create a Skyflow client + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .addVaultConfig(vaultConfig) // Add the vault configuration + .build(); + + try { + + // Step 4: Create a deidentify file request with all options + + // Create file object + File file = new File("") // Alternatively, you can use .filePath() + .build(); + + // Output configuration + String outputDirectory = ""; // Replace with the desired output directory to save the deidentified file + + // Entities to detect + // List detectEntities = new ArrayList<>(); + // detectEntities.add(DetectEntities.IP_ADDRESS); // Replace with the entities you want to detect + + // Image-specific options + // Boolean outputProcessedImage = true; // Include processed image in output + // Boolean outputOcrText = true; // Include OCR text in output + MaskingMethod maskingMethod = MaskingMethod.BLACKBOX; // Masking method for images + + // PDF-specific options + // Integer pixelDensity = 15; // Pixel density for PDF processing + // Integer maxResolution = 2000; // Max resolution for PDF + + // Audio-specific options + // Boolean outputProcessedAudio = true; // Include processed audio + // DetectOutputTranscriptions outputTanscription = DetectOutputTranscriptions.PLAINTEXT_TRANSCRIPTION; // Transcription type + + // Audio bleep configuration + // AudioBleep audioBleep = AudioBleep.builder() + // .frequency(5D) // Pitch in Hz + // .startPadding(7D) // Padding at start (seconds) + // .stopPadding(8D) // Padding at end (seconds) + // .build(); + + Integer waitTime = 20; // Max wait time for response (max 64 seconds) + + DeidentifyFileRequest deidentifyFileRequest = DeidentifyFileRequest.builder() + .file(fileInput) + .waitTime(waitTime) + // .entities(detectEntities) + .outputDirectory(outputDirectory) + .maskingMethod(maskingMethod) + // .outputProcessedImage(outputProcessedImage) + // .outputOcrText(outputOcrText) + // .pixelDensity(pixelDensity) + // .maxResolution(maxResolution) + // .outputProcessedAudio(outputProcessedAudio) + // .outputTranscription(outputTanscription) + // .bleep(audioBleep) + .build(); + + + DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect(vaultConfig.getVaultId()).deidentifyFile(deidentifyFileRequest); + System.out.println("Deidentify file response: " + deidentifyFileResponse.toString()); + } catch (SkyflowException e) { + System.err.println("Error occurred during deidentify file: "); + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/samples/src/main/java/com/example/detect/DeidentifyTextExample.java b/samples/src/main/java/com/example/detect/DeidentifyTextExample.java new file mode 100644 index 00000000..837dde00 --- /dev/null +++ b/samples/src/main/java/com/example/detect/DeidentifyTextExample.java @@ -0,0 +1,142 @@ +package com.example.detect; + +import java.util.ArrayList; +import java.util.List; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.DetectEntities; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.detect.DeidentifyTextRequest; +import com.skyflow.vault.detect.DeidentifyTextResponse; +import com.skyflow.vault.detect.TokenFormat; + +/** + * Skyflow Deidentify Text Example + *

+ * This example demonstrates how to use the Skyflow SDK to deidentify text data + * across multiple vaults. It includes: + * 1. Setting up credentials and vault configurations. + * 2. Creating a Skyflow client with multiple vaults. + * 3. Performing deidentify of text with various options. + * 4. Handling responses and errors. + */ + +public class DeidentifyTextExample { + public static void main(String[] args) throws SkyflowException { + + // Step 1: Set up credentials for the first vault configuration + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + // Step 2: Configure the first vault (Blitz) + VaultConfig blitzConfig = new VaultConfig(); + blitzConfig.setVaultId(""); // Replace with the ID of the first vault + blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault + blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) + blitzConfig.setCredentials(credentials); // Associate the credentials with the vault + + // Step 3: Configure the second vault (Stage) + VaultConfig stageConfig = new VaultConfig(); + stageConfig.setVaultId(""); // Replace with the ID of the second vault + stageConfig.setClusterId(""); // Replace with the cluster ID of the second vault + stageConfig.setEnv(Env.STAGE); // Set the environment for the second vault + + // Step 4: Set up credentials for the Skyflow client + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setPath(""); // Replace with the path to another credentials file + + // Step 5: Create a Skyflow client and add vault configurations + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .addVaultConfig(blitzConfig) // Add the first vault configuration + .addVaultConfig(stageConfig) // Add the second vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials + .build(); + + // Step 6: Configuring the different options for deidentify + // Replace with the entity you want to detect + List detectEntitiesList = new ArrayList<>(); + detectEntitiesList.add(DetectEntities.SSN); + detectEntitiesList.add(DetectEntities.CREDIT_CARD); + + // Replace with the entity you want to detect with vault token + List vaultTokenList = new ArrayList<>(); + vaultTokenList.add(DetectEntities.SSN); + vaultTokenList.add(DetectEntities.CREDIT_CARD); + + // Replace with the entity you want to detect with entity only + // List entityOnlyList = new ArrayList<>(); + // entityOnlyList.add(DetectEntities.SSN); + + // Replace with the entity you want to detect with entity unique counter + // List entityUniqueCounterList = new ArrayList<>(); + // entityUniqueCounterList.add(DetectEntities.SSN); + + // Replace with the regex patterns you want to allow during deidentification + // List allowRegexList = new ArrayList<>(); + // allowRegexList.add(""); + + // Replace with the regex patterns you want to restrict during deidentification + // List restrictRegexList = new ArrayList<>(); + // restrictRegexList.add("YOUR_RESTRICT_REGEX_LIST"); + + // Configure Token Format + TokenFormat tokenFormat = TokenFormat.builder() + .vaultToken(vaultTokenList) + // .entityOnly(entityOnlyList) + // .entityUniqueCounter(entityUniqueCounterList) + .build(); + + // Configure Transformation for deidentified entities + // List detectEntitiesTransformationList = new ArrayList<>(); + // detectEntitiesTransformationList.add(DetectEntities.DOB); // Replace with the entity you want to transform + // detectEntitiesTransformationList.add(DetectEntities.DATE); + + // DateTransformation dateTransformation = new DateTransformation(20, 5, detectEntitiesTransformationList); + // Transformations transformations = new Transformations(dateTransformation); + + // Example 1: Deidentify text on the first vault + try { + // Create a deidentify text request for the first vault + DeidentifyTextRequest deidentifyTextRequest = DeidentifyTextRequest.builder() + .text("My SSN is 123-45-6789 and my card is 4111 1111 1111 1111.") // Replace with the text you want to deidentify + .entities(detectEntitiesList) + // .allowRegexList(allowRegexList) + // .restrictRegexList(restrictRegexList) + .tokenFormat(tokenFormat) + // .transformations(transformations) + .build(); + + + DeidentifyTextResponse deidentifyTextResponse = skyflowClient.detect(blitzConfig.getVaultId()).deidentifyText(deidentifyTextRequest); + + System.out.println("Deidentify text Response (Vault1): " + deidentifyTextResponse); + } catch (SkyflowException e) { + System.err.println("Error occurred during deidentify (Vault1): "); + e.printStackTrace(); + } + // Example 2: Deidentify text on the second vault + try { + // Create a deidentify text request for the second vault + DeidentifyTextRequest deidentifyTextRequest2 = DeidentifyTextRequest.builder() + .text("My SSN is 123-45-6789 and my card is 4111 1111 1111 1111.") // Replace with the text you want to deidentify + .entities(detectEntitiesList) + // .allowRegexList(allowRegexList) + // .restrictRegexList(restrictRegexList) + .tokenFormat(tokenFormat) + // .transformations(transformations) + .build(); + + DeidentifyTextResponse deidentifyTextResponse2 = skyflowClient.detect(stageConfig.getVaultId()).deidentifyText(deidentifyTextRequest2); + System.out.println("Deidentify text Response (Vault2): " + deidentifyTextResponse2); + + } catch (SkyflowException e) { + System.err.println("Error occurred during deidentify (Vault2): "); + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/samples/src/main/java/com/example/detect/GetDetectRunExample.java b/samples/src/main/java/com/example/detect/GetDetectRunExample.java new file mode 100644 index 00000000..09fc2bc4 --- /dev/null +++ b/samples/src/main/java/com/example/detect/GetDetectRunExample.java @@ -0,0 +1,55 @@ +package com.example.detect; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.detect.DeidentifyFileResponse; +import com.skyflow.vault.detect.GetDetectRunRequest; + +/** + * Skyflow Get Detect Run Example + *

+ * This example demonstrates how to: + * 1. Configure credentials + * 2. Set up vault configuration + * 3. Create a get detect run request + * 4. Call getDetectRun to poll for file processing results + * 5. Handle response and errors + */ +public class GetDetectRunExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Configure credentials + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + // Step 2: Configure the vault config + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the ID of the vault + vaultConfig.setClusterId(""); // Replace with the cluster ID of the vault + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate the credentials with the vault + + // Step 3: Create a Skyflow client + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .addVaultConfig(vaultConfig) // Add the vault configuration + .build(); + + try { + // Step 4: Create a get detect run request + GetDetectRunRequest getDetectRunRequest = GetDetectRunRequest.builder() + .runId("") // Replace with the runId from deidentifyFile call + .build(); + + // Step 5: Call getDetectRun to poll for file processing results + DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect(vaultConfig.getVaultId()).getDetectRun(getDetectRunRequest); + System.out.println("Get Detect Run Response: " + deidentifyFileResponse); + } catch (SkyflowException e) { + System.err.println("Error occurred during get detect run: "); + e.printStackTrace(); + } + } +} \ No newline at end of file From 06892d99d44c2e9f6bafeca63931ef8ffc50a8f3 Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Tue, 29 Jul 2025 17:50:58 +0530 Subject: [PATCH 120/126] SK-2207 Update release workflows and POM - Migrating from OSSRH to central publisher portal --- .github/workflows/beta-release.yml | 4 ++-- .github/workflows/release.yml | 4 ++-- pom.xml | 20 ++++++++++---------- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.github/workflows/beta-release.yml b/.github/workflows/beta-release.yml index c723914a..b30cc27f 100644 --- a/.github/workflows/beta-release.yml +++ b/.github/workflows/beta-release.yml @@ -11,8 +11,8 @@ jobs: profile: maven-central tag: 'beta' secrets: - server-username: ${{ secrets.OSSRH_USERNAME }} - server-password: ${{ secrets.OSSRH_PASSWORD }} + server-username: ${{ secrets.CENTRAL_PUBLISHER_PORTAL_USERNAME }} + server-password: ${{ secrets.CENTRAL_PUBLISHER_PORTAL_PASSWORD }} gpg-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} gpg-passphrase: ${{ secrets.MAVEN_GPG_PASSPHRASE }} skyflow-credentials: ${{ secrets.SKYFLOW_CREDENTIALS }} >> .env diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 855b7b4c..76dda879 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,8 +11,8 @@ jobs: profile: maven-central tag: 'public' secrets: - server-username: ${{ secrets.OSSRH_USERNAME }} - server-password: ${{ secrets.OSSRH_PASSWORD }} + server-username: ${{ secrets.CENTRAL_PUBLISHER_PORTAL_USERNAME }} + server-password: ${{ secrets.CENTRAL_PUBLISHER_PORTAL_PASSWORD }} gpg-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} gpg-passphrase: ${{ secrets.MAVEN_GPG_PASSPHRASE }} skyflow-credentials: ${{ secrets.SKYFLOW_CREDENTIALS }} >> .env diff --git a/pom.xml b/pom.xml index 832fd901..df054845 100644 --- a/pom.xml +++ b/pom.xml @@ -263,25 +263,25 @@ maven-central - ossrh - https://s01.oss.sonatype.org/service/local/staging/deploy/maven2 + central + https://central.sonatype.com/api/v1/publisher/upload - ossrh - https://s01.oss.sonatype.org/content/repositories/snapshots + central-snapshots + https://central.sonatype.com/api/v1/publisher/upload - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 + org.sonatype.central + central-publishing-maven-plugin + 0.4.0 true - ossrh - https://s01.oss.sonatype.org/ - true + central + true + true From 655c61218fa3542a8c511ef7cdb14b260f48dad3 Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow <156889717+saileshwar-skyflow@users.noreply.github.com> Date: Wed, 10 Sep 2025 17:48:30 +0530 Subject: [PATCH 121/126] SK-1817: Public release Java SDK V2 (#222) * SK-1817: public release for v2 --- .github/workflows/beta-release.yml | 2 +- .github/workflows/pr.yml | 2 +- .github/workflows/release.yml | 2 +- .github/workflows/shared-build-and-deploy.yml | 4 +- pom.xml | 26 +- src/main/java/com/skyflow/VaultClient.java | 36 +- .../skyflow/enums/DeidentifyFileStatus.java | 4 +- .../com/skyflow/enums/DetectEntities.java | 9 +- .../java/com/skyflow/errors/ErrorMessage.java | 8 + .../com/skyflow/generated/rest/ApiClient.java | 10 +- .../generated/rest/AsyncApiClient.java | 10 +- .../generated/rest/core/ClientOptions.java | 2 +- .../rest/core/QueryStringMapperTest.java | 339 ---------- .../deprecated/AsyncDeprecatedClient.java | 89 --- .../deprecated/AsyncRawDeprecatedClient.java | 271 -------- .../deprecated/DeprecatedClient.java | 87 --- .../deprecated/RawDeprecatedClient.java | 222 ------ .../DetectServiceDetectStatusRequest.java | 101 --- .../DetectServiceDetectTextRequest.java | 526 --------------- .../requests/V1DetectFileRequest.java | 634 ------------------ .../resources/files/AsyncFilesClient.java | 17 + .../resources/files/AsyncRawFilesClient.java | 90 +++ .../rest/resources/files/FilesClient.java | 16 + .../rest/resources/files/RawFilesClient.java | 69 ++ .../requests/DeidentifyAudioRequest.java | 32 + .../requests/DeidentifyDocumentRequest.java | 32 + .../files/requests/DeidentifyFileRequest.java | 32 + .../requests/DeidentifyImageRequest.java | 32 + .../files/requests/DeidentifyPdfRequest.java | 64 +- .../DeidentifyPresentationRequest.java | 32 + .../DeidentifySpreadsheetRequest.java | 32 + .../DeidentifyStructuredTextRequest.java | 32 + .../files/requests/DeidentifyTextRequest.java | 32 + .../files/requests/ReidentifyFileRequest.java | 183 +++++ .../DeidentifyFileRequestFileDataFormat.java | 2 + .../types/ReidentifyFileRequestFile.java | 145 ++++ .../ReidentifyFileRequestFileDataFormat.java} | 34 +- .../types/ReidentifyFileRequestFormat.java | 163 +++++ .../guardrails/AsyncGuardrailsClient.java | 43 ++ .../guardrails/AsyncRawGuardrailsClient.java | 127 ++++ .../guardrails/GuardrailsClient.java | 41 ++ .../guardrails/RawGuardrailsClient.java | 102 +++ .../requests/CheckGuardrailsRequest.java | 227 +++++++ .../records/AsyncRawRecordsClient.java | 143 +++- .../resources/records/AsyncRecordsClient.java | 36 +- .../resources/records/RawRecordsClient.java | 122 +++- .../rest/resources/records/RecordsClient.java | 35 +- .../FileServiceUploadFileRequest.java | 48 +- .../records/requests/UploadFileV2Request.java | 236 +++++++ .../requests/DeidentifyStringRequest.java | 32 + .../types/AdvancedOptionsColumnMapping.java | 194 ------ .../types/AdvancedOptionsEntityColumnMap.java | 126 ---- .../types/AdvancedOptionsVaultSchema.java | 135 ---- .../types/AudioConfigTranscriptionType.java | 40 -- .../rest/types/CheckGuardrailsResponse.java | 193 ++++++ ...=> CheckGuardrailsResponseValidation.java} | 8 +- .../rest/types/DeidentifyStatusResponse.java | 32 +- .../DeidentifyStatusResponseOutputType.java | 2 - .../types/DeidentifyStatusResponseStatus.java | 4 +- .../rest/types/DetectDataAccuracy.java | 36 - .../rest/types/DetectDataEntities.java | 146 ---- .../generated/rest/types/EntityType.java | 16 +- .../ProcessedFileOutputProcessedFileType.java | 40 -- .../rest/types/ReidentifyFileResponse.java | 170 +++++ .../types/ReidentifyFileResponseOutput.java | 154 +++++ ... => ReidentifyFileResponseOutputType.java} | 10 +- ...java => ReidentifyFileResponseStatus.java} | 10 +- .../rest/types/UploadFileV2Response.java | 124 ++++ .../rest/types/V1AdvancedOptions.java | 157 ----- .../generated/rest/types/V1AudioConfig.java | 151 ----- .../generated/rest/types/V1AudioOptions.java | 234 ------- .../rest/types/V1DetectFileResponse.java | 101 --- .../rest/types/V1DetectStatusResponse.java | 156 ----- .../rest/types/V1DetectTextRequest.java | 522 -------------- .../rest/types/V1DetectTextResponse.java | 133 ---- .../generated/rest/types/V1ImageOptions.java | 132 ---- .../generated/rest/types/V1Locations.java | 193 ------ .../generated/rest/types/V1PdfConfig.java | 95 --- .../generated/rest/types/V1PdfOptions.java | 130 ---- .../rest/types/V1ProcessedFileOutput.java | 151 ----- .../rest/types/V1ResponseEntities.java | 218 ------ src/main/java/com/skyflow/logs/ErrorLogs.java | 9 + src/main/java/com/skyflow/logs/InfoLogs.java | 5 + .../java/com/skyflow/utils/Constants.java | 4 +- .../utils/validations/Validations.java | 108 ++- .../connection/InvokeConnectionResponse.java | 11 +- .../controller/ConnectionController.java | 2 +- .../vault/controller/DetectController.java | 88 ++- .../vault/controller/VaultController.java | 53 +- .../skyflow/vault/data/FileUploadRequest.java | 97 +++ .../vault/data/FileUploadResponse.java | 31 + .../com/skyflow/vault/data/GetResponse.java | 2 +- .../skyflow/vault/data/InsertResponse.java | 2 +- .../vault/detect/DeidentifyFileResponse.java | 10 +- .../skyflow/vault/tokens/DetokenizeData.java | 4 +- .../vault/tokens/DetokenizeResponse.java | 27 +- .../skyflow/errors/SkyflowExceptionTest.java | 60 +- .../util/SignedDataTokensTests.java | 7 +- .../connection/InvokeConnectionTests.java | 6 +- .../controller/VaultControllerTests.java | 20 + .../skyflow/vault/data/FileUploadTests.java | 222 ++++++ .../java/com/skyflow/vault/data/GetTests.java | 6 +- .../detect/DeidentifyFileResponseTest.java | 5 +- .../skyflow/vault/tokens/DetokenizeTests.java | 2 +- 104 files changed, 3599 insertions(+), 5610 deletions(-) delete mode 100644 src/main/java/com/skyflow/generated/rest/core/QueryStringMapperTest.java delete mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncDeprecatedClient.java delete mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncRawDeprecatedClient.java delete mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/DeprecatedClient.java delete mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/RawDeprecatedClient.java delete mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectStatusRequest.java delete mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectTextRequest.java delete mode 100644 src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/V1DetectFileRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/requests/ReidentifyFileRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/ReidentifyFileRequestFile.java rename src/main/java/com/skyflow/generated/rest/{types/V1FileDataFormat.java => resources/files/types/ReidentifyFileRequestFileDataFormat.java} (54%) create mode 100644 src/main/java/com/skyflow/generated/rest/resources/files/types/ReidentifyFileRequestFormat.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncGuardrailsClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncRawGuardrailsClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/guardrails/GuardrailsClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/guardrails/RawGuardrailsClient.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/guardrails/requests/CheckGuardrailsRequest.java create mode 100644 src/main/java/com/skyflow/generated/rest/resources/records/requests/UploadFileV2Request.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsColumnMapping.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsEntityColumnMap.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsVaultSchema.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/AudioConfigTranscriptionType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/CheckGuardrailsResponse.java rename src/main/java/com/skyflow/generated/rest/types/{DetectFileRequestDataType.java => CheckGuardrailsResponseValidation.java} (70%) delete mode 100644 src/main/java/com/skyflow/generated/rest/types/DetectDataAccuracy.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/DetectDataEntities.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/ProcessedFileOutputProcessedFileType.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponse.java create mode 100644 src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseOutput.java rename src/main/java/com/skyflow/generated/rest/types/{DetectRequestDeidentifyOption.java => ReidentifyFileResponseOutputType.java} (63%) rename src/main/java/com/skyflow/generated/rest/types/{V1DetectStatusResponseStatus.java => ReidentifyFileResponseStatus.java} (72%) create mode 100644 src/main/java/com/skyflow/generated/rest/types/UploadFileV2Response.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/V1AdvancedOptions.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/V1AudioConfig.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/V1AudioOptions.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DetectFileResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DetectTextRequest.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/V1DetectTextResponse.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/V1ImageOptions.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/V1Locations.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/V1PdfConfig.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/V1PdfOptions.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/V1ProcessedFileOutput.java delete mode 100644 src/main/java/com/skyflow/generated/rest/types/V1ResponseEntities.java create mode 100644 src/main/java/com/skyflow/vault/data/FileUploadRequest.java create mode 100644 src/main/java/com/skyflow/vault/data/FileUploadResponse.java create mode 100644 src/test/java/com/skyflow/vault/data/FileUploadTests.java diff --git a/.github/workflows/beta-release.yml b/.github/workflows/beta-release.yml index b30cc27f..13fcf623 100644 --- a/.github/workflows/beta-release.yml +++ b/.github/workflows/beta-release.yml @@ -7,7 +7,7 @@ jobs: uses: ./.github/workflows/shared-build-and-deploy.yml with: ref: ${{ github.ref_name }} - server-id: ossrh + server-id: central profile: maven-central tag: 'beta' secrets: diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 3883a1a9..2b2945f0 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -22,7 +22,7 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-java@v1 with: - java-version: "1.8" + java-version: "11" - name: create-json id: create-json diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 76dda879..1cc20ca1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,7 +7,7 @@ jobs: uses: ./.github/workflows/shared-build-and-deploy.yml with: ref: ${{ github.ref_name }} - server-id: ossrh + server-id: central profile: maven-central tag: 'public' secrets: diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index c9cadd2c..13fd1b5b 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -52,9 +52,9 @@ jobs: fetch-depth: 0 - name: Set up maven or jfrog repository - uses: actions/setup-java@v1 + uses: actions/setup-java@v4 with: - java-version: "1.8" + java-version: "11" distribution: "adopt" server-id: ${{ inputs.server-id }} server-username: SERVER_USERNAME diff --git a/pom.xml b/pom.xml index df054845..fb6a5d0e 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 2.0.0-beta.2 + 2.0.0-beta.4 jar ${project.groupId}:${project.artifactId} @@ -45,12 +45,6 @@ - - com.squareup.okhttp3 - okhttp - 4.12.0 - compile - com.fasterxml.jackson.core jackson-databind @@ -126,9 +120,10 @@ junit junit - ${junit-version} + 4.13.2 test + org.powermock powermock-module-junit4 @@ -141,12 +136,6 @@ 2.0.9 test - - org.junit.jupiter - junit-jupiter - 5.13.2 - compile - @@ -185,7 +174,14 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.2 + 3.2.5 + + false + + **/*Test.java + **/*Tests.java + + org.jacoco diff --git a/src/main/java/com/skyflow/VaultClient.java b/src/main/java/com/skyflow/VaultClient.java index 7536a2c1..edb8ee47 100644 --- a/src/main/java/com/skyflow/VaultClient.java +++ b/src/main/java/com/skyflow/VaultClient.java @@ -17,6 +17,7 @@ import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.resources.records.requests.UploadFileV2Request; import com.skyflow.generated.rest.resources.strings.StringsClient; import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; @@ -32,6 +33,7 @@ import com.skyflow.utils.Utils; import com.skyflow.utils.logger.LogUtil; import com.skyflow.utils.validations.Validations; +import com.skyflow.vault.data.FileUploadRequest; import com.skyflow.vault.data.InsertRequest; import com.skyflow.vault.data.UpdateRequest; import com.skyflow.vault.detect.*; @@ -44,6 +46,10 @@ import io.github.cdimascio.dotenv.Dotenv; import io.github.cdimascio.dotenv.DotenvException; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; @@ -209,6 +215,22 @@ protected V1TokenizePayload getTokenizePayload(TokenizeRequest request) { return payloadBuilder.build(); } + protected File getFileForFileUpload(FileUploadRequest fileUploadRequest) throws IOException { + if (fileUploadRequest.getFilePath() != null) { + return new File(fileUploadRequest.getFilePath()); + } + else if (fileUploadRequest.getBase64() != null) { + byte[] decodedBytes = Base64.getDecoder().decode(fileUploadRequest.getBase64()); + File file = new File(fileUploadRequest.getFileName()); + Files.write(file.toPath(), decodedBytes); + return file; + } + else if (fileUploadRequest.getFileObject() != null) { + return fileUploadRequest.getFileObject(); + } + return null; + } + protected void setBearerToken() throws SkyflowException { prioritiseCredentials(); Validations.validateCredentials(this.finalCredentials); @@ -512,7 +534,6 @@ protected DeidentifyPdfRequest getDeidentifyPdfRequest(DeidentifyFileRequest req Optional> entityUniqueCounter = Optional.empty(); Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); if (tokenFormat != null) { if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { @@ -540,13 +561,12 @@ protected DeidentifyPdfRequest getDeidentifyPdfRequest(DeidentifyFileRequest req return DeidentifyPdfRequest.builder() .vaultId(vaultId) .file(file) - .density(request.getPixelDensity() != null ? request.getPixelDensity().intValue() : null) - .maxResolution(request.getMaxResolution() != null ? request.getMaxResolution().intValue() : null) + .density(request.getPixelDensity() != null ? request.getPixelDensity().doubleValue() : null) + .maxResolution(request.getMaxResolution() != null ? request.getMaxResolution().doubleValue() : null) .entityTypes(mappedEntityTypes) .tokenType(tokenType) .allowRegex(allowRegex) .restrictRegex(restrictRegex) - .transformations(transformations) .build(); } @@ -558,7 +578,6 @@ protected DeidentifyImageRequest getDeidentifyImageRequest(DeidentifyFileRequest Optional> entityUniqueCounter = Optional.empty(); Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); @@ -580,7 +599,6 @@ protected DeidentifyImageRequest getDeidentifyImageRequest(DeidentifyFileRequest .tokenType(tokenType) .allowRegex(allowRegex) .restrictRegex(restrictRegex) - .transformations(transformations) .outputProcessedImage(request.getOutputProcessedImage()) .outputOcrText(request.getOutputOcrText()) .build(); @@ -594,7 +612,6 @@ protected DeidentifyPresentationRequest getDeidentifyPresentationRequest(Deident Optional> entityUniqueCounter = Optional.empty(); Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); @@ -610,7 +627,6 @@ protected DeidentifyPresentationRequest getDeidentifyPresentationRequest(Deident .tokenType(tokenType) .allowRegex(allowRegex) .restrictRegex(restrictRegex) - .transformations(transformations) .build(); } @@ -622,7 +638,6 @@ protected DeidentifySpreadsheetRequest getDeidentifySpreadsheetRequest(Deidentif Optional> entityUniqueCounter = Optional.empty(); Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); @@ -638,7 +653,6 @@ protected DeidentifySpreadsheetRequest getDeidentifySpreadsheetRequest(Deidentif .tokenType(tokenType) .allowRegex(allowRegex) .restrictRegex(restrictRegex) - .transformations(transformations) .build(); } @@ -678,7 +692,6 @@ protected DeidentifyDocumentRequest getDeidentifyDocumentRequest(DeidentifyFileR Optional> entityUniqueCounter = Optional.empty(); Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); - Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); @@ -694,7 +707,6 @@ protected DeidentifyDocumentRequest getDeidentifyDocumentRequest(DeidentifyFileR .tokenType(tokenType) .allowRegex(allowRegex) .restrictRegex(restrictRegex) - .transformations(transformations) .build(); } diff --git a/src/main/java/com/skyflow/enums/DeidentifyFileStatus.java b/src/main/java/com/skyflow/enums/DeidentifyFileStatus.java index e17c6d0c..87ffc109 100644 --- a/src/main/java/com/skyflow/enums/DeidentifyFileStatus.java +++ b/src/main/java/com/skyflow/enums/DeidentifyFileStatus.java @@ -2,7 +2,9 @@ public enum DeidentifyFileStatus { IN_PROGRESS("IN_PROGRESS"), - SUCCESS("SUCCESS"); + FAILED("FAILED"), + SUCCESS("SUCCESS"), + UNKNOWN("UNKNOWN"); private final String value; diff --git a/src/main/java/com/skyflow/enums/DetectEntities.java b/src/main/java/com/skyflow/enums/DetectEntities.java index f2c21eff..3fd15a67 100644 --- a/src/main/java/com/skyflow/enums/DetectEntities.java +++ b/src/main/java/com/skyflow/enums/DetectEntities.java @@ -13,17 +13,19 @@ public enum DetectEntities { CREDIT_CARD_EXPIRATION("credit_card_expiration"), CVV("cvv"), DATE("date"), + DAY("day"), DATE_INTERVAL("date_interval"), DOB("dob"), DOSE("dose"), DRIVER_LICENSE("driver_license"), DRUG("drug"), DURATION("duration"), + EFFECT("effect"), EMAIL_ADDRESS("email_address"), EVENT("event"), FILENAME("filename"), FINANCIAL_METRIC("financial_metric"), - GENDER_SEXUALITY("gender_sexuality"), + GENDER("gender"), HEALTHCARE_NUMBER("healthcare_number"), INJURY("injury"), IP_ADDRESS("ip_address"), @@ -40,6 +42,7 @@ public enum DetectEntities { MEDICAL_CODE("medical_code"), MEDICAL_PROCESS("medical_process"), MONEY("money"), + MONTH("month"), NAME("name"), NAME_FAMILY("name_family"), NAME_GIVEN("name_given"), @@ -47,16 +50,19 @@ public enum DetectEntities { NUMERICAL_PII("numerical_pii"), OCCUPATION("occupation"), ORGANIZATION("organization"), + ORGANIZATION_ID("organization_id"), ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), ORIGIN("origin"), PASSPORT_NUMBER("passport_number"), PASSWORD("password"), PHONE_NUMBER("phone_number"), + PROJECT("project"), PHYSICAL_ATTRIBUTE("physical_attribute"), POLITICAL_AFFILIATION("political_affiliation"), PRODUCT("product"), RELIGION("religion"), ROUTING_NUMBER("routing_number"), + SEXUALITY("sexuality"), SSN("ssn"), STATISTICS("statistics"), TIME("time"), @@ -64,6 +70,7 @@ public enum DetectEntities { URL("url"), USERNAME("username"), VEHICLE_ID("vehicle_id"), + YEAR("year"), ZODIAC_SIGN("zodiac_sign"); private final String detectEntities; diff --git a/src/main/java/com/skyflow/errors/ErrorMessage.java b/src/main/java/com/skyflow/errors/ErrorMessage.java index df075bca..ac6adfd0 100644 --- a/src/main/java/com/skyflow/errors/ErrorMessage.java +++ b/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -124,6 +124,13 @@ public enum ErrorMessage { InvalidRequestBody("%s0 Validation error. Invalid request body. Specify the request body as an object."), EmptyRequestBody("%s0 Validation error. Request body can't be empty. Specify a valid request body."), + // File upload + ColumnNameKeyErrorFileUpload("%s0 Validation error. columnName is missing from the payload. Specify a columnName key."), + MissingFileSourceInUploadFileRequest("%s0 Validation error. Provide exactly one of filePath, base64, or fileObject."), + FileNameMustBeProvidedWithFileObject("%s0 Validation error. fileName must be provided when using fileObject."), + InvalidFileObject("%s0 Validation error. Invalid file object in file upload request. Specify a valid file object."), + InvalidBase64("%s0 Validation error. Invalid base64 string in file upload request. Specify a valid base64 string."), + // detect InvalidTextInDeIdentify("%s0 Validation error. The text field is required and must be a non-empty string. Specify a valid text."), InvalidTextInReIdentify("%s0 Validation error. The text field is required and must be a non-empty string. Specify a valid text."), @@ -144,6 +151,7 @@ public enum ErrorMessage { FailedToEncodeFile("%s0 Validation error. Failed to encode the file. Ensure the file is in a supported format and try again."), FailedToDecodeFileFromResponse("%s0 Failed to decode the file from the response. Ensure the response is valid and try again."), EmptyFileAndFilePathInDeIdentifyFile("%s0 Validation error. Both file and filePath are empty. Specify either file object or filePath, not both."), + VaultTokenFormatIsNotAllowedForFiles("%s0 Validation error. Vault token format is not allowed for deidentify file request."), PollingForResultsFailed("%s0 API error. Polling for results failed. Unable to retrieve the deidentified file"), FailedtoSaveProcessedFile("%s0 Validation error. Failed to save the processed file. Ensure the output directory is valid and writable."), InvalidAudioFileType("%s0 Validation error. The file type is not supported. Specify a valid file type mp3 or wav."), diff --git a/src/main/java/com/skyflow/generated/rest/ApiClient.java b/src/main/java/com/skyflow/generated/rest/ApiClient.java index 296a553f..7c5ae554 100644 --- a/src/main/java/com/skyflow/generated/rest/ApiClient.java +++ b/src/main/java/com/skyflow/generated/rest/ApiClient.java @@ -8,8 +8,8 @@ import com.skyflow.generated.rest.resources.audit.AuditClient; import com.skyflow.generated.rest.resources.authentication.AuthenticationClient; import com.skyflow.generated.rest.resources.binlookup.BinLookupClient; -import com.skyflow.generated.rest.resources.deprecated.DeprecatedClient; import com.skyflow.generated.rest.resources.files.FilesClient; +import com.skyflow.generated.rest.resources.guardrails.GuardrailsClient; import com.skyflow.generated.rest.resources.query.QueryClient; import com.skyflow.generated.rest.resources.records.RecordsClient; import com.skyflow.generated.rest.resources.strings.StringsClient; @@ -31,7 +31,7 @@ public class ApiClient { protected final Supplier authenticationClient; - protected final Supplier deprecatedClient; + protected final Supplier guardrailsClient; protected final Supplier stringsClient; @@ -45,7 +45,7 @@ public ApiClient(ClientOptions clientOptions) { this.tokensClient = Suppliers.memoize(() -> new TokensClient(clientOptions)); this.queryClient = Suppliers.memoize(() -> new QueryClient(clientOptions)); this.authenticationClient = Suppliers.memoize(() -> new AuthenticationClient(clientOptions)); - this.deprecatedClient = Suppliers.memoize(() -> new DeprecatedClient(clientOptions)); + this.guardrailsClient = Suppliers.memoize(() -> new GuardrailsClient(clientOptions)); this.stringsClient = Suppliers.memoize(() -> new StringsClient(clientOptions)); this.filesClient = Suppliers.memoize(() -> new FilesClient(clientOptions)); } @@ -74,8 +74,8 @@ public AuthenticationClient authentication() { return this.authenticationClient.get(); } - public DeprecatedClient deprecated() { - return this.deprecatedClient.get(); + public GuardrailsClient guardrails() { + return this.guardrailsClient.get(); } public StringsClient strings() { diff --git a/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java b/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java index d36c8141..1fb7b844 100644 --- a/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java +++ b/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java @@ -8,8 +8,8 @@ import com.skyflow.generated.rest.resources.audit.AsyncAuditClient; import com.skyflow.generated.rest.resources.authentication.AsyncAuthenticationClient; import com.skyflow.generated.rest.resources.binlookup.AsyncBinLookupClient; -import com.skyflow.generated.rest.resources.deprecated.AsyncDeprecatedClient; import com.skyflow.generated.rest.resources.files.AsyncFilesClient; +import com.skyflow.generated.rest.resources.guardrails.AsyncGuardrailsClient; import com.skyflow.generated.rest.resources.query.AsyncQueryClient; import com.skyflow.generated.rest.resources.records.AsyncRecordsClient; import com.skyflow.generated.rest.resources.strings.AsyncStringsClient; @@ -31,7 +31,7 @@ public class AsyncApiClient { protected final Supplier authenticationClient; - protected final Supplier deprecatedClient; + protected final Supplier guardrailsClient; protected final Supplier stringsClient; @@ -45,7 +45,7 @@ public AsyncApiClient(ClientOptions clientOptions) { this.tokensClient = Suppliers.memoize(() -> new AsyncTokensClient(clientOptions)); this.queryClient = Suppliers.memoize(() -> new AsyncQueryClient(clientOptions)); this.authenticationClient = Suppliers.memoize(() -> new AsyncAuthenticationClient(clientOptions)); - this.deprecatedClient = Suppliers.memoize(() -> new AsyncDeprecatedClient(clientOptions)); + this.guardrailsClient = Suppliers.memoize(() -> new AsyncGuardrailsClient(clientOptions)); this.stringsClient = Suppliers.memoize(() -> new AsyncStringsClient(clientOptions)); this.filesClient = Suppliers.memoize(() -> new AsyncFilesClient(clientOptions)); } @@ -74,8 +74,8 @@ public AsyncAuthenticationClient authentication() { return this.authenticationClient.get(); } - public AsyncDeprecatedClient deprecated() { - return this.deprecatedClient.get(); + public AsyncGuardrailsClient guardrails() { + return this.guardrailsClient.get(); } public AsyncStringsClient strings() { diff --git a/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java b/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java index badaddd3..fe635bf1 100644 --- a/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java +++ b/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java @@ -34,7 +34,7 @@ private ClientOptions( { put("X-Fern-Language", "JAVA"); put("X-Fern-SDK-Name", "com.skyflow.fern:api-sdk"); - put("X-Fern-SDK-Version", "0.0.219"); + put("X-Fern-SDK-Version", "0.0.322"); } }); this.headerSuppliers = headerSuppliers; diff --git a/src/main/java/com/skyflow/generated/rest/core/QueryStringMapperTest.java b/src/main/java/com/skyflow/generated/rest/core/QueryStringMapperTest.java deleted file mode 100644 index c5728721..00000000 --- a/src/main/java/com/skyflow/generated/rest/core/QueryStringMapperTest.java +++ /dev/null @@ -1,339 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.core; - -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import okhttp3.HttpUrl; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public final class QueryStringMapperTest { - @Test - public void testObjectWithQuotedString_indexedArrays() { - Map map = new HashMap() { - { - put("hello", "\"world\""); - } - }; - - String expectedQueryString = "withquoted%5Bhello%5D=%22world%22"; - - String actualQueryString = queryString( - new HashMap() { - { - put("withquoted", map); - } - }, - false); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObjectWithQuotedString_arraysAsRepeats() { - Map map = new HashMap() { - { - put("hello", "\"world\""); - } - }; - - String expectedQueryString = "withquoted%5Bhello%5D=%22world%22"; - - String actualQueryString = queryString( - new HashMap() { - { - put("withquoted", map); - } - }, - true); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObject_indexedArrays() { - Map map = new HashMap() { - { - put("foo", "bar"); - put("baz", "qux"); - } - }; - - String expectedQueryString = "metadata%5Bfoo%5D=bar&metadata%5Bbaz%5D=qux"; - - String actualQueryString = queryString( - new HashMap() { - { - put("metadata", map); - } - }, - false); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObject_arraysAsRepeats() { - Map map = new HashMap() { - { - put("foo", "bar"); - put("baz", "qux"); - } - }; - - String expectedQueryString = "metadata%5Bfoo%5D=bar&metadata%5Bbaz%5D=qux"; - - String actualQueryString = queryString( - new HashMap() { - { - put("metadata", map); - } - }, - true); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testNestedObject_indexedArrays() { - Map> nestedMap = new HashMap>() { - { - put("mapkey1", new HashMap() { - { - put("mapkey1mapkey1", "mapkey1mapkey1value"); - put("mapkey1mapkey2", "mapkey1mapkey2value"); - } - }); - put("mapkey2", new HashMap() { - { - put("mapkey2mapkey1", "mapkey2mapkey1value"); - } - }); - } - }; - - String expectedQueryString = - "nested%5Bmapkey2%5D%5Bmapkey2mapkey1%5D=mapkey2mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey1" - + "%5D=mapkey1mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey2%5D=mapkey1mapkey2value"; - - String actualQueryString = queryString( - new HashMap() { - { - put("nested", nestedMap); - } - }, - false); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testNestedObject_arraysAsRepeats() { - Map> nestedMap = new HashMap>() { - { - put("mapkey1", new HashMap() { - { - put("mapkey1mapkey1", "mapkey1mapkey1value"); - put("mapkey1mapkey2", "mapkey1mapkey2value"); - } - }); - put("mapkey2", new HashMap() { - { - put("mapkey2mapkey1", "mapkey2mapkey1value"); - } - }); - } - }; - - String expectedQueryString = - "nested%5Bmapkey2%5D%5Bmapkey2mapkey1%5D=mapkey2mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey1" - + "%5D=mapkey1mapkey1value&nested%5Bmapkey1%5D%5Bmapkey1mapkey2%5D=mapkey1mapkey2value"; - - String actualQueryString = queryString( - new HashMap() { - { - put("nested", nestedMap); - } - }, - true); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testDateTime_indexedArrays() { - OffsetDateTime dateTime = - OffsetDateTime.ofInstant(Instant.ofEpochSecond(1740412107L), ZoneId.of("America/New_York")); - - String expectedQueryString = "datetime=2025-02-24T10%3A48%3A27-05%3A00"; - - String actualQueryString = queryString( - new HashMap() { - { - put("datetime", dateTime); - } - }, - false); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testDateTime_arraysAsRepeats() { - OffsetDateTime dateTime = - OffsetDateTime.ofInstant(Instant.ofEpochSecond(1740412107L), ZoneId.of("America/New_York")); - - String expectedQueryString = "datetime=2025-02-24T10%3A48%3A27-05%3A00"; - - String actualQueryString = queryString( - new HashMap() { - { - put("datetime", dateTime); - } - }, - true); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObjectArray_indexedArrays() { - List> mapArray = new ArrayList>() { - { - add(new HashMap() { - { - put("key", "hello"); - put("value", "world"); - } - }); - add(new HashMap() { - { - put("key", "foo"); - put("value", "bar"); - } - }); - add(new HashMap<>()); - } - }; - - String expectedQueryString = "objects%5B0%5D%5Bvalue%5D=world&objects%5B0%5D%5Bkey%5D=hello&objects%5B1%5D" - + "%5Bvalue%5D=bar&objects%5B1%5D%5Bkey%5D=foo"; - - String actualQueryString = queryString( - new HashMap() { - { - put("objects", mapArray); - } - }, - false); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObjectArray_arraysAsRepeats() { - List> mapArray = new ArrayList>() { - { - add(new HashMap() { - { - put("key", "hello"); - put("value", "world"); - } - }); - add(new HashMap() { - { - put("key", "foo"); - put("value", "bar"); - } - }); - add(new HashMap<>()); - } - }; - - String expectedQueryString = - "objects%5Bvalue%5D=world&objects%5Bkey%5D=hello&objects%5Bvalue" + "%5D=bar&objects%5Bkey%5D=foo"; - - String actualQueryString = queryString( - new HashMap() { - { - put("objects", mapArray); - } - }, - true); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObjectWithArray_indexedArrays() { - Map objectWithArray = new HashMap() { - { - put("id", "abc123"); - put("contactIds", new ArrayList() { - { - add("id1"); - add("id2"); - add("id3"); - } - }); - } - }; - - String expectedQueryString = - "objectwitharray%5Bid%5D=abc123&objectwitharray%5BcontactIds%5D%5B0%5D=id1&objectwitharray" - + "%5BcontactIds%5D%5B1%5D=id2&objectwitharray%5BcontactIds%5D%5B2%5D=id3"; - - String actualQueryString = queryString( - new HashMap() { - { - put("objectwitharray", objectWithArray); - } - }, - false); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - @Test - public void testObjectWithArray_arraysAsRepeats() { - Map objectWithArray = new HashMap() { - { - put("id", "abc123"); - put("contactIds", new ArrayList() { - { - add("id1"); - add("id2"); - add("id3"); - } - }); - } - }; - - String expectedQueryString = "objectwitharray%5Bid%5D=abc123&objectwitharray%5BcontactIds" - + "%5D=id1&objectwitharray%5BcontactIds%5D=id2&objectwitharray%5BcontactIds%5D=id3"; - - String actualQueryString = queryString( - new HashMap() { - { - put("objectwitharray", objectWithArray); - } - }, - true); - - Assertions.assertEquals(expectedQueryString, actualQueryString); - } - - private static String queryString(Map params, boolean arraysAsRepeats) { - HttpUrl.Builder httpUrl = HttpUrl.parse("http://www.fakewebsite.com/").newBuilder(); - params.forEach((paramName, paramValue) -> - QueryStringMapper.addQueryParameter(httpUrl, paramName, paramValue, arraysAsRepeats)); - return httpUrl.build().encodedQuery(); - } -} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncDeprecatedClient.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncDeprecatedClient.java deleted file mode 100644 index c1709f7f..00000000 --- a/src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncDeprecatedClient.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.deprecated; - -import com.skyflow.generated.rest.core.ClientOptions; -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectStatusRequest; -import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectTextRequest; -import com.skyflow.generated.rest.resources.deprecated.requests.V1DetectFileRequest; -import com.skyflow.generated.rest.types.V1DetectFileResponse; -import com.skyflow.generated.rest.types.V1DetectStatusResponse; -import com.skyflow.generated.rest.types.V1DetectTextResponse; -import java.util.concurrent.CompletableFuture; - -public class AsyncDeprecatedClient { - protected final ClientOptions clientOptions; - - private final AsyncRawDeprecatedClient rawClient; - - public AsyncDeprecatedClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new AsyncRawDeprecatedClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public AsyncRawDeprecatedClient withRawResponse() { - return this.rawClient; - } - - /** - * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. - */ - public CompletableFuture detectServiceDetectFileInput(V1DetectFileRequest request) { - return this.rawClient.detectServiceDetectFileInput(request).thenApply(response -> response.body()); - } - - /** - * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. - */ - public CompletableFuture detectServiceDetectFileInput( - V1DetectFileRequest request, RequestOptions requestOptions) { - return this.rawClient - .detectServiceDetectFileInput(request, requestOptions) - .thenApply(response -> response.body()); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. - */ - public CompletableFuture detectServiceDetectStatus(String id) { - return this.rawClient.detectServiceDetectStatus(id).thenApply(response -> response.body()); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. - */ - public CompletableFuture detectServiceDetectStatus( - String id, DetectServiceDetectStatusRequest request) { - return this.rawClient.detectServiceDetectStatus(id, request).thenApply(response -> response.body()); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. - */ - public CompletableFuture detectServiceDetectStatus( - String id, DetectServiceDetectStatusRequest request, RequestOptions requestOptions) { - return this.rawClient - .detectServiceDetectStatus(id, request, requestOptions) - .thenApply(response -> response.body()); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. - */ - public CompletableFuture detectServiceDetectText(DetectServiceDetectTextRequest request) { - return this.rawClient.detectServiceDetectText(request).thenApply(response -> response.body()); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. - */ - public CompletableFuture detectServiceDetectText( - DetectServiceDetectTextRequest request, RequestOptions requestOptions) { - return this.rawClient.detectServiceDetectText(request, requestOptions).thenApply(response -> response.body()); - } -} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncRawDeprecatedClient.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncRawDeprecatedClient.java deleted file mode 100644 index 9c9ec79a..00000000 --- a/src/main/java/com/skyflow/generated/rest/resources/deprecated/AsyncRawDeprecatedClient.java +++ /dev/null @@ -1,271 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.deprecated; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.ApiClientApiException; -import com.skyflow.generated.rest.core.ApiClientException; -import com.skyflow.generated.rest.core.ApiClientHttpResponse; -import com.skyflow.generated.rest.core.ClientOptions; -import com.skyflow.generated.rest.core.MediaTypes; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.core.QueryStringMapper; -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.errors.NotFoundError; -import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectStatusRequest; -import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectTextRequest; -import com.skyflow.generated.rest.resources.deprecated.requests.V1DetectFileRequest; -import com.skyflow.generated.rest.types.V1DetectFileResponse; -import com.skyflow.generated.rest.types.V1DetectStatusResponse; -import com.skyflow.generated.rest.types.V1DetectTextResponse; -import java.io.IOException; -import java.util.concurrent.CompletableFuture; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; - -public class AsyncRawDeprecatedClient { - protected final ClientOptions clientOptions; - - public AsyncRawDeprecatedClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. - */ - public CompletableFuture> detectServiceDetectFileInput( - V1DetectFileRequest request) { - return detectServiceDetectFileInput(request, null); - } - - /** - * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. - */ - public CompletableFuture> detectServiceDetectFileInput( - V1DetectFileRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/file") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetectFileResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. - */ - public CompletableFuture> detectServiceDetectStatus(String id) { - return detectServiceDetectStatus( - id, DetectServiceDetectStatusRequest.builder().build()); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. - */ - public CompletableFuture> detectServiceDetectStatus( - String id, DetectServiceDetectStatusRequest request) { - return detectServiceDetectStatus(id, request, null); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. - */ - public CompletableFuture> detectServiceDetectStatus( - String id, DetectServiceDetectStatusRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/status") - .addPathSegment(id); - if (request.getVaultId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "vault_id", request.getVaultId().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue( - responseBody.string(), V1DetectStatusResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. - */ - public CompletableFuture> detectServiceDetectText( - DetectServiceDetectTextRequest request) { - return detectServiceDetectText(request, null); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. - */ - public CompletableFuture> detectServiceDetectText( - DetectServiceDetectTextRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/text") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - CompletableFuture> future = new CompletableFuture<>(); - client.newCall(okhttpRequest).enqueue(new Callback() { - @Override - public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { - try (ResponseBody responseBody = response.body()) { - if (response.isSuccessful()) { - future.complete(new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetectTextResponse.class), - response)); - return; - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - future.completeExceptionally(new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); - return; - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - future.completeExceptionally(new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response)); - return; - } catch (IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - } - - @Override - public void onFailure(@NotNull Call call, @NotNull IOException e) { - future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); - } - }); - return future; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/DeprecatedClient.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/DeprecatedClient.java deleted file mode 100644 index 820a349b..00000000 --- a/src/main/java/com/skyflow/generated/rest/resources/deprecated/DeprecatedClient.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.deprecated; - -import com.skyflow.generated.rest.core.ClientOptions; -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectStatusRequest; -import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectTextRequest; -import com.skyflow.generated.rest.resources.deprecated.requests.V1DetectFileRequest; -import com.skyflow.generated.rest.types.V1DetectFileResponse; -import com.skyflow.generated.rest.types.V1DetectStatusResponse; -import com.skyflow.generated.rest.types.V1DetectTextResponse; - -public class DeprecatedClient { - protected final ClientOptions clientOptions; - - private final RawDeprecatedClient rawClient; - - public DeprecatedClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - this.rawClient = new RawDeprecatedClient(clientOptions); - } - - /** - * Get responses with HTTP metadata like headers - */ - public RawDeprecatedClient withRawResponse() { - return this.rawClient; - } - - /** - * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. - */ - public V1DetectFileResponse detectServiceDetectFileInput(V1DetectFileRequest request) { - return this.rawClient.detectServiceDetectFileInput(request).body(); - } - - /** - * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. - */ - public V1DetectFileResponse detectServiceDetectFileInput( - V1DetectFileRequest request, RequestOptions requestOptions) { - return this.rawClient - .detectServiceDetectFileInput(request, requestOptions) - .body(); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. - */ - public V1DetectStatusResponse detectServiceDetectStatus(String id) { - return this.rawClient.detectServiceDetectStatus(id).body(); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. - */ - public V1DetectStatusResponse detectServiceDetectStatus(String id, DetectServiceDetectStatusRequest request) { - return this.rawClient.detectServiceDetectStatus(id, request).body(); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. - */ - public V1DetectStatusResponse detectServiceDetectStatus( - String id, DetectServiceDetectStatusRequest request, RequestOptions requestOptions) { - return this.rawClient - .detectServiceDetectStatus(id, request, requestOptions) - .body(); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. - */ - public V1DetectTextResponse detectServiceDetectText(DetectServiceDetectTextRequest request) { - return this.rawClient.detectServiceDetectText(request).body(); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. - */ - public V1DetectTextResponse detectServiceDetectText( - DetectServiceDetectTextRequest request, RequestOptions requestOptions) { - return this.rawClient.detectServiceDetectText(request, requestOptions).body(); - } -} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/RawDeprecatedClient.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/RawDeprecatedClient.java deleted file mode 100644 index 4472487f..00000000 --- a/src/main/java/com/skyflow/generated/rest/resources/deprecated/RawDeprecatedClient.java +++ /dev/null @@ -1,222 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.deprecated; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.skyflow.generated.rest.core.ApiClientApiException; -import com.skyflow.generated.rest.core.ApiClientException; -import com.skyflow.generated.rest.core.ApiClientHttpResponse; -import com.skyflow.generated.rest.core.ClientOptions; -import com.skyflow.generated.rest.core.MediaTypes; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.core.QueryStringMapper; -import com.skyflow.generated.rest.core.RequestOptions; -import com.skyflow.generated.rest.errors.NotFoundError; -import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectStatusRequest; -import com.skyflow.generated.rest.resources.deprecated.requests.DetectServiceDetectTextRequest; -import com.skyflow.generated.rest.resources.deprecated.requests.V1DetectFileRequest; -import com.skyflow.generated.rest.types.V1DetectFileResponse; -import com.skyflow.generated.rest.types.V1DetectStatusResponse; -import com.skyflow.generated.rest.types.V1DetectTextResponse; -import java.io.IOException; -import okhttp3.Headers; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; - -public class RawDeprecatedClient { - protected final ClientOptions clientOptions; - - public RawDeprecatedClient(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - } - - /** - * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. - */ - public ApiClientHttpResponse detectServiceDetectFileInput(V1DetectFileRequest request) { - return detectServiceDetectFileInput(request, null); - } - - /** - * <b>Note</b>: This operation is deprecated. Use one of the <a href=#De-identify%20File>De-identify File</a> operations.<br/><br/>Detects and deidentifies sensitive data from image, audio, and video files. - */ - public ApiClientHttpResponse detectServiceDetectFileInput( - V1DetectFileRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/file") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetectFileResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. - */ - public ApiClientHttpResponse detectServiceDetectStatus(String id) { - return detectServiceDetectStatus( - id, DetectServiceDetectStatusRequest.builder().build()); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. - */ - public ApiClientHttpResponse detectServiceDetectStatus( - String id, DetectServiceDetectStatusRequest request) { - return detectServiceDetectStatus(id, request, null); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#get_detect_run>Get Detect Run</a>.<br/><br/>Returns the status of a file deidentification request. - */ - public ApiClientHttpResponse detectServiceDetectStatus( - String id, DetectServiceDetectStatusRequest request, RequestOptions requestOptions) { - HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/status") - .addPathSegment(id); - if (request.getVaultId().isPresent()) { - QueryStringMapper.addQueryParameter( - httpUrl, "vault_id", request.getVaultId().get(), false); - } - Request.Builder _requestBuilder = new Request.Builder() - .url(httpUrl.build()) - .method("GET", null) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Accept", "application/json"); - Request okhttpRequest = _requestBuilder.build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetectStatusResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. - */ - public ApiClientHttpResponse detectServiceDetectText(DetectServiceDetectTextRequest request) { - return detectServiceDetectText(request, null); - } - - /** - * <b>Note</b>: This operation is deprecated. Use <a href=#deidentify_string>De-identify String</a>.<br/><br/>Detects and deidentifies sensitive data from text. - */ - public ApiClientHttpResponse detectServiceDetectText( - DetectServiceDetectTextRequest request, RequestOptions requestOptions) { - HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) - .newBuilder() - .addPathSegments("v1/detect/text") - .build(); - RequestBody body; - try { - body = RequestBody.create( - ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); - } catch (JsonProcessingException e) { - throw new ApiClientException("Failed to serialize request", e); - } - Request okhttpRequest = new Request.Builder() - .url(httpUrl) - .method("POST", body) - .headers(Headers.of(clientOptions.headers(requestOptions))) - .addHeader("Content-Type", "application/json") - .addHeader("Accept", "application/json") - .build(); - OkHttpClient client = clientOptions.httpClient(); - if (requestOptions != null && requestOptions.getTimeout().isPresent()) { - client = clientOptions.httpClientWithTimeout(requestOptions); - } - try (Response response = client.newCall(okhttpRequest).execute()) { - ResponseBody responseBody = response.body(); - if (response.isSuccessful()) { - return new ApiClientHttpResponse<>( - ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1DetectTextResponse.class), - response); - } - String responseBodyString = responseBody != null ? responseBody.string() : "{}"; - try { - if (response.code() == 404) { - throw new NotFoundError( - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); - } - } catch (JsonProcessingException ignored) { - // unable to map error response, throwing generic error - } - throw new ApiClientApiException( - "Error with status code " + response.code(), - response.code(), - ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), - response); - } catch (IOException e) { - throw new ApiClientException("Network error executing HTTP request", e); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectStatusRequest.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectStatusRequest.java deleted file mode 100644 index 45997db3..00000000 --- a/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectStatusRequest.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.deprecated.requests; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DetectServiceDetectStatusRequest.Builder.class) -public final class DetectServiceDetectStatusRequest { - private final Optional vaultId; - - private final Map additionalProperties; - - private DetectServiceDetectStatusRequest(Optional vaultId, Map additionalProperties) { - this.vaultId = vaultId; - this.additionalProperties = additionalProperties; - } - - /** - * @return ID of the vault. - */ - @JsonProperty("vault_id") - public Optional getVaultId() { - return vaultId; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DetectServiceDetectStatusRequest && equalTo((DetectServiceDetectStatusRequest) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DetectServiceDetectStatusRequest other) { - return vaultId.equals(other.vaultId); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.vaultId); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional vaultId = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(DetectServiceDetectStatusRequest other) { - vaultId(other.getVaultId()); - return this; - } - - /** - *

ID of the vault.

- */ - @JsonSetter(value = "vault_id", nulls = Nulls.SKIP) - public Builder vaultId(Optional vaultId) { - this.vaultId = vaultId; - return this; - } - - public Builder vaultId(String vaultId) { - this.vaultId = Optional.ofNullable(vaultId); - return this; - } - - public DetectServiceDetectStatusRequest build() { - return new DetectServiceDetectStatusRequest(vaultId, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectTextRequest.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectTextRequest.java deleted file mode 100644 index 3c4b4ea2..00000000 --- a/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/DetectServiceDetectTextRequest.java +++ /dev/null @@ -1,526 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.deprecated.requests; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.types.DetectDataAccuracy; -import com.skyflow.generated.rest.types.DetectDataEntities; -import com.skyflow.generated.rest.types.DetectRequestDeidentifyOption; -import com.skyflow.generated.rest.types.V1AdvancedOptions; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import org.jetbrains.annotations.NotNull; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = DetectServiceDetectTextRequest.Builder.class) -public final class DetectServiceDetectTextRequest { - private final String text; - - private final String vaultId; - - private final Optional sessionId; - - private final Optional> restrictEntityTypes; - - private final Optional deidentifyTokenFormat; - - private final Optional> allowRegex; - - private final Optional> restrictRegex; - - private final Optional returnEntities; - - private final Optional accuracy; - - private final Optional advancedOptions; - - private final Optional storeEntities; - - private final Map additionalProperties; - - private DetectServiceDetectTextRequest( - String text, - String vaultId, - Optional sessionId, - Optional> restrictEntityTypes, - Optional deidentifyTokenFormat, - Optional> allowRegex, - Optional> restrictRegex, - Optional returnEntities, - Optional accuracy, - Optional advancedOptions, - Optional storeEntities, - Map additionalProperties) { - this.text = text; - this.vaultId = vaultId; - this.sessionId = sessionId; - this.restrictEntityTypes = restrictEntityTypes; - this.deidentifyTokenFormat = deidentifyTokenFormat; - this.allowRegex = allowRegex; - this.restrictRegex = restrictRegex; - this.returnEntities = returnEntities; - this.accuracy = accuracy; - this.advancedOptions = advancedOptions; - this.storeEntities = storeEntities; - this.additionalProperties = additionalProperties; - } - - /** - * @return Data to deidentify. - */ - @JsonProperty("text") - public String getText() { - return text; - } - - /** - * @return ID of the vault. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - /** - * @return Will give a handle to delete the tokens generated during a specific interaction. - */ - @JsonProperty("session_id") - public Optional getSessionId() { - return sessionId; - } - - /** - * @return Entities to detect and deidentify. - */ - @JsonProperty("restrict_entity_types") - public Optional> getRestrictEntityTypes() { - return restrictEntityTypes; - } - - @JsonProperty("deidentify_token_format") - public Optional getDeidentifyTokenFormat() { - return deidentifyTokenFormat; - } - - /** - * @return Regular expressions to ignore when detecting entities. - */ - @JsonProperty("allow_regex") - public Optional> getAllowRegex() { - return allowRegex; - } - - /** - * @return Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'. - */ - @JsonProperty("restrict_regex") - public Optional> getRestrictRegex() { - return restrictRegex; - } - - /** - * @return If true, returns the details for the detected entities. - */ - @JsonProperty("return_entities") - public Optional getReturnEntities() { - return returnEntities; - } - - @JsonProperty("accuracy") - public Optional getAccuracy() { - return accuracy; - } - - @JsonProperty("advanced_options") - public Optional getAdvancedOptions() { - return advancedOptions; - } - - /** - * @return Indicates whether entities should be stored in the vault. - */ - @JsonProperty("store_entities") - public Optional getStoreEntities() { - return storeEntities; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof DetectServiceDetectTextRequest && equalTo((DetectServiceDetectTextRequest) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(DetectServiceDetectTextRequest other) { - return text.equals(other.text) - && vaultId.equals(other.vaultId) - && sessionId.equals(other.sessionId) - && restrictEntityTypes.equals(other.restrictEntityTypes) - && deidentifyTokenFormat.equals(other.deidentifyTokenFormat) - && allowRegex.equals(other.allowRegex) - && restrictRegex.equals(other.restrictRegex) - && returnEntities.equals(other.returnEntities) - && accuracy.equals(other.accuracy) - && advancedOptions.equals(other.advancedOptions) - && storeEntities.equals(other.storeEntities); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash( - this.text, - this.vaultId, - this.sessionId, - this.restrictEntityTypes, - this.deidentifyTokenFormat, - this.allowRegex, - this.restrictRegex, - this.returnEntities, - this.accuracy, - this.advancedOptions, - this.storeEntities); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static TextStage builder() { - return new Builder(); - } - - public interface TextStage { - /** - * Data to deidentify. - */ - VaultIdStage text(@NotNull String text); - - Builder from(DetectServiceDetectTextRequest other); - } - - public interface VaultIdStage { - /** - * ID of the vault. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - DetectServiceDetectTextRequest build(); - - /** - *

Will give a handle to delete the tokens generated during a specific interaction.

- */ - _FinalStage sessionId(Optional sessionId); - - _FinalStage sessionId(String sessionId); - - /** - *

Entities to detect and deidentify.

- */ - _FinalStage restrictEntityTypes(Optional> restrictEntityTypes); - - _FinalStage restrictEntityTypes(List restrictEntityTypes); - - _FinalStage deidentifyTokenFormat(Optional deidentifyTokenFormat); - - _FinalStage deidentifyTokenFormat(DetectRequestDeidentifyOption deidentifyTokenFormat); - - /** - *

Regular expressions to ignore when detecting entities.

- */ - _FinalStage allowRegex(Optional> allowRegex); - - _FinalStage allowRegex(List allowRegex); - - /** - *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

- */ - _FinalStage restrictRegex(Optional> restrictRegex); - - _FinalStage restrictRegex(List restrictRegex); - - /** - *

If true, returns the details for the detected entities.

- */ - _FinalStage returnEntities(Optional returnEntities); - - _FinalStage returnEntities(Boolean returnEntities); - - _FinalStage accuracy(Optional accuracy); - - _FinalStage accuracy(DetectDataAccuracy accuracy); - - _FinalStage advancedOptions(Optional advancedOptions); - - _FinalStage advancedOptions(V1AdvancedOptions advancedOptions); - - /** - *

Indicates whether entities should be stored in the vault.

- */ - _FinalStage storeEntities(Optional storeEntities); - - _FinalStage storeEntities(Boolean storeEntities); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements TextStage, VaultIdStage, _FinalStage { - private String text; - - private String vaultId; - - private Optional storeEntities = Optional.empty(); - - private Optional advancedOptions = Optional.empty(); - - private Optional accuracy = Optional.empty(); - - private Optional returnEntities = Optional.empty(); - - private Optional> restrictRegex = Optional.empty(); - - private Optional> allowRegex = Optional.empty(); - - private Optional deidentifyTokenFormat = Optional.empty(); - - private Optional> restrictEntityTypes = Optional.empty(); - - private Optional sessionId = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @java.lang.Override - public Builder from(DetectServiceDetectTextRequest other) { - text(other.getText()); - vaultId(other.getVaultId()); - sessionId(other.getSessionId()); - restrictEntityTypes(other.getRestrictEntityTypes()); - deidentifyTokenFormat(other.getDeidentifyTokenFormat()); - allowRegex(other.getAllowRegex()); - restrictRegex(other.getRestrictRegex()); - returnEntities(other.getReturnEntities()); - accuracy(other.getAccuracy()); - advancedOptions(other.getAdvancedOptions()); - storeEntities(other.getStoreEntities()); - return this; - } - - /** - * Data to deidentify.

Data to deidentify.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - @JsonSetter("text") - public VaultIdStage text(@NotNull String text) { - this.text = Objects.requireNonNull(text, "text must not be null"); - return this; - } - - /** - * ID of the vault.

ID of the vault.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - @JsonSetter("vault_id") - public _FinalStage vaultId(@NotNull String vaultId) { - this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); - return this; - } - - /** - *

Indicates whether entities should be stored in the vault.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage storeEntities(Boolean storeEntities) { - this.storeEntities = Optional.ofNullable(storeEntities); - return this; - } - - /** - *

Indicates whether entities should be stored in the vault.

- */ - @java.lang.Override - @JsonSetter(value = "store_entities", nulls = Nulls.SKIP) - public _FinalStage storeEntities(Optional storeEntities) { - this.storeEntities = storeEntities; - return this; - } - - @java.lang.Override - public _FinalStage advancedOptions(V1AdvancedOptions advancedOptions) { - this.advancedOptions = Optional.ofNullable(advancedOptions); - return this; - } - - @java.lang.Override - @JsonSetter(value = "advanced_options", nulls = Nulls.SKIP) - public _FinalStage advancedOptions(Optional advancedOptions) { - this.advancedOptions = advancedOptions; - return this; - } - - @java.lang.Override - public _FinalStage accuracy(DetectDataAccuracy accuracy) { - this.accuracy = Optional.ofNullable(accuracy); - return this; - } - - @java.lang.Override - @JsonSetter(value = "accuracy", nulls = Nulls.SKIP) - public _FinalStage accuracy(Optional accuracy) { - this.accuracy = accuracy; - return this; - } - - /** - *

If true, returns the details for the detected entities.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage returnEntities(Boolean returnEntities) { - this.returnEntities = Optional.ofNullable(returnEntities); - return this; - } - - /** - *

If true, returns the details for the detected entities.

- */ - @java.lang.Override - @JsonSetter(value = "return_entities", nulls = Nulls.SKIP) - public _FinalStage returnEntities(Optional returnEntities) { - this.returnEntities = returnEntities; - return this; - } - - /** - *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage restrictRegex(List restrictRegex) { - this.restrictRegex = Optional.ofNullable(restrictRegex); - return this; - } - - /** - *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

- */ - @java.lang.Override - @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) - public _FinalStage restrictRegex(Optional> restrictRegex) { - this.restrictRegex = restrictRegex; - return this; - } - - /** - *

Regular expressions to ignore when detecting entities.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage allowRegex(List allowRegex) { - this.allowRegex = Optional.ofNullable(allowRegex); - return this; - } - - /** - *

Regular expressions to ignore when detecting entities.

- */ - @java.lang.Override - @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) - public _FinalStage allowRegex(Optional> allowRegex) { - this.allowRegex = allowRegex; - return this; - } - - @java.lang.Override - public _FinalStage deidentifyTokenFormat(DetectRequestDeidentifyOption deidentifyTokenFormat) { - this.deidentifyTokenFormat = Optional.ofNullable(deidentifyTokenFormat); - return this; - } - - @java.lang.Override - @JsonSetter(value = "deidentify_token_format", nulls = Nulls.SKIP) - public _FinalStage deidentifyTokenFormat(Optional deidentifyTokenFormat) { - this.deidentifyTokenFormat = deidentifyTokenFormat; - return this; - } - - /** - *

Entities to detect and deidentify.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage restrictEntityTypes(List restrictEntityTypes) { - this.restrictEntityTypes = Optional.ofNullable(restrictEntityTypes); - return this; - } - - /** - *

Entities to detect and deidentify.

- */ - @java.lang.Override - @JsonSetter(value = "restrict_entity_types", nulls = Nulls.SKIP) - public _FinalStage restrictEntityTypes(Optional> restrictEntityTypes) { - this.restrictEntityTypes = restrictEntityTypes; - return this; - } - - /** - *

Will give a handle to delete the tokens generated during a specific interaction.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage sessionId(String sessionId) { - this.sessionId = Optional.ofNullable(sessionId); - return this; - } - - /** - *

Will give a handle to delete the tokens generated during a specific interaction.

- */ - @java.lang.Override - @JsonSetter(value = "session_id", nulls = Nulls.SKIP) - public _FinalStage sessionId(Optional sessionId) { - this.sessionId = sessionId; - return this; - } - - @java.lang.Override - public DetectServiceDetectTextRequest build() { - return new DetectServiceDetectTextRequest( - text, - vaultId, - sessionId, - restrictEntityTypes, - deidentifyTokenFormat, - allowRegex, - restrictRegex, - returnEntities, - accuracy, - advancedOptions, - storeEntities, - additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/V1DetectFileRequest.java b/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/V1DetectFileRequest.java deleted file mode 100644 index 8bdee935..00000000 --- a/src/main/java/com/skyflow/generated/rest/resources/deprecated/requests/V1DetectFileRequest.java +++ /dev/null @@ -1,634 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.resources.deprecated.requests; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import com.skyflow.generated.rest.types.DetectDataAccuracy; -import com.skyflow.generated.rest.types.DetectDataEntities; -import com.skyflow.generated.rest.types.DetectFileRequestDataType; -import com.skyflow.generated.rest.types.DetectRequestDeidentifyOption; -import com.skyflow.generated.rest.types.V1AdvancedOptions; -import com.skyflow.generated.rest.types.V1AudioConfig; -import com.skyflow.generated.rest.types.V1FileDataFormat; -import com.skyflow.generated.rest.types.V1ImageOptions; -import com.skyflow.generated.rest.types.V1PdfConfig; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import org.jetbrains.annotations.NotNull; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1DetectFileRequest.Builder.class) -public final class V1DetectFileRequest { - private final String file; - - private final V1FileDataFormat dataFormat; - - private final DetectFileRequestDataType inputType; - - private final String vaultId; - - private final Optional sessionId; - - private final Optional> restrictEntityTypes; - - private final Optional> allowRegex; - - private final Optional> restrictRegex; - - private final Optional returnEntities; - - private final Optional accuracy; - - private final Optional audio; - - private final Optional image; - - private final Optional pdf; - - private final Optional advancedOptions; - - private final Optional deidentifyTokenFormat; - - private final Map additionalProperties; - - private V1DetectFileRequest( - String file, - V1FileDataFormat dataFormat, - DetectFileRequestDataType inputType, - String vaultId, - Optional sessionId, - Optional> restrictEntityTypes, - Optional> allowRegex, - Optional> restrictRegex, - Optional returnEntities, - Optional accuracy, - Optional audio, - Optional image, - Optional pdf, - Optional advancedOptions, - Optional deidentifyTokenFormat, - Map additionalProperties) { - this.file = file; - this.dataFormat = dataFormat; - this.inputType = inputType; - this.vaultId = vaultId; - this.sessionId = sessionId; - this.restrictEntityTypes = restrictEntityTypes; - this.allowRegex = allowRegex; - this.restrictRegex = restrictRegex; - this.returnEntities = returnEntities; - this.accuracy = accuracy; - this.audio = audio; - this.image = image; - this.pdf = pdf; - this.advancedOptions = advancedOptions; - this.deidentifyTokenFormat = deidentifyTokenFormat; - this.additionalProperties = additionalProperties; - } - - /** - * @return Path of the file or base64-encoded data that has to be processed. - */ - @JsonProperty("file") - public String getFile() { - return file; - } - - @JsonProperty("data_format") - public V1FileDataFormat getDataFormat() { - return dataFormat; - } - - @JsonProperty("input_type") - public DetectFileRequestDataType getInputType() { - return inputType; - } - - /** - * @return ID of the vault. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - /** - * @return Will give a handle to delete the tokens generated during a specific interaction. - */ - @JsonProperty("session_id") - public Optional getSessionId() { - return sessionId; - } - - /** - * @return Entities to detect and deidentify. - */ - @JsonProperty("restrict_entity_types") - public Optional> getRestrictEntityTypes() { - return restrictEntityTypes; - } - - /** - * @return Regular expressions to ignore when detecting entities. - */ - @JsonProperty("allow_regex") - public Optional> getAllowRegex() { - return allowRegex; - } - - /** - * @return Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'. - */ - @JsonProperty("restrict_regex") - public Optional> getRestrictRegex() { - return restrictRegex; - } - - /** - * @return If true, returns the details for the detected entities. - */ - @JsonProperty("return_entities") - public Optional getReturnEntities() { - return returnEntities; - } - - @JsonProperty("accuracy") - public Optional getAccuracy() { - return accuracy; - } - - @JsonProperty("audio") - public Optional getAudio() { - return audio; - } - - @JsonProperty("image") - public Optional getImage() { - return image; - } - - @JsonProperty("pdf") - public Optional getPdf() { - return pdf; - } - - @JsonProperty("advanced_options") - public Optional getAdvancedOptions() { - return advancedOptions; - } - - @JsonProperty("deidentify_token_format") - public Optional getDeidentifyTokenFormat() { - return deidentifyTokenFormat; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1DetectFileRequest && equalTo((V1DetectFileRequest) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1DetectFileRequest other) { - return file.equals(other.file) - && dataFormat.equals(other.dataFormat) - && inputType.equals(other.inputType) - && vaultId.equals(other.vaultId) - && sessionId.equals(other.sessionId) - && restrictEntityTypes.equals(other.restrictEntityTypes) - && allowRegex.equals(other.allowRegex) - && restrictRegex.equals(other.restrictRegex) - && returnEntities.equals(other.returnEntities) - && accuracy.equals(other.accuracy) - && audio.equals(other.audio) - && image.equals(other.image) - && pdf.equals(other.pdf) - && advancedOptions.equals(other.advancedOptions) - && deidentifyTokenFormat.equals(other.deidentifyTokenFormat); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash( - this.file, - this.dataFormat, - this.inputType, - this.vaultId, - this.sessionId, - this.restrictEntityTypes, - this.allowRegex, - this.restrictRegex, - this.returnEntities, - this.accuracy, - this.audio, - this.image, - this.pdf, - this.advancedOptions, - this.deidentifyTokenFormat); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static FileStage builder() { - return new Builder(); - } - - public interface FileStage { - /** - * Path of the file or base64-encoded data that has to be processed. - */ - DataFormatStage file(@NotNull String file); - - Builder from(V1DetectFileRequest other); - } - - public interface DataFormatStage { - InputTypeStage dataFormat(@NotNull V1FileDataFormat dataFormat); - } - - public interface InputTypeStage { - VaultIdStage inputType(@NotNull DetectFileRequestDataType inputType); - } - - public interface VaultIdStage { - /** - * ID of the vault. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - V1DetectFileRequest build(); - - /** - *

Will give a handle to delete the tokens generated during a specific interaction.

- */ - _FinalStage sessionId(Optional sessionId); - - _FinalStage sessionId(String sessionId); - - /** - *

Entities to detect and deidentify.

- */ - _FinalStage restrictEntityTypes(Optional> restrictEntityTypes); - - _FinalStage restrictEntityTypes(List restrictEntityTypes); - - /** - *

Regular expressions to ignore when detecting entities.

- */ - _FinalStage allowRegex(Optional> allowRegex); - - _FinalStage allowRegex(List allowRegex); - - /** - *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

- */ - _FinalStage restrictRegex(Optional> restrictRegex); - - _FinalStage restrictRegex(List restrictRegex); - - /** - *

If true, returns the details for the detected entities.

- */ - _FinalStage returnEntities(Optional returnEntities); - - _FinalStage returnEntities(Boolean returnEntities); - - _FinalStage accuracy(Optional accuracy); - - _FinalStage accuracy(DetectDataAccuracy accuracy); - - _FinalStage audio(Optional audio); - - _FinalStage audio(V1AudioConfig audio); - - _FinalStage image(Optional image); - - _FinalStage image(V1ImageOptions image); - - _FinalStage pdf(Optional pdf); - - _FinalStage pdf(V1PdfConfig pdf); - - _FinalStage advancedOptions(Optional advancedOptions); - - _FinalStage advancedOptions(V1AdvancedOptions advancedOptions); - - _FinalStage deidentifyTokenFormat(Optional deidentifyTokenFormat); - - _FinalStage deidentifyTokenFormat(DetectRequestDeidentifyOption deidentifyTokenFormat); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements FileStage, DataFormatStage, InputTypeStage, VaultIdStage, _FinalStage { - private String file; - - private V1FileDataFormat dataFormat; - - private DetectFileRequestDataType inputType; - - private String vaultId; - - private Optional deidentifyTokenFormat = Optional.empty(); - - private Optional advancedOptions = Optional.empty(); - - private Optional pdf = Optional.empty(); - - private Optional image = Optional.empty(); - - private Optional audio = Optional.empty(); - - private Optional accuracy = Optional.empty(); - - private Optional returnEntities = Optional.empty(); - - private Optional> restrictRegex = Optional.empty(); - - private Optional> allowRegex = Optional.empty(); - - private Optional> restrictEntityTypes = Optional.empty(); - - private Optional sessionId = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @java.lang.Override - public Builder from(V1DetectFileRequest other) { - file(other.getFile()); - dataFormat(other.getDataFormat()); - inputType(other.getInputType()); - vaultId(other.getVaultId()); - sessionId(other.getSessionId()); - restrictEntityTypes(other.getRestrictEntityTypes()); - allowRegex(other.getAllowRegex()); - restrictRegex(other.getRestrictRegex()); - returnEntities(other.getReturnEntities()); - accuracy(other.getAccuracy()); - audio(other.getAudio()); - image(other.getImage()); - pdf(other.getPdf()); - advancedOptions(other.getAdvancedOptions()); - deidentifyTokenFormat(other.getDeidentifyTokenFormat()); - return this; - } - - /** - * Path of the file or base64-encoded data that has to be processed.

Path of the file or base64-encoded data that has to be processed.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - @JsonSetter("file") - public DataFormatStage file(@NotNull String file) { - this.file = Objects.requireNonNull(file, "file must not be null"); - return this; - } - - @java.lang.Override - @JsonSetter("data_format") - public InputTypeStage dataFormat(@NotNull V1FileDataFormat dataFormat) { - this.dataFormat = Objects.requireNonNull(dataFormat, "dataFormat must not be null"); - return this; - } - - @java.lang.Override - @JsonSetter("input_type") - public VaultIdStage inputType(@NotNull DetectFileRequestDataType inputType) { - this.inputType = Objects.requireNonNull(inputType, "inputType must not be null"); - return this; - } - - /** - * ID of the vault.

ID of the vault.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - @JsonSetter("vault_id") - public _FinalStage vaultId(@NotNull String vaultId) { - this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); - return this; - } - - @java.lang.Override - public _FinalStage deidentifyTokenFormat(DetectRequestDeidentifyOption deidentifyTokenFormat) { - this.deidentifyTokenFormat = Optional.ofNullable(deidentifyTokenFormat); - return this; - } - - @java.lang.Override - @JsonSetter(value = "deidentify_token_format", nulls = Nulls.SKIP) - public _FinalStage deidentifyTokenFormat(Optional deidentifyTokenFormat) { - this.deidentifyTokenFormat = deidentifyTokenFormat; - return this; - } - - @java.lang.Override - public _FinalStage advancedOptions(V1AdvancedOptions advancedOptions) { - this.advancedOptions = Optional.ofNullable(advancedOptions); - return this; - } - - @java.lang.Override - @JsonSetter(value = "advanced_options", nulls = Nulls.SKIP) - public _FinalStage advancedOptions(Optional advancedOptions) { - this.advancedOptions = advancedOptions; - return this; - } - - @java.lang.Override - public _FinalStage pdf(V1PdfConfig pdf) { - this.pdf = Optional.ofNullable(pdf); - return this; - } - - @java.lang.Override - @JsonSetter(value = "pdf", nulls = Nulls.SKIP) - public _FinalStage pdf(Optional pdf) { - this.pdf = pdf; - return this; - } - - @java.lang.Override - public _FinalStage image(V1ImageOptions image) { - this.image = Optional.ofNullable(image); - return this; - } - - @java.lang.Override - @JsonSetter(value = "image", nulls = Nulls.SKIP) - public _FinalStage image(Optional image) { - this.image = image; - return this; - } - - @java.lang.Override - public _FinalStage audio(V1AudioConfig audio) { - this.audio = Optional.ofNullable(audio); - return this; - } - - @java.lang.Override - @JsonSetter(value = "audio", nulls = Nulls.SKIP) - public _FinalStage audio(Optional audio) { - this.audio = audio; - return this; - } - - @java.lang.Override - public _FinalStage accuracy(DetectDataAccuracy accuracy) { - this.accuracy = Optional.ofNullable(accuracy); - return this; - } - - @java.lang.Override - @JsonSetter(value = "accuracy", nulls = Nulls.SKIP) - public _FinalStage accuracy(Optional accuracy) { - this.accuracy = accuracy; - return this; - } - - /** - *

If true, returns the details for the detected entities.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage returnEntities(Boolean returnEntities) { - this.returnEntities = Optional.ofNullable(returnEntities); - return this; - } - - /** - *

If true, returns the details for the detected entities.

- */ - @java.lang.Override - @JsonSetter(value = "return_entities", nulls = Nulls.SKIP) - public _FinalStage returnEntities(Optional returnEntities) { - this.returnEntities = returnEntities; - return this; - } - - /** - *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage restrictRegex(List restrictRegex) { - this.restrictRegex = Optional.ofNullable(restrictRegex); - return this; - } - - /** - *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

- */ - @java.lang.Override - @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) - public _FinalStage restrictRegex(Optional> restrictRegex) { - this.restrictRegex = restrictRegex; - return this; - } - - /** - *

Regular expressions to ignore when detecting entities.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage allowRegex(List allowRegex) { - this.allowRegex = Optional.ofNullable(allowRegex); - return this; - } - - /** - *

Regular expressions to ignore when detecting entities.

- */ - @java.lang.Override - @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) - public _FinalStage allowRegex(Optional> allowRegex) { - this.allowRegex = allowRegex; - return this; - } - - /** - *

Entities to detect and deidentify.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage restrictEntityTypes(List restrictEntityTypes) { - this.restrictEntityTypes = Optional.ofNullable(restrictEntityTypes); - return this; - } - - /** - *

Entities to detect and deidentify.

- */ - @java.lang.Override - @JsonSetter(value = "restrict_entity_types", nulls = Nulls.SKIP) - public _FinalStage restrictEntityTypes(Optional> restrictEntityTypes) { - this.restrictEntityTypes = restrictEntityTypes; - return this; - } - - /** - *

Will give a handle to delete the tokens generated during a specific interaction.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage sessionId(String sessionId) { - this.sessionId = Optional.ofNullable(sessionId); - return this; - } - - /** - *

Will give a handle to delete the tokens generated during a specific interaction.

- */ - @java.lang.Override - @JsonSetter(value = "session_id", nulls = Nulls.SKIP) - public _FinalStage sessionId(Optional sessionId) { - this.sessionId = sessionId; - return this; - } - - @java.lang.Override - public V1DetectFileRequest build() { - return new V1DetectFileRequest( - file, - dataFormat, - inputType, - vaultId, - sessionId, - restrictEntityTypes, - allowRegex, - restrictRegex, - returnEntities, - accuracy, - audio, - image, - pdf, - advancedOptions, - deidentifyTokenFormat, - additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/AsyncFilesClient.java b/src/main/java/com/skyflow/generated/rest/resources/files/AsyncFilesClient.java index 48692d9f..782d2d2b 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/AsyncFilesClient.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/AsyncFilesClient.java @@ -15,8 +15,10 @@ import com.skyflow.generated.rest.resources.files.requests.DeidentifyStructuredTextRequest; import com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest; import com.skyflow.generated.rest.resources.files.requests.GetRunRequest; +import com.skyflow.generated.rest.resources.files.requests.ReidentifyFileRequest; import com.skyflow.generated.rest.types.DeidentifyFileResponse; import com.skyflow.generated.rest.types.DeidentifyStatusResponse; +import com.skyflow.generated.rest.types.ReidentifyFileResponse; import java.util.concurrent.CompletableFuture; public class AsyncFilesClient { @@ -185,4 +187,19 @@ public CompletableFuture getRun( String runId, GetRunRequest request, RequestOptions requestOptions) { return this.rawClient.getRun(runId, request, requestOptions).thenApply(response -> response.body()); } + + /** + * Re-identifies tokens in a file. + */ + public CompletableFuture reidentifyFile(ReidentifyFileRequest request) { + return this.rawClient.reidentifyFile(request).thenApply(response -> response.body()); + } + + /** + * Re-identifies tokens in a file. + */ + public CompletableFuture reidentifyFile( + ReidentifyFileRequest request, RequestOptions requestOptions) { + return this.rawClient.reidentifyFile(request, requestOptions).thenApply(response -> response.body()); + } } diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/AsyncRawFilesClient.java b/src/main/java/com/skyflow/generated/rest/resources/files/AsyncRawFilesClient.java index f400bb2a..4672288a 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/AsyncRawFilesClient.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/AsyncRawFilesClient.java @@ -26,9 +26,11 @@ import com.skyflow.generated.rest.resources.files.requests.DeidentifyStructuredTextRequest; import com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest; import com.skyflow.generated.rest.resources.files.requests.GetRunRequest; +import com.skyflow.generated.rest.resources.files.requests.ReidentifyFileRequest; import com.skyflow.generated.rest.types.DeidentifyFileResponse; import com.skyflow.generated.rest.types.DeidentifyStatusResponse; import com.skyflow.generated.rest.types.ErrorResponse; +import com.skyflow.generated.rest.types.ReidentifyFileResponse; import java.io.IOException; import java.util.concurrent.CompletableFuture; import okhttp3.Call; @@ -926,4 +928,92 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { }); return future; } + + /** + * Re-identifies tokens in a file. + */ + public CompletableFuture> reidentifyFile( + ReidentifyFileRequest request) { + return reidentifyFile(request, null); + } + + /** + * Re-identifies tokens in a file. + */ + public CompletableFuture> reidentifyFile( + ReidentifyFileRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/reidentify/file") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), ReidentifyFileResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } } diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/FilesClient.java b/src/main/java/com/skyflow/generated/rest/resources/files/FilesClient.java index 89898d41..5eee1560 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/FilesClient.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/FilesClient.java @@ -15,8 +15,10 @@ import com.skyflow.generated.rest.resources.files.requests.DeidentifyStructuredTextRequest; import com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest; import com.skyflow.generated.rest.resources.files.requests.GetRunRequest; +import com.skyflow.generated.rest.resources.files.requests.ReidentifyFileRequest; import com.skyflow.generated.rest.types.DeidentifyFileResponse; import com.skyflow.generated.rest.types.DeidentifyStatusResponse; +import com.skyflow.generated.rest.types.ReidentifyFileResponse; public class FilesClient { protected final ClientOptions clientOptions; @@ -177,4 +179,18 @@ public DeidentifyStatusResponse getRun(String runId, GetRunRequest request) { public DeidentifyStatusResponse getRun(String runId, GetRunRequest request, RequestOptions requestOptions) { return this.rawClient.getRun(runId, request, requestOptions).body(); } + + /** + * Re-identifies tokens in a file. + */ + public ReidentifyFileResponse reidentifyFile(ReidentifyFileRequest request) { + return this.rawClient.reidentifyFile(request).body(); + } + + /** + * Re-identifies tokens in a file. + */ + public ReidentifyFileResponse reidentifyFile(ReidentifyFileRequest request, RequestOptions requestOptions) { + return this.rawClient.reidentifyFile(request, requestOptions).body(); + } } diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/RawFilesClient.java b/src/main/java/com/skyflow/generated/rest/resources/files/RawFilesClient.java index 85939625..d0fb0bfc 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/RawFilesClient.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/RawFilesClient.java @@ -26,9 +26,11 @@ import com.skyflow.generated.rest.resources.files.requests.DeidentifyStructuredTextRequest; import com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest; import com.skyflow.generated.rest.resources.files.requests.GetRunRequest; +import com.skyflow.generated.rest.resources.files.requests.ReidentifyFileRequest; import com.skyflow.generated.rest.types.DeidentifyFileResponse; import com.skyflow.generated.rest.types.DeidentifyStatusResponse; import com.skyflow.generated.rest.types.ErrorResponse; +import com.skyflow.generated.rest.types.ReidentifyFileResponse; import java.io.IOException; import okhttp3.Headers; import okhttp3.HttpUrl; @@ -711,4 +713,71 @@ public ApiClientHttpResponse getRun( throw new ApiClientException("Network error executing HTTP request", e); } } + + /** + * Re-identifies tokens in a file. + */ + public ApiClientHttpResponse reidentifyFile(ReidentifyFileRequest request) { + return reidentifyFile(request, null); + } + + /** + * Re-identifies tokens in a file. + */ + public ApiClientHttpResponse reidentifyFile( + ReidentifyFileRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/reidentify/file") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), ReidentifyFileResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } } diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyAudioRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyAudioRequest.java index 5f4929aa..b9f02d97 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyAudioRequest.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyAudioRequest.java @@ -31,6 +31,8 @@ public final class DeidentifyAudioRequest { private final DeidentifyAudioRequestFile file; + private final Optional configurationId; + private final Optional outputProcessedAudio; private final Optional outputTranscription; @@ -58,6 +60,7 @@ public final class DeidentifyAudioRequest { private DeidentifyAudioRequest( String vaultId, DeidentifyAudioRequestFile file, + Optional configurationId, Optional outputProcessedAudio, Optional outputTranscription, Optional bleepGain, @@ -72,6 +75,7 @@ private DeidentifyAudioRequest( Map additionalProperties) { this.vaultId = vaultId; this.file = file; + this.configurationId = configurationId; this.outputProcessedAudio = outputProcessedAudio; this.outputTranscription = outputTranscription; this.bleepGain = bleepGain; @@ -99,6 +103,11 @@ public DeidentifyAudioRequestFile getFile() { return file; } + @JsonProperty("configuration_id") + public Optional getConfigurationId() { + return configurationId; + } + /** * @return If true, includes processed audio file in the response. */ @@ -186,6 +195,7 @@ public Map getAdditionalProperties() { private boolean equalTo(DeidentifyAudioRequest other) { return vaultId.equals(other.vaultId) && file.equals(other.file) + && configurationId.equals(other.configurationId) && outputProcessedAudio.equals(other.outputProcessedAudio) && outputTranscription.equals(other.outputTranscription) && bleepGain.equals(other.bleepGain) @@ -204,6 +214,7 @@ public int hashCode() { return Objects.hash( this.vaultId, this.file, + this.configurationId, this.outputProcessedAudio, this.outputTranscription, this.bleepGain, @@ -242,6 +253,10 @@ public interface FileStage { public interface _FinalStage { DeidentifyAudioRequest build(); + _FinalStage configurationId(Optional configurationId); + + _FinalStage configurationId(String configurationId); + /** *

If true, includes processed audio file in the response.

*/ @@ -333,6 +348,8 @@ public static final class Builder implements VaultIdStage, FileStage, _FinalStag private Optional outputProcessedAudio = Optional.empty(); + private Optional configurationId = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -342,6 +359,7 @@ private Builder() {} public Builder from(DeidentifyAudioRequest other) { vaultId(other.getVaultId()); file(other.getFile()); + configurationId(other.getConfigurationId()); outputProcessedAudio(other.getOutputProcessedAudio()); outputTranscription(other.getOutputTranscription()); bleepGain(other.getBleepGain()); @@ -560,11 +578,25 @@ public _FinalStage outputProcessedAudio(Optional outputProcessedAudio) return this; } + @java.lang.Override + public _FinalStage configurationId(String configurationId) { + this.configurationId = Optional.ofNullable(configurationId); + return this; + } + + @java.lang.Override + @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) + public _FinalStage configurationId(Optional configurationId) { + this.configurationId = configurationId; + return this; + } + @java.lang.Override public DeidentifyAudioRequest build() { return new DeidentifyAudioRequest( vaultId, file, + configurationId, outputProcessedAudio, outputTranscription, bleepGain, diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyDocumentRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyDocumentRequest.java index bf6f307e..dd2d1548 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyDocumentRequest.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyDocumentRequest.java @@ -30,6 +30,8 @@ public final class DeidentifyDocumentRequest { private final DeidentifyDocumentRequestFile file; + private final Optional configurationId; + private final Optional> entityTypes; private final Optional tokenType; @@ -45,6 +47,7 @@ public final class DeidentifyDocumentRequest { private DeidentifyDocumentRequest( String vaultId, DeidentifyDocumentRequestFile file, + Optional configurationId, Optional> entityTypes, Optional tokenType, Optional> allowRegex, @@ -53,6 +56,7 @@ private DeidentifyDocumentRequest( Map additionalProperties) { this.vaultId = vaultId; this.file = file; + this.configurationId = configurationId; this.entityTypes = entityTypes; this.tokenType = tokenType; this.allowRegex = allowRegex; @@ -74,6 +78,11 @@ public DeidentifyDocumentRequestFile getFile() { return file; } + @JsonProperty("configuration_id") + public Optional getConfigurationId() { + return configurationId; + } + @JsonProperty("entity_types") public Optional> getEntityTypes() { return entityTypes; @@ -113,6 +122,7 @@ public Map getAdditionalProperties() { private boolean equalTo(DeidentifyDocumentRequest other) { return vaultId.equals(other.vaultId) && file.equals(other.file) + && configurationId.equals(other.configurationId) && entityTypes.equals(other.entityTypes) && tokenType.equals(other.tokenType) && allowRegex.equals(other.allowRegex) @@ -125,6 +135,7 @@ public int hashCode() { return Objects.hash( this.vaultId, this.file, + this.configurationId, this.entityTypes, this.tokenType, this.allowRegex, @@ -157,6 +168,10 @@ public interface FileStage { public interface _FinalStage { DeidentifyDocumentRequest build(); + _FinalStage configurationId(Optional configurationId); + + _FinalStage configurationId(String configurationId); + _FinalStage entityTypes(Optional> entityTypes); _FinalStage entityTypes(List entityTypes); @@ -194,6 +209,8 @@ public static final class Builder implements VaultIdStage, FileStage, _FinalStag private Optional> entityTypes = Optional.empty(); + private Optional configurationId = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -203,6 +220,7 @@ private Builder() {} public Builder from(DeidentifyDocumentRequest other) { vaultId(other.getVaultId()); file(other.getFile()); + configurationId(other.getConfigurationId()); entityTypes(other.getEntityTypes()); tokenType(other.getTokenType()); allowRegex(other.getAllowRegex()); @@ -294,11 +312,25 @@ public _FinalStage entityTypes(Optional> entityTypes) { return this; } + @java.lang.Override + public _FinalStage configurationId(String configurationId) { + this.configurationId = Optional.ofNullable(configurationId); + return this; + } + + @java.lang.Override + @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) + public _FinalStage configurationId(Optional configurationId) { + this.configurationId = configurationId; + return this; + } + @java.lang.Override public DeidentifyDocumentRequest build() { return new DeidentifyDocumentRequest( vaultId, file, + configurationId, entityTypes, tokenType, allowRegex, diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequest.java index 1cbcd8f1..ae21845d 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequest.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyFileRequest.java @@ -30,6 +30,8 @@ public final class DeidentifyFileRequest { private final DeidentifyFileRequestFile file; + private final Optional configurationId; + private final Optional> entityTypes; private final Optional tokenType; @@ -45,6 +47,7 @@ public final class DeidentifyFileRequest { private DeidentifyFileRequest( String vaultId, DeidentifyFileRequestFile file, + Optional configurationId, Optional> entityTypes, Optional tokenType, Optional> allowRegex, @@ -53,6 +56,7 @@ private DeidentifyFileRequest( Map additionalProperties) { this.vaultId = vaultId; this.file = file; + this.configurationId = configurationId; this.entityTypes = entityTypes; this.tokenType = tokenType; this.allowRegex = allowRegex; @@ -74,6 +78,11 @@ public DeidentifyFileRequestFile getFile() { return file; } + @JsonProperty("configuration_id") + public Optional getConfigurationId() { + return configurationId; + } + @JsonProperty("entity_types") public Optional> getEntityTypes() { return entityTypes; @@ -113,6 +122,7 @@ public Map getAdditionalProperties() { private boolean equalTo(DeidentifyFileRequest other) { return vaultId.equals(other.vaultId) && file.equals(other.file) + && configurationId.equals(other.configurationId) && entityTypes.equals(other.entityTypes) && tokenType.equals(other.tokenType) && allowRegex.equals(other.allowRegex) @@ -125,6 +135,7 @@ public int hashCode() { return Objects.hash( this.vaultId, this.file, + this.configurationId, this.entityTypes, this.tokenType, this.allowRegex, @@ -157,6 +168,10 @@ public interface FileStage { public interface _FinalStage { DeidentifyFileRequest build(); + _FinalStage configurationId(Optional configurationId); + + _FinalStage configurationId(String configurationId); + _FinalStage entityTypes(Optional> entityTypes); _FinalStage entityTypes(List entityTypes); @@ -194,6 +209,8 @@ public static final class Builder implements VaultIdStage, FileStage, _FinalStag private Optional> entityTypes = Optional.empty(); + private Optional configurationId = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -203,6 +220,7 @@ private Builder() {} public Builder from(DeidentifyFileRequest other) { vaultId(other.getVaultId()); file(other.getFile()); + configurationId(other.getConfigurationId()); entityTypes(other.getEntityTypes()); tokenType(other.getTokenType()); allowRegex(other.getAllowRegex()); @@ -294,11 +312,25 @@ public _FinalStage entityTypes(Optional> entityTypes) { return this; } + @java.lang.Override + public _FinalStage configurationId(String configurationId) { + this.configurationId = Optional.ofNullable(configurationId); + return this; + } + + @java.lang.Override + @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) + public _FinalStage configurationId(Optional configurationId) { + this.configurationId = configurationId; + return this; + } + @java.lang.Override public DeidentifyFileRequest build() { return new DeidentifyFileRequest( vaultId, file, + configurationId, entityTypes, tokenType, allowRegex, diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyImageRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyImageRequest.java index 41de24b2..92445d02 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyImageRequest.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyImageRequest.java @@ -31,6 +31,8 @@ public final class DeidentifyImageRequest { private final DeidentifyImageRequestFile file; + private final Optional configurationId; + private final Optional outputProcessedImage; private final Optional outputOcrText; @@ -52,6 +54,7 @@ public final class DeidentifyImageRequest { private DeidentifyImageRequest( String vaultId, DeidentifyImageRequestFile file, + Optional configurationId, Optional outputProcessedImage, Optional outputOcrText, Optional maskingMethod, @@ -63,6 +66,7 @@ private DeidentifyImageRequest( Map additionalProperties) { this.vaultId = vaultId; this.file = file; + this.configurationId = configurationId; this.outputProcessedImage = outputProcessedImage; this.outputOcrText = outputOcrText; this.maskingMethod = maskingMethod; @@ -87,6 +91,11 @@ public DeidentifyImageRequestFile getFile() { return file; } + @JsonProperty("configuration_id") + public Optional getConfigurationId() { + return configurationId; + } + /** * @return If true, includes processed image in the output. */ @@ -150,6 +159,7 @@ public Map getAdditionalProperties() { private boolean equalTo(DeidentifyImageRequest other) { return vaultId.equals(other.vaultId) && file.equals(other.file) + && configurationId.equals(other.configurationId) && outputProcessedImage.equals(other.outputProcessedImage) && outputOcrText.equals(other.outputOcrText) && maskingMethod.equals(other.maskingMethod) @@ -165,6 +175,7 @@ public int hashCode() { return Objects.hash( this.vaultId, this.file, + this.configurationId, this.outputProcessedImage, this.outputOcrText, this.maskingMethod, @@ -200,6 +211,10 @@ public interface FileStage { public interface _FinalStage { DeidentifyImageRequest build(); + _FinalStage configurationId(Optional configurationId); + + _FinalStage configurationId(String configurationId); + /** *

If true, includes processed image in the output.

*/ @@ -264,6 +279,8 @@ public static final class Builder implements VaultIdStage, FileStage, _FinalStag private Optional outputProcessedImage = Optional.empty(); + private Optional configurationId = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -273,6 +290,7 @@ private Builder() {} public Builder from(DeidentifyImageRequest other) { vaultId(other.getVaultId()); file(other.getFile()); + configurationId(other.getConfigurationId()); outputProcessedImage(other.getOutputProcessedImage()); outputOcrText(other.getOutputOcrText()); maskingMethod(other.getMaskingMethod()); @@ -427,11 +445,25 @@ public _FinalStage outputProcessedImage(Optional outputProcessedImage) return this; } + @java.lang.Override + public _FinalStage configurationId(String configurationId) { + this.configurationId = Optional.ofNullable(configurationId); + return this; + } + + @java.lang.Override + @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) + public _FinalStage configurationId(Optional configurationId) { + this.configurationId = configurationId; + return this; + } + @java.lang.Override public DeidentifyImageRequest build() { return new DeidentifyImageRequest( vaultId, file, + configurationId, outputProcessedImage, outputOcrText, maskingMethod, diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPdfRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPdfRequest.java index 83fbb14f..4927eff3 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPdfRequest.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPdfRequest.java @@ -30,9 +30,11 @@ public final class DeidentifyPdfRequest { private final DeidentifyPdfRequestFile file; - private final Optional density; + private final Optional configurationId; - private final Optional maxResolution; + private final Optional density; + + private final Optional maxResolution; private final Optional> entityTypes; @@ -49,8 +51,9 @@ public final class DeidentifyPdfRequest { private DeidentifyPdfRequest( String vaultId, DeidentifyPdfRequestFile file, - Optional density, - Optional maxResolution, + Optional configurationId, + Optional density, + Optional maxResolution, Optional> entityTypes, Optional tokenType, Optional> allowRegex, @@ -59,6 +62,7 @@ private DeidentifyPdfRequest( Map additionalProperties) { this.vaultId = vaultId; this.file = file; + this.configurationId = configurationId; this.density = density; this.maxResolution = maxResolution; this.entityTypes = entityTypes; @@ -82,11 +86,16 @@ public DeidentifyPdfRequestFile getFile() { return file; } + @JsonProperty("configuration_id") + public Optional getConfigurationId() { + return configurationId; + } + /** * @return Pixel density at which to process the PDF file. */ @JsonProperty("density") - public Optional getDensity() { + public Optional getDensity() { return density; } @@ -94,7 +103,7 @@ public Optional getDensity() { * @return Max resolution at which to process the PDF file. */ @JsonProperty("max_resolution") - public Optional getMaxResolution() { + public Optional getMaxResolution() { return maxResolution; } @@ -137,6 +146,7 @@ public Map getAdditionalProperties() { private boolean equalTo(DeidentifyPdfRequest other) { return vaultId.equals(other.vaultId) && file.equals(other.file) + && configurationId.equals(other.configurationId) && density.equals(other.density) && maxResolution.equals(other.maxResolution) && entityTypes.equals(other.entityTypes) @@ -151,6 +161,7 @@ public int hashCode() { return Objects.hash( this.vaultId, this.file, + this.configurationId, this.density, this.maxResolution, this.entityTypes, @@ -185,19 +196,23 @@ public interface FileStage { public interface _FinalStage { DeidentifyPdfRequest build(); + _FinalStage configurationId(Optional configurationId); + + _FinalStage configurationId(String configurationId); + /** *

Pixel density at which to process the PDF file.

*/ - _FinalStage density(Optional density); + _FinalStage density(Optional density); - _FinalStage density(Integer density); + _FinalStage density(Double density); /** *

Max resolution at which to process the PDF file.

*/ - _FinalStage maxResolution(Optional maxResolution); + _FinalStage maxResolution(Optional maxResolution); - _FinalStage maxResolution(Integer maxResolution); + _FinalStage maxResolution(Double maxResolution); _FinalStage entityTypes(Optional> entityTypes); @@ -236,9 +251,11 @@ public static final class Builder implements VaultIdStage, FileStage, _FinalStag private Optional> entityTypes = Optional.empty(); - private Optional maxResolution = Optional.empty(); + private Optional maxResolution = Optional.empty(); + + private Optional density = Optional.empty(); - private Optional density = Optional.empty(); + private Optional configurationId = Optional.empty(); @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -249,6 +266,7 @@ private Builder() {} public Builder from(DeidentifyPdfRequest other) { vaultId(other.getVaultId()); file(other.getFile()); + configurationId(other.getConfigurationId()); density(other.getDensity()); maxResolution(other.getMaxResolution()); entityTypes(other.getEntityTypes()); @@ -347,7 +365,7 @@ public _FinalStage entityTypes(Optional> entityTypes) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage maxResolution(Integer maxResolution) { + public _FinalStage maxResolution(Double maxResolution) { this.maxResolution = Optional.ofNullable(maxResolution); return this; } @@ -357,7 +375,7 @@ public _FinalStage maxResolution(Integer maxResolution) { */ @java.lang.Override @JsonSetter(value = "max_resolution", nulls = Nulls.SKIP) - public _FinalStage maxResolution(Optional maxResolution) { + public _FinalStage maxResolution(Optional maxResolution) { this.maxResolution = maxResolution; return this; } @@ -367,7 +385,7 @@ public _FinalStage maxResolution(Optional maxResolution) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage density(Integer density) { + public _FinalStage density(Double density) { this.density = Optional.ofNullable(density); return this; } @@ -377,16 +395,30 @@ public _FinalStage density(Integer density) { */ @java.lang.Override @JsonSetter(value = "density", nulls = Nulls.SKIP) - public _FinalStage density(Optional density) { + public _FinalStage density(Optional density) { this.density = density; return this; } + @java.lang.Override + public _FinalStage configurationId(String configurationId) { + this.configurationId = Optional.ofNullable(configurationId); + return this; + } + + @java.lang.Override + @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) + public _FinalStage configurationId(Optional configurationId) { + this.configurationId = configurationId; + return this; + } + @java.lang.Override public DeidentifyPdfRequest build() { return new DeidentifyPdfRequest( vaultId, file, + configurationId, density, maxResolution, entityTypes, diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPresentationRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPresentationRequest.java index 47a63a5b..95ced625 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPresentationRequest.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyPresentationRequest.java @@ -30,6 +30,8 @@ public final class DeidentifyPresentationRequest { private final DeidentifyPresentationRequestFile file; + private final Optional configurationId; + private final Optional> entityTypes; private final Optional tokenType; @@ -45,6 +47,7 @@ public final class DeidentifyPresentationRequest { private DeidentifyPresentationRequest( String vaultId, DeidentifyPresentationRequestFile file, + Optional configurationId, Optional> entityTypes, Optional tokenType, Optional> allowRegex, @@ -53,6 +56,7 @@ private DeidentifyPresentationRequest( Map additionalProperties) { this.vaultId = vaultId; this.file = file; + this.configurationId = configurationId; this.entityTypes = entityTypes; this.tokenType = tokenType; this.allowRegex = allowRegex; @@ -74,6 +78,11 @@ public DeidentifyPresentationRequestFile getFile() { return file; } + @JsonProperty("configuration_id") + public Optional getConfigurationId() { + return configurationId; + } + @JsonProperty("entity_types") public Optional> getEntityTypes() { return entityTypes; @@ -113,6 +122,7 @@ public Map getAdditionalProperties() { private boolean equalTo(DeidentifyPresentationRequest other) { return vaultId.equals(other.vaultId) && file.equals(other.file) + && configurationId.equals(other.configurationId) && entityTypes.equals(other.entityTypes) && tokenType.equals(other.tokenType) && allowRegex.equals(other.allowRegex) @@ -125,6 +135,7 @@ public int hashCode() { return Objects.hash( this.vaultId, this.file, + this.configurationId, this.entityTypes, this.tokenType, this.allowRegex, @@ -157,6 +168,10 @@ public interface FileStage { public interface _FinalStage { DeidentifyPresentationRequest build(); + _FinalStage configurationId(Optional configurationId); + + _FinalStage configurationId(String configurationId); + _FinalStage entityTypes(Optional> entityTypes); _FinalStage entityTypes(List entityTypes); @@ -194,6 +209,8 @@ public static final class Builder implements VaultIdStage, FileStage, _FinalStag private Optional> entityTypes = Optional.empty(); + private Optional configurationId = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -203,6 +220,7 @@ private Builder() {} public Builder from(DeidentifyPresentationRequest other) { vaultId(other.getVaultId()); file(other.getFile()); + configurationId(other.getConfigurationId()); entityTypes(other.getEntityTypes()); tokenType(other.getTokenType()); allowRegex(other.getAllowRegex()); @@ -294,11 +312,25 @@ public _FinalStage entityTypes(Optional> entityTypes) { return this; } + @java.lang.Override + public _FinalStage configurationId(String configurationId) { + this.configurationId = Optional.ofNullable(configurationId); + return this; + } + + @java.lang.Override + @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) + public _FinalStage configurationId(Optional configurationId) { + this.configurationId = configurationId; + return this; + } + @java.lang.Override public DeidentifyPresentationRequest build() { return new DeidentifyPresentationRequest( vaultId, file, + configurationId, entityTypes, tokenType, allowRegex, diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifySpreadsheetRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifySpreadsheetRequest.java index b72b412b..283457f8 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifySpreadsheetRequest.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifySpreadsheetRequest.java @@ -30,6 +30,8 @@ public final class DeidentifySpreadsheetRequest { private final DeidentifySpreadsheetRequestFile file; + private final Optional configurationId; + private final Optional> entityTypes; private final Optional tokenType; @@ -45,6 +47,7 @@ public final class DeidentifySpreadsheetRequest { private DeidentifySpreadsheetRequest( String vaultId, DeidentifySpreadsheetRequestFile file, + Optional configurationId, Optional> entityTypes, Optional tokenType, Optional> allowRegex, @@ -53,6 +56,7 @@ private DeidentifySpreadsheetRequest( Map additionalProperties) { this.vaultId = vaultId; this.file = file; + this.configurationId = configurationId; this.entityTypes = entityTypes; this.tokenType = tokenType; this.allowRegex = allowRegex; @@ -74,6 +78,11 @@ public DeidentifySpreadsheetRequestFile getFile() { return file; } + @JsonProperty("configuration_id") + public Optional getConfigurationId() { + return configurationId; + } + @JsonProperty("entity_types") public Optional> getEntityTypes() { return entityTypes; @@ -113,6 +122,7 @@ public Map getAdditionalProperties() { private boolean equalTo(DeidentifySpreadsheetRequest other) { return vaultId.equals(other.vaultId) && file.equals(other.file) + && configurationId.equals(other.configurationId) && entityTypes.equals(other.entityTypes) && tokenType.equals(other.tokenType) && allowRegex.equals(other.allowRegex) @@ -125,6 +135,7 @@ public int hashCode() { return Objects.hash( this.vaultId, this.file, + this.configurationId, this.entityTypes, this.tokenType, this.allowRegex, @@ -157,6 +168,10 @@ public interface FileStage { public interface _FinalStage { DeidentifySpreadsheetRequest build(); + _FinalStage configurationId(Optional configurationId); + + _FinalStage configurationId(String configurationId); + _FinalStage entityTypes(Optional> entityTypes); _FinalStage entityTypes(List entityTypes); @@ -194,6 +209,8 @@ public static final class Builder implements VaultIdStage, FileStage, _FinalStag private Optional> entityTypes = Optional.empty(); + private Optional configurationId = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -203,6 +220,7 @@ private Builder() {} public Builder from(DeidentifySpreadsheetRequest other) { vaultId(other.getVaultId()); file(other.getFile()); + configurationId(other.getConfigurationId()); entityTypes(other.getEntityTypes()); tokenType(other.getTokenType()); allowRegex(other.getAllowRegex()); @@ -294,11 +312,25 @@ public _FinalStage entityTypes(Optional> entityTypes) { return this; } + @java.lang.Override + public _FinalStage configurationId(String configurationId) { + this.configurationId = Optional.ofNullable(configurationId); + return this; + } + + @java.lang.Override + @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) + public _FinalStage configurationId(Optional configurationId) { + this.configurationId = configurationId; + return this; + } + @java.lang.Override public DeidentifySpreadsheetRequest build() { return new DeidentifySpreadsheetRequest( vaultId, file, + configurationId, entityTypes, tokenType, allowRegex, diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyStructuredTextRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyStructuredTextRequest.java index a61a5ba0..8ff7e195 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyStructuredTextRequest.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyStructuredTextRequest.java @@ -30,6 +30,8 @@ public final class DeidentifyStructuredTextRequest { private final DeidentifyStructuredTextRequestFile file; + private final Optional configurationId; + private final Optional> entityTypes; private final Optional tokenType; @@ -45,6 +47,7 @@ public final class DeidentifyStructuredTextRequest { private DeidentifyStructuredTextRequest( String vaultId, DeidentifyStructuredTextRequestFile file, + Optional configurationId, Optional> entityTypes, Optional tokenType, Optional> allowRegex, @@ -53,6 +56,7 @@ private DeidentifyStructuredTextRequest( Map additionalProperties) { this.vaultId = vaultId; this.file = file; + this.configurationId = configurationId; this.entityTypes = entityTypes; this.tokenType = tokenType; this.allowRegex = allowRegex; @@ -74,6 +78,11 @@ public DeidentifyStructuredTextRequestFile getFile() { return file; } + @JsonProperty("configuration_id") + public Optional getConfigurationId() { + return configurationId; + } + @JsonProperty("entity_types") public Optional> getEntityTypes() { return entityTypes; @@ -113,6 +122,7 @@ public Map getAdditionalProperties() { private boolean equalTo(DeidentifyStructuredTextRequest other) { return vaultId.equals(other.vaultId) && file.equals(other.file) + && configurationId.equals(other.configurationId) && entityTypes.equals(other.entityTypes) && tokenType.equals(other.tokenType) && allowRegex.equals(other.allowRegex) @@ -125,6 +135,7 @@ public int hashCode() { return Objects.hash( this.vaultId, this.file, + this.configurationId, this.entityTypes, this.tokenType, this.allowRegex, @@ -157,6 +168,10 @@ public interface FileStage { public interface _FinalStage { DeidentifyStructuredTextRequest build(); + _FinalStage configurationId(Optional configurationId); + + _FinalStage configurationId(String configurationId); + _FinalStage entityTypes(Optional> entityTypes); _FinalStage entityTypes(List entityTypes); @@ -194,6 +209,8 @@ public static final class Builder implements VaultIdStage, FileStage, _FinalStag private Optional> entityTypes = Optional.empty(); + private Optional configurationId = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -203,6 +220,7 @@ private Builder() {} public Builder from(DeidentifyStructuredTextRequest other) { vaultId(other.getVaultId()); file(other.getFile()); + configurationId(other.getConfigurationId()); entityTypes(other.getEntityTypes()); tokenType(other.getTokenType()); allowRegex(other.getAllowRegex()); @@ -294,11 +312,25 @@ public _FinalStage entityTypes(Optional> entityTypes) { return this; } + @java.lang.Override + public _FinalStage configurationId(String configurationId) { + this.configurationId = Optional.ofNullable(configurationId); + return this; + } + + @java.lang.Override + @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) + public _FinalStage configurationId(Optional configurationId) { + this.configurationId = configurationId; + return this; + } + @java.lang.Override public DeidentifyStructuredTextRequest build() { return new DeidentifyStructuredTextRequest( vaultId, file, + configurationId, entityTypes, tokenType, allowRegex, diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyTextRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyTextRequest.java index 4eb0ac6c..e65d89e8 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyTextRequest.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/DeidentifyTextRequest.java @@ -30,6 +30,8 @@ public final class DeidentifyTextRequest { private final DeidentifyTextRequestFile file; + private final Optional configurationId; + private final Optional> entityTypes; private final Optional tokenType; @@ -45,6 +47,7 @@ public final class DeidentifyTextRequest { private DeidentifyTextRequest( String vaultId, DeidentifyTextRequestFile file, + Optional configurationId, Optional> entityTypes, Optional tokenType, Optional> allowRegex, @@ -53,6 +56,7 @@ private DeidentifyTextRequest( Map additionalProperties) { this.vaultId = vaultId; this.file = file; + this.configurationId = configurationId; this.entityTypes = entityTypes; this.tokenType = tokenType; this.allowRegex = allowRegex; @@ -74,6 +78,11 @@ public DeidentifyTextRequestFile getFile() { return file; } + @JsonProperty("configuration_id") + public Optional getConfigurationId() { + return configurationId; + } + @JsonProperty("entity_types") public Optional> getEntityTypes() { return entityTypes; @@ -113,6 +122,7 @@ public Map getAdditionalProperties() { private boolean equalTo(DeidentifyTextRequest other) { return vaultId.equals(other.vaultId) && file.equals(other.file) + && configurationId.equals(other.configurationId) && entityTypes.equals(other.entityTypes) && tokenType.equals(other.tokenType) && allowRegex.equals(other.allowRegex) @@ -125,6 +135,7 @@ public int hashCode() { return Objects.hash( this.vaultId, this.file, + this.configurationId, this.entityTypes, this.tokenType, this.allowRegex, @@ -157,6 +168,10 @@ public interface FileStage { public interface _FinalStage { DeidentifyTextRequest build(); + _FinalStage configurationId(Optional configurationId); + + _FinalStage configurationId(String configurationId); + _FinalStage entityTypes(Optional> entityTypes); _FinalStage entityTypes(List entityTypes); @@ -194,6 +209,8 @@ public static final class Builder implements VaultIdStage, FileStage, _FinalStag private Optional> entityTypes = Optional.empty(); + private Optional configurationId = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -203,6 +220,7 @@ private Builder() {} public Builder from(DeidentifyTextRequest other) { vaultId(other.getVaultId()); file(other.getFile()); + configurationId(other.getConfigurationId()); entityTypes(other.getEntityTypes()); tokenType(other.getTokenType()); allowRegex(other.getAllowRegex()); @@ -294,11 +312,25 @@ public _FinalStage entityTypes(Optional> entityTypes) { return this; } + @java.lang.Override + public _FinalStage configurationId(String configurationId) { + this.configurationId = Optional.ofNullable(configurationId); + return this; + } + + @java.lang.Override + @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) + public _FinalStage configurationId(Optional configurationId) { + this.configurationId = configurationId; + return this; + } + @java.lang.Override public DeidentifyTextRequest build() { return new DeidentifyTextRequest( vaultId, file, + configurationId, entityTypes, tokenType, allowRegex, diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/ReidentifyFileRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/ReidentifyFileRequest.java new file mode 100644 index 00000000..4afb0146 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/ReidentifyFileRequest.java @@ -0,0 +1,183 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.files.types.ReidentifyFileRequestFile; +import com.skyflow.generated.rest.resources.files.types.ReidentifyFileRequestFormat; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyFileRequest.Builder.class) +public final class ReidentifyFileRequest { + private final String vaultId; + + private final ReidentifyFileRequestFile file; + + private final Optional format; + + private final Map additionalProperties; + + private ReidentifyFileRequest( + String vaultId, + ReidentifyFileRequestFile file, + Optional format, + Map additionalProperties) { + this.vaultId = vaultId; + this.file = file; + this.format = format; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return File to re-identify. Files are specified as Base64-encoded data or an EFS path. + */ + @JsonProperty("file") + public ReidentifyFileRequestFile getFile() { + return file; + } + + /** + * @return Mapping of preferred data formatting options to entity types. Returned values are dependent on the configuration of the vault storing the data and the permissions of the user or account making the request. + */ + @JsonProperty("format") + public Optional getFormat() { + return format; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyFileRequest && equalTo((ReidentifyFileRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyFileRequest other) { + return vaultId.equals(other.vaultId) && file.equals(other.file) && format.equals(other.format); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.file, this.format); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + FileStage vaultId(@NotNull String vaultId); + + Builder from(ReidentifyFileRequest other); + } + + public interface FileStage { + /** + * File to re-identify. Files are specified as Base64-encoded data or an EFS path. + */ + _FinalStage file(@NotNull ReidentifyFileRequestFile file); + } + + public interface _FinalStage { + ReidentifyFileRequest build(); + + /** + *

Mapping of preferred data formatting options to entity types. Returned values are dependent on the configuration of the vault storing the data and the permissions of the user or account making the request.

+ */ + _FinalStage format(Optional format); + + _FinalStage format(ReidentifyFileRequestFormat format); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, FileStage, _FinalStage { + private String vaultId; + + private ReidentifyFileRequestFile file; + + private Optional format = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ReidentifyFileRequest other) { + vaultId(other.getVaultId()); + file(other.getFile()); + format(other.getFormat()); + return this; + } + + @java.lang.Override + @JsonSetter("vault_id") + public FileStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + * File to re-identify. Files are specified as Base64-encoded data or an EFS path.

File to re-identify. Files are specified as Base64-encoded data or an EFS path.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("file") + public _FinalStage file(@NotNull ReidentifyFileRequestFile file) { + this.file = Objects.requireNonNull(file, "file must not be null"); + return this; + } + + /** + *

Mapping of preferred data formatting options to entity types. Returned values are dependent on the configuration of the vault storing the data and the permissions of the user or account making the request.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage format(ReidentifyFileRequestFormat format) { + this.format = Optional.ofNullable(format); + return this; + } + + /** + *

Mapping of preferred data formatting options to entity types. Returned values are dependent on the configuration of the vault storing the data and the permissions of the user or account making the request.

+ */ + @java.lang.Override + @JsonSetter(value = "format", nulls = Nulls.SKIP) + public _FinalStage format(Optional format) { + this.format = format; + return this; + } + + @java.lang.Override + public ReidentifyFileRequest build() { + return new ReidentifyFileRequest(vaultId, file, format, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestFileDataFormat.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestFileDataFormat.java index afc90bc3..b0ab22b9 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestFileDataFormat.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/DeidentifyFileRequestFileDataFormat.java @@ -10,6 +10,8 @@ public enum DeidentifyFileRequestFileDataFormat { CSV("csv"), + DCM("dcm"), + DOC("doc"), DOCX("docx"), diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/ReidentifyFileRequestFile.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/ReidentifyFileRequestFile.java new file mode 100644 index 00000000..bea9b303 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/ReidentifyFileRequestFile.java @@ -0,0 +1,145 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyFileRequestFile.Builder.class) +public final class ReidentifyFileRequestFile { + private final String base64; + + private final ReidentifyFileRequestFileDataFormat dataFormat; + + private final Map additionalProperties; + + private ReidentifyFileRequestFile( + String base64, ReidentifyFileRequestFileDataFormat dataFormat, Map additionalProperties) { + this.base64 = base64; + this.dataFormat = dataFormat; + this.additionalProperties = additionalProperties; + } + + /** + * @return Base64-encoded data of the file to re-identify. + */ + @JsonProperty("base64") + public String getBase64() { + return base64; + } + + /** + * @return Data format of the file. + */ + @JsonProperty("data_format") + public ReidentifyFileRequestFileDataFormat getDataFormat() { + return dataFormat; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyFileRequestFile && equalTo((ReidentifyFileRequestFile) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyFileRequestFile other) { + return base64.equals(other.base64) && dataFormat.equals(other.dataFormat); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.base64, this.dataFormat); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Base64Stage builder() { + return new Builder(); + } + + public interface Base64Stage { + /** + * Base64-encoded data of the file to re-identify. + */ + DataFormatStage base64(@NotNull String base64); + + Builder from(ReidentifyFileRequestFile other); + } + + public interface DataFormatStage { + /** + * Data format of the file. + */ + _FinalStage dataFormat(@NotNull ReidentifyFileRequestFileDataFormat dataFormat); + } + + public interface _FinalStage { + ReidentifyFileRequestFile build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements Base64Stage, DataFormatStage, _FinalStage { + private String base64; + + private ReidentifyFileRequestFileDataFormat dataFormat; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ReidentifyFileRequestFile other) { + base64(other.getBase64()); + dataFormat(other.getDataFormat()); + return this; + } + + /** + * Base64-encoded data of the file to re-identify.

Base64-encoded data of the file to re-identify.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("base64") + public DataFormatStage base64(@NotNull String base64) { + this.base64 = Objects.requireNonNull(base64, "base64 must not be null"); + return this; + } + + /** + * Data format of the file.

Data format of the file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("data_format") + public _FinalStage dataFormat(@NotNull ReidentifyFileRequestFileDataFormat dataFormat) { + this.dataFormat = Objects.requireNonNull(dataFormat, "dataFormat must not be null"); + return this; + } + + @java.lang.Override + public ReidentifyFileRequestFile build() { + return new ReidentifyFileRequestFile(base64, dataFormat, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1FileDataFormat.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/ReidentifyFileRequestFileDataFormat.java similarity index 54% rename from src/main/java/com/skyflow/generated/rest/types/V1FileDataFormat.java rename to src/main/java/com/skyflow/generated/rest/resources/files/types/ReidentifyFileRequestFileDataFormat.java index a384af7f..3e1555f3 100644 --- a/src/main/java/com/skyflow/generated/rest/types/V1FileDataFormat.java +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/ReidentifyFileRequestFileDataFormat.java @@ -1,52 +1,30 @@ /** * This file was auto-generated by Fern from our API Definition. */ -package com.skyflow.generated.rest.types; +package com.skyflow.generated.rest.resources.files.types; import com.fasterxml.jackson.annotation.JsonValue; -public enum V1FileDataFormat { - BMP("bmp"), - +public enum ReidentifyFileRequestFileDataFormat { CSV("csv"), DOC("doc"), DOCX("docx"), - JPEG("jpeg"), - - JPG("jpg"), - JSON("json"), - MP_3("mp3"), - - PDF("pdf"), - - PNG("png"), - - PPT("ppt"), - - PPTX("pptx"), - - TIF("tif"), - - TIFF("tiff"), - TXT("txt"), - UNKNOWN("unknown"), - - WAV("wav"), - XLS("xls"), - XLSX("xlsx"); + XLSX("xlsx"), + + XML("xml"); private final String value; - V1FileDataFormat(String value) { + ReidentifyFileRequestFileDataFormat(String value) { this.value = value; } diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/types/ReidentifyFileRequestFormat.java b/src/main/java/com/skyflow/generated/rest/resources/files/types/ReidentifyFileRequestFormat.java new file mode 100644 index 00000000..232fcd55 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/types/ReidentifyFileRequestFormat.java @@ -0,0 +1,163 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.EntityType; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyFileRequestFormat.Builder.class) +public final class ReidentifyFileRequestFormat { + private final Optional> redacted; + + private final Optional> masked; + + private final Optional> plaintext; + + private final Map additionalProperties; + + private ReidentifyFileRequestFormat( + Optional> redacted, + Optional> masked, + Optional> plaintext, + Map additionalProperties) { + this.redacted = redacted; + this.masked = masked; + this.plaintext = plaintext; + this.additionalProperties = additionalProperties; + } + + /** + * @return Entity types to fully redact. + */ + @JsonProperty("redacted") + public Optional> getRedacted() { + return redacted; + } + + /** + * @return Entity types to mask. + */ + @JsonProperty("masked") + public Optional> getMasked() { + return masked; + } + + /** + * @return Entity types to return in plaintext. + */ + @JsonProperty("plaintext") + public Optional> getPlaintext() { + return plaintext; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyFileRequestFormat && equalTo((ReidentifyFileRequestFormat) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyFileRequestFormat other) { + return redacted.equals(other.redacted) && masked.equals(other.masked) && plaintext.equals(other.plaintext); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.redacted, this.masked, this.plaintext); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> redacted = Optional.empty(); + + private Optional> masked = Optional.empty(); + + private Optional> plaintext = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(ReidentifyFileRequestFormat other) { + redacted(other.getRedacted()); + masked(other.getMasked()); + plaintext(other.getPlaintext()); + return this; + } + + /** + *

Entity types to fully redact.

+ */ + @JsonSetter(value = "redacted", nulls = Nulls.SKIP) + public Builder redacted(Optional> redacted) { + this.redacted = redacted; + return this; + } + + public Builder redacted(List redacted) { + this.redacted = Optional.ofNullable(redacted); + return this; + } + + /** + *

Entity types to mask.

+ */ + @JsonSetter(value = "masked", nulls = Nulls.SKIP) + public Builder masked(Optional> masked) { + this.masked = masked; + return this; + } + + public Builder masked(List masked) { + this.masked = Optional.ofNullable(masked); + return this; + } + + /** + *

Entity types to return in plaintext.

+ */ + @JsonSetter(value = "plaintext", nulls = Nulls.SKIP) + public Builder plaintext(Optional> plaintext) { + this.plaintext = plaintext; + return this; + } + + public Builder plaintext(List plaintext) { + this.plaintext = Optional.ofNullable(plaintext); + return this; + } + + public ReidentifyFileRequestFormat build() { + return new ReidentifyFileRequestFormat(redacted, masked, plaintext, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncGuardrailsClient.java b/src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncGuardrailsClient.java new file mode 100644 index 00000000..1caa38aa --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncGuardrailsClient.java @@ -0,0 +1,43 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.guardrails; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.guardrails.requests.CheckGuardrailsRequest; +import com.skyflow.generated.rest.types.CheckGuardrailsResponse; +import java.util.concurrent.CompletableFuture; + +public class AsyncGuardrailsClient { + protected final ClientOptions clientOptions; + + private final AsyncRawGuardrailsClient rawClient; + + public AsyncGuardrailsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawGuardrailsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawGuardrailsClient withRawResponse() { + return this.rawClient; + } + + /** + * Preserve safety and compliance with usage policies. + */ + public CompletableFuture checkGuardrails(CheckGuardrailsRequest request) { + return this.rawClient.checkGuardrails(request).thenApply(response -> response.body()); + } + + /** + * Preserve safety and compliance with usage policies. + */ + public CompletableFuture checkGuardrails( + CheckGuardrailsRequest request, RequestOptions requestOptions) { + return this.rawClient.checkGuardrails(request, requestOptions).thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncRawGuardrailsClient.java b/src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncRawGuardrailsClient.java new file mode 100644 index 00000000..fcea229b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/guardrails/AsyncRawGuardrailsClient.java @@ -0,0 +1,127 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.guardrails; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.InternalServerError; +import com.skyflow.generated.rest.errors.UnauthorizedError; +import com.skyflow.generated.rest.resources.guardrails.requests.CheckGuardrailsRequest; +import com.skyflow.generated.rest.types.CheckGuardrailsResponse; +import com.skyflow.generated.rest.types.ErrorResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawGuardrailsClient { + protected final ClientOptions clientOptions; + + public AsyncRawGuardrailsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Preserve safety and compliance with usage policies. + */ + public CompletableFuture> checkGuardrails( + CheckGuardrailsRequest request) { + return checkGuardrails(request, null); + } + + /** + * Preserve safety and compliance with usage policies. + */ + public CompletableFuture> checkGuardrails( + CheckGuardrailsRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/guardrails") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue( + responseBody.string(), CheckGuardrailsResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/guardrails/GuardrailsClient.java b/src/main/java/com/skyflow/generated/rest/resources/guardrails/GuardrailsClient.java new file mode 100644 index 00000000..fe4ab899 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/guardrails/GuardrailsClient.java @@ -0,0 +1,41 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.guardrails; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.guardrails.requests.CheckGuardrailsRequest; +import com.skyflow.generated.rest.types.CheckGuardrailsResponse; + +public class GuardrailsClient { + protected final ClientOptions clientOptions; + + private final RawGuardrailsClient rawClient; + + public GuardrailsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawGuardrailsClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawGuardrailsClient withRawResponse() { + return this.rawClient; + } + + /** + * Preserve safety and compliance with usage policies. + */ + public CheckGuardrailsResponse checkGuardrails(CheckGuardrailsRequest request) { + return this.rawClient.checkGuardrails(request).body(); + } + + /** + * Preserve safety and compliance with usage policies. + */ + public CheckGuardrailsResponse checkGuardrails(CheckGuardrailsRequest request, RequestOptions requestOptions) { + return this.rawClient.checkGuardrails(request, requestOptions).body(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/guardrails/RawGuardrailsClient.java b/src/main/java/com/skyflow/generated/rest/resources/guardrails/RawGuardrailsClient.java new file mode 100644 index 00000000..2667b55a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/guardrails/RawGuardrailsClient.java @@ -0,0 +1,102 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.guardrails; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.MediaTypes; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.InternalServerError; +import com.skyflow.generated.rest.errors.UnauthorizedError; +import com.skyflow.generated.rest.resources.guardrails.requests.CheckGuardrailsRequest; +import com.skyflow.generated.rest.types.CheckGuardrailsResponse; +import com.skyflow.generated.rest.types.ErrorResponse; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawGuardrailsClient { + protected final ClientOptions clientOptions; + + public RawGuardrailsClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Preserve safety and compliance with usage policies. + */ + public ApiClientHttpResponse checkGuardrails(CheckGuardrailsRequest request) { + return checkGuardrails(request, null); + } + + /** + * Preserve safety and compliance with usage policies. + */ + public ApiClientHttpResponse checkGuardrails( + CheckGuardrailsRequest request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/detect/guardrails") + .build(); + RequestBody body; + try { + body = RequestBody.create( + ObjectMappers.JSON_MAPPER.writeValueAsBytes(request), MediaTypes.APPLICATION_JSON); + } catch (JsonProcessingException e) { + throw new ApiClientException("Failed to serialize request", e); + } + Request okhttpRequest = new Request.Builder() + .url(httpUrl) + .method("POST", body) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Content-Type", "application/json") + .addHeader("Accept", "application/json") + .build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), CheckGuardrailsResponse.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/guardrails/requests/CheckGuardrailsRequest.java b/src/main/java/com/skyflow/generated/rest/resources/guardrails/requests/CheckGuardrailsRequest.java new file mode 100644 index 00000000..8fbf90f7 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/guardrails/requests/CheckGuardrailsRequest.java @@ -0,0 +1,227 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.guardrails.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = CheckGuardrailsRequest.Builder.class) +public final class CheckGuardrailsRequest { + private final String vaultId; + + private final String text; + + private final Optional checkToxicity; + + private final Optional> denyTopics; + + private final Map additionalProperties; + + private CheckGuardrailsRequest( + String vaultId, + String text, + Optional checkToxicity, + Optional> denyTopics, + Map additionalProperties) { + this.vaultId = vaultId; + this.text = text; + this.checkToxicity = checkToxicity; + this.denyTopics = denyTopics; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return Text to check against guardrails. + */ + @JsonProperty("text") + public String getText() { + return text; + } + + /** + * @return Check for toxicity in the text. + */ + @JsonProperty("check_toxicity") + public Optional getCheckToxicity() { + return checkToxicity; + } + + /** + * @return List of topics to deny. + */ + @JsonProperty("deny_topics") + public Optional> getDenyTopics() { + return denyTopics; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof CheckGuardrailsRequest && equalTo((CheckGuardrailsRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(CheckGuardrailsRequest other) { + return vaultId.equals(other.vaultId) + && text.equals(other.text) + && checkToxicity.equals(other.checkToxicity) + && denyTopics.equals(other.denyTopics); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.text, this.checkToxicity, this.denyTopics); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + TextStage vaultId(@NotNull String vaultId); + + Builder from(CheckGuardrailsRequest other); + } + + public interface TextStage { + /** + * Text to check against guardrails. + */ + _FinalStage text(@NotNull String text); + } + + public interface _FinalStage { + CheckGuardrailsRequest build(); + + /** + *

Check for toxicity in the text.

+ */ + _FinalStage checkToxicity(Optional checkToxicity); + + _FinalStage checkToxicity(Boolean checkToxicity); + + /** + *

List of topics to deny.

+ */ + _FinalStage denyTopics(Optional> denyTopics); + + _FinalStage denyTopics(List denyTopics); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements VaultIdStage, TextStage, _FinalStage { + private String vaultId; + + private String text; + + private Optional> denyTopics = Optional.empty(); + + private Optional checkToxicity = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(CheckGuardrailsRequest other) { + vaultId(other.getVaultId()); + text(other.getText()); + checkToxicity(other.getCheckToxicity()); + denyTopics(other.getDenyTopics()); + return this; + } + + @java.lang.Override + @JsonSetter("vault_id") + public TextStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + /** + * Text to check against guardrails.

Text to check against guardrails.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("text") + public _FinalStage text(@NotNull String text) { + this.text = Objects.requireNonNull(text, "text must not be null"); + return this; + } + + /** + *

List of topics to deny.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage denyTopics(List denyTopics) { + this.denyTopics = Optional.ofNullable(denyTopics); + return this; + } + + /** + *

List of topics to deny.

+ */ + @java.lang.Override + @JsonSetter(value = "deny_topics", nulls = Nulls.SKIP) + public _FinalStage denyTopics(Optional> denyTopics) { + this.denyTopics = denyTopics; + return this; + } + + /** + *

Check for toxicity in the text.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage checkToxicity(Boolean checkToxicity) { + this.checkToxicity = Optional.ofNullable(checkToxicity); + return this; + } + + /** + *

Check for toxicity in the text.

+ */ + @java.lang.Override + @JsonSetter(value = "check_toxicity", nulls = Nulls.SKIP) + public _FinalStage checkToxicity(Optional checkToxicity) { + this.checkToxicity = checkToxicity; + return this; + } + + @java.lang.Override + public CheckGuardrailsRequest build() { + return new CheckGuardrailsRequest(vaultId, text, checkToxicity, denyTopics, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRawRecordsClient.java b/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRawRecordsClient.java index 757ee8e4..a810f142 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRawRecordsClient.java +++ b/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRawRecordsClient.java @@ -12,7 +12,10 @@ import com.skyflow.generated.rest.core.ObjectMappers; import com.skyflow.generated.rest.core.QueryStringMapper; import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.InternalServerError; import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.errors.UnauthorizedError; import com.skyflow.generated.rest.resources.records.requests.FileServiceUploadFileRequest; import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkDeleteRecordBody; @@ -20,6 +23,9 @@ import com.skyflow.generated.rest.resources.records.requests.RecordServiceGetRecordRequest; import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.resources.records.requests.UploadFileV2Request; +import com.skyflow.generated.rest.types.ErrorResponse; +import com.skyflow.generated.rest.types.UploadFileV2Response; import com.skyflow.generated.rest.types.V1BatchOperationResponse; import com.skyflow.generated.rest.types.V1BulkDeleteRecordResponse; import com.skyflow.generated.rest.types.V1BulkGetRecordResponse; @@ -703,12 +709,12 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { * Uploads a file to the specified record. */ public CompletableFuture> fileServiceUploadFile( - String vaultId, String objectName, String id, Optional fileColumnName) { + String vaultId, String objectName, String id, Optional file) { return fileServiceUploadFile( vaultId, objectName, id, - fileColumnName, + file, FileServiceUploadFileRequest.builder().build()); } @@ -716,12 +722,8 @@ public CompletableFuture> fileServ * Uploads a file to the specified record. */ public CompletableFuture> fileServiceUploadFile( - String vaultId, - String objectName, - String id, - Optional fileColumnName, - FileServiceUploadFileRequest request) { - return fileServiceUploadFile(vaultId, objectName, id, fileColumnName, request, null); + String vaultId, String objectName, String id, Optional file, FileServiceUploadFileRequest request) { + return fileServiceUploadFile(vaultId, objectName, id, file, request, null); } /** @@ -731,7 +733,7 @@ public CompletableFuture> fileServ String vaultId, String objectName, String id, - Optional fileColumnName, + Optional file, FileServiceUploadFileRequest request, RequestOptions requestOptions) { HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) @@ -744,15 +746,15 @@ public CompletableFuture> fileServ .build(); MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM); try { - if (fileColumnName.isPresent()) { - String fileColumnNameMimeType = - Files.probeContentType(fileColumnName.get().toPath()); - MediaType fileColumnNameMimeTypeMediaType = - fileColumnNameMimeType != null ? MediaType.parse(fileColumnNameMimeType) : null; + if (file.isPresent()) { + String fileMimeType = Files.probeContentType(file.get().toPath()); + MediaType fileMimeTypeMediaType = fileMimeType != null ? MediaType.parse(fileMimeType) : null; body.addFormDataPart( - "fileColumnName", - fileColumnName.get().getName(), - RequestBody.create(fileColumnName.get(), fileColumnNameMimeTypeMediaType)); + "file", file.get().getName(), RequestBody.create(file.get(), fileMimeTypeMediaType)); + } + if (request.getColumnName().isPresent()) { + QueryStringMapper.addFormDataPart( + body, "columnName", request.getColumnName().get(), false); } } catch (Exception e) { throw new RuntimeException(e); @@ -953,4 +955,111 @@ public void onFailure(@NotNull Call call, @NotNull IOException e) { }); return future; } + + /** + * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. + */ + public CompletableFuture> uploadFileV2( + String vaultId, File file, UploadFileV2Request request) { + return uploadFileV2(vaultId, file, request, null); + } + + /** + * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. + */ + public CompletableFuture> uploadFileV2( + String vaultId, File file, UploadFileV2Request request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/vaults") + .addPathSegment(vaultId) + .addPathSegments("files/upload") + .build(); + MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM); + try { + QueryStringMapper.addFormDataPart(body, "tableName", request.getTableName(), false); + QueryStringMapper.addFormDataPart(body, "columnName", request.getColumnName(), false); + String fileMimeType = Files.probeContentType(file.toPath()); + MediaType fileMimeTypeMediaType = fileMimeType != null ? MediaType.parse(fileMimeType) : null; + body.addFormDataPart("file", file.getName(), RequestBody.create(file, fileMimeTypeMediaType)); + if (request.getSkyflowId().isPresent()) { + QueryStringMapper.addFormDataPart( + body, "skyflowID", request.getSkyflowId().get(), false); + } + if (request.getReturnFileMetadata().isPresent()) { + QueryStringMapper.addFormDataPart( + body, + "returnFileMetadata", + request.getReturnFileMetadata().get(), + false); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", body.build()) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), UploadFileV2Response.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + future.completeExceptionally(new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 401: + future.completeExceptionally(new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 404: + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + case 500: + future.completeExceptionally(new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), + response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } } diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRecordsClient.java b/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRecordsClient.java index baf98c1d..c6925b50 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRecordsClient.java +++ b/src/main/java/com/skyflow/generated/rest/resources/records/AsyncRecordsClient.java @@ -12,6 +12,8 @@ import com.skyflow.generated.rest.resources.records.requests.RecordServiceGetRecordRequest; import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.resources.records.requests.UploadFileV2Request; +import com.skyflow.generated.rest.types.UploadFileV2Response; import com.skyflow.generated.rest.types.V1BatchOperationResponse; import com.skyflow.generated.rest.types.V1BulkDeleteRecordResponse; import com.skyflow.generated.rest.types.V1BulkGetRecordResponse; @@ -240,9 +242,9 @@ public CompletableFuture recordServiceDeleteRecord( * Uploads a file to the specified record. */ public CompletableFuture fileServiceUploadFile( - String vaultId, String objectName, String id, Optional fileColumnName) { + String vaultId, String objectName, String id, Optional file) { return this.rawClient - .fileServiceUploadFile(vaultId, objectName, id, fileColumnName) + .fileServiceUploadFile(vaultId, objectName, id, file) .thenApply(response -> response.body()); } @@ -250,13 +252,9 @@ public CompletableFuture fileServiceUploadFile( * Uploads a file to the specified record. */ public CompletableFuture fileServiceUploadFile( - String vaultId, - String objectName, - String id, - Optional fileColumnName, - FileServiceUploadFileRequest request) { + String vaultId, String objectName, String id, Optional file, FileServiceUploadFileRequest request) { return this.rawClient - .fileServiceUploadFile(vaultId, objectName, id, fileColumnName, request) + .fileServiceUploadFile(vaultId, objectName, id, file, request) .thenApply(response -> response.body()); } @@ -267,11 +265,11 @@ public CompletableFuture fileServiceUploadFile( String vaultId, String objectName, String id, - Optional fileColumnName, + Optional file, FileServiceUploadFileRequest request, RequestOptions requestOptions) { return this.rawClient - .fileServiceUploadFile(vaultId, objectName, id, fileColumnName, request, requestOptions) + .fileServiceUploadFile(vaultId, objectName, id, file, request, requestOptions) .thenApply(response -> response.body()); } @@ -314,4 +312,22 @@ public CompletableFuture fileServiceGetFileScanStat .fileServiceGetFileScanStatus(vaultId, tableName, id, columnName, requestOptions) .thenApply(response -> response.body()); } + + /** + * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. + */ + public CompletableFuture uploadFileV2( + String vaultId, File file, UploadFileV2Request request) { + return this.rawClient.uploadFileV2(vaultId, file, request).thenApply(response -> response.body()); + } + + /** + * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. + */ + public CompletableFuture uploadFileV2( + String vaultId, File file, UploadFileV2Request request, RequestOptions requestOptions) { + return this.rawClient + .uploadFileV2(vaultId, file, request, requestOptions) + .thenApply(response -> response.body()); + } } diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/RawRecordsClient.java b/src/main/java/com/skyflow/generated/rest/resources/records/RawRecordsClient.java index 593f5e3d..d1b607a0 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/records/RawRecordsClient.java +++ b/src/main/java/com/skyflow/generated/rest/resources/records/RawRecordsClient.java @@ -12,7 +12,10 @@ import com.skyflow.generated.rest.core.ObjectMappers; import com.skyflow.generated.rest.core.QueryStringMapper; import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.BadRequestError; +import com.skyflow.generated.rest.errors.InternalServerError; import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.errors.UnauthorizedError; import com.skyflow.generated.rest.resources.records.requests.FileServiceUploadFileRequest; import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; import com.skyflow.generated.rest.resources.records.requests.RecordServiceBulkDeleteRecordBody; @@ -20,6 +23,9 @@ import com.skyflow.generated.rest.resources.records.requests.RecordServiceGetRecordRequest; import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.resources.records.requests.UploadFileV2Request; +import com.skyflow.generated.rest.types.ErrorResponse; +import com.skyflow.generated.rest.types.UploadFileV2Response; import com.skyflow.generated.rest.types.V1BatchOperationResponse; import com.skyflow.generated.rest.types.V1BulkDeleteRecordResponse; import com.skyflow.generated.rest.types.V1BulkGetRecordResponse; @@ -591,12 +597,12 @@ public ApiClientHttpResponse recordServiceDeleteRecord( * Uploads a file to the specified record. */ public ApiClientHttpResponse fileServiceUploadFile( - String vaultId, String objectName, String id, Optional fileColumnName) { + String vaultId, String objectName, String id, Optional file) { return fileServiceUploadFile( vaultId, objectName, id, - fileColumnName, + file, FileServiceUploadFileRequest.builder().build()); } @@ -604,12 +610,8 @@ public ApiClientHttpResponse fileServiceUploadFile( * Uploads a file to the specified record. */ public ApiClientHttpResponse fileServiceUploadFile( - String vaultId, - String objectName, - String id, - Optional fileColumnName, - FileServiceUploadFileRequest request) { - return fileServiceUploadFile(vaultId, objectName, id, fileColumnName, request, null); + String vaultId, String objectName, String id, Optional file, FileServiceUploadFileRequest request) { + return fileServiceUploadFile(vaultId, objectName, id, file, request, null); } /** @@ -619,7 +621,7 @@ public ApiClientHttpResponse fileServiceUploadFile( String vaultId, String objectName, String id, - Optional fileColumnName, + Optional file, FileServiceUploadFileRequest request, RequestOptions requestOptions) { HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) @@ -632,15 +634,15 @@ public ApiClientHttpResponse fileServiceUploadFile( .build(); MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM); try { - if (fileColumnName.isPresent()) { - String fileColumnNameMimeType = - Files.probeContentType(fileColumnName.get().toPath()); - MediaType fileColumnNameMimeTypeMediaType = - fileColumnNameMimeType != null ? MediaType.parse(fileColumnNameMimeType) : null; + if (file.isPresent()) { + String fileMimeType = Files.probeContentType(file.get().toPath()); + MediaType fileMimeTypeMediaType = fileMimeType != null ? MediaType.parse(fileMimeType) : null; body.addFormDataPart( - "fileColumnName", - fileColumnName.get().getName(), - RequestBody.create(fileColumnName.get(), fileColumnNameMimeTypeMediaType)); + "file", file.get().getName(), RequestBody.create(file.get(), fileMimeTypeMediaType)); + } + if (request.getColumnName().isPresent()) { + QueryStringMapper.addFormDataPart( + body, "columnName", request.getColumnName().get(), false); } } catch (Exception e) { throw new RuntimeException(e); @@ -797,4 +799,90 @@ public ApiClientHttpResponse fileServiceGetFileScan throw new ApiClientException("Network error executing HTTP request", e); } } + + /** + * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. + */ + public ApiClientHttpResponse uploadFileV2( + String vaultId, File file, UploadFileV2Request request) { + return uploadFileV2(vaultId, file, request, null); + } + + /** + * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. + */ + public ApiClientHttpResponse uploadFileV2( + String vaultId, File file, UploadFileV2Request request, RequestOptions requestOptions) { + HttpUrl httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v2/vaults") + .addPathSegment(vaultId) + .addPathSegments("files/upload") + .build(); + MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM); + try { + QueryStringMapper.addFormDataPart(body, "tableName", request.getTableName(), false); + QueryStringMapper.addFormDataPart(body, "columnName", request.getColumnName(), false); + String fileMimeType = Files.probeContentType(file.toPath()); + MediaType fileMimeTypeMediaType = fileMimeType != null ? MediaType.parse(fileMimeType) : null; + body.addFormDataPart("file", file.getName(), RequestBody.create(file, fileMimeTypeMediaType)); + if (request.getSkyflowId().isPresent()) { + QueryStringMapper.addFormDataPart( + body, "skyflowID", request.getSkyflowId().get(), false); + } + if (request.getReturnFileMetadata().isPresent()) { + QueryStringMapper.addFormDataPart( + body, + "returnFileMetadata", + request.getReturnFileMetadata().get(), + false); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl) + .method("POST", body.build()) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), UploadFileV2Response.class), + response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + switch (response.code()) { + case 400: + throw new BadRequestError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 401: + throw new UnauthorizedError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 404: + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + case 500: + throw new InternalServerError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, ErrorResponse.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } } diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/RecordsClient.java b/src/main/java/com/skyflow/generated/rest/resources/records/RecordsClient.java index fee9d49b..7b4599c6 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/records/RecordsClient.java +++ b/src/main/java/com/skyflow/generated/rest/resources/records/RecordsClient.java @@ -12,6 +12,8 @@ import com.skyflow.generated.rest.resources.records.requests.RecordServiceGetRecordRequest; import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.resources.records.requests.UploadFileV2Request; +import com.skyflow.generated.rest.types.UploadFileV2Response; import com.skyflow.generated.rest.types.V1BatchOperationResponse; import com.skyflow.generated.rest.types.V1BulkDeleteRecordResponse; import com.skyflow.generated.rest.types.V1BulkGetRecordResponse; @@ -236,9 +238,9 @@ public V1DeleteRecordResponse recordServiceDeleteRecord( * Uploads a file to the specified record. */ public V1UpdateRecordResponse fileServiceUploadFile( - String vaultId, String objectName, String id, Optional fileColumnName) { + String vaultId, String objectName, String id, Optional file) { return this.rawClient - .fileServiceUploadFile(vaultId, objectName, id, fileColumnName) + .fileServiceUploadFile(vaultId, objectName, id, file) .body(); } @@ -246,13 +248,9 @@ public V1UpdateRecordResponse fileServiceUploadFile( * Uploads a file to the specified record. */ public V1UpdateRecordResponse fileServiceUploadFile( - String vaultId, - String objectName, - String id, - Optional fileColumnName, - FileServiceUploadFileRequest request) { + String vaultId, String objectName, String id, Optional file, FileServiceUploadFileRequest request) { return this.rawClient - .fileServiceUploadFile(vaultId, objectName, id, fileColumnName, request) + .fileServiceUploadFile(vaultId, objectName, id, file, request) .body(); } @@ -263,11 +261,11 @@ public V1UpdateRecordResponse fileServiceUploadFile( String vaultId, String objectName, String id, - Optional fileColumnName, + Optional file, FileServiceUploadFileRequest request, RequestOptions requestOptions) { return this.rawClient - .fileServiceUploadFile(vaultId, objectName, id, fileColumnName, request, requestOptions) + .fileServiceUploadFile(vaultId, objectName, id, file, request, requestOptions) .body(); } @@ -309,4 +307,21 @@ public V1GetFileScanStatusResponse fileServiceGetFileScanStatus( .fileServiceGetFileScanStatus(vaultId, tableName, id, columnName, requestOptions) .body(); } + + /** + * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. + */ + public UploadFileV2Response uploadFileV2(String vaultId, File file, UploadFileV2Request request) { + return this.rawClient.uploadFileV2(vaultId, file, request).body(); + } + + /** + * Uploads the specified file to a record. If an existing record isn't specified, creates a new record and uploads the file to that record. + */ + public UploadFileV2Response uploadFileV2( + String vaultId, File file, UploadFileV2Request request, RequestOptions requestOptions) { + return this.rawClient + .uploadFileV2(vaultId, file, request, requestOptions) + .body(); + } } diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/requests/FileServiceUploadFileRequest.java b/src/main/java/com/skyflow/generated/rest/resources/records/requests/FileServiceUploadFileRequest.java index d1b64906..8152e4d7 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/records/requests/FileServiceUploadFileRequest.java +++ b/src/main/java/com/skyflow/generated/rest/resources/records/requests/FileServiceUploadFileRequest.java @@ -7,24 +7,40 @@ import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.skyflow.generated.rest.core.ObjectMappers; import java.util.HashMap; import java.util.Map; +import java.util.Objects; +import java.util.Optional; @JsonInclude(JsonInclude.Include.NON_ABSENT) @JsonDeserialize(builder = FileServiceUploadFileRequest.Builder.class) public final class FileServiceUploadFileRequest { + private final Optional columnName; + private final Map additionalProperties; - private FileServiceUploadFileRequest(Map additionalProperties) { + private FileServiceUploadFileRequest(Optional columnName, Map additionalProperties) { + this.columnName = columnName; this.additionalProperties = additionalProperties; } + /** + * @return Name of the column to store the file in. The column must have a file data type. + */ + @JsonProperty("columnName") + public Optional getColumnName() { + return columnName; + } + @java.lang.Override public boolean equals(Object other) { if (this == other) return true; - return other instanceof FileServiceUploadFileRequest; + return other instanceof FileServiceUploadFileRequest && equalTo((FileServiceUploadFileRequest) other); } @JsonAnyGetter @@ -32,6 +48,15 @@ public Map getAdditionalProperties() { return this.additionalProperties; } + private boolean equalTo(FileServiceUploadFileRequest other) { + return columnName.equals(other.columnName); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.columnName); + } + @java.lang.Override public String toString() { return ObjectMappers.stringify(this); @@ -43,17 +68,34 @@ public static Builder builder() { @JsonIgnoreProperties(ignoreUnknown = true) public static final class Builder { + private Optional columnName = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); private Builder() {} public Builder from(FileServiceUploadFileRequest other) { + columnName(other.getColumnName()); + return this; + } + + /** + *

Name of the column to store the file in. The column must have a file data type.

+ */ + @JsonSetter(value = "columnName", nulls = Nulls.SKIP) + public Builder columnName(Optional columnName) { + this.columnName = columnName; + return this; + } + + public Builder columnName(String columnName) { + this.columnName = Optional.ofNullable(columnName); return this; } public FileServiceUploadFileRequest build() { - return new FileServiceUploadFileRequest(additionalProperties); + return new FileServiceUploadFileRequest(columnName, additionalProperties); } } } diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/requests/UploadFileV2Request.java b/src/main/java/com/skyflow/generated/rest/resources/records/requests/UploadFileV2Request.java new file mode 100644 index 00000000..ca26f0d3 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/requests/UploadFileV2Request.java @@ -0,0 +1,236 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = UploadFileV2Request.Builder.class) +public final class UploadFileV2Request { + private final String tableName; + + private final String columnName; + + private final Optional skyflowId; + + private final Optional returnFileMetadata; + + private final Map additionalProperties; + + private UploadFileV2Request( + String tableName, + String columnName, + Optional skyflowId, + Optional returnFileMetadata, + Map additionalProperties) { + this.tableName = tableName; + this.columnName = columnName; + this.skyflowId = skyflowId; + this.returnFileMetadata = returnFileMetadata; + this.additionalProperties = additionalProperties; + } + + /** + * @return Name of the table to upload the file to. + */ + @JsonProperty("tableName") + public String getTableName() { + return tableName; + } + + /** + * @return Name of the column to upload the file to. The column must have a file data type. + */ + @JsonProperty("columnName") + public String getColumnName() { + return columnName; + } + + /** + * @return Skyflow ID of the record to upload the file to. If skyflowID isn't specified, a new record will be created. + */ + @JsonProperty("skyflowID") + public Optional getSkyflowId() { + return skyflowId; + } + + /** + * @return If true, returns metadata about the uploaded file. + */ + @JsonProperty("returnFileMetadata") + public Optional getReturnFileMetadata() { + return returnFileMetadata; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof UploadFileV2Request && equalTo((UploadFileV2Request) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(UploadFileV2Request other) { + return tableName.equals(other.tableName) + && columnName.equals(other.columnName) + && skyflowId.equals(other.skyflowId) + && returnFileMetadata.equals(other.returnFileMetadata); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.tableName, this.columnName, this.skyflowId, this.returnFileMetadata); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static TableNameStage builder() { + return new Builder(); + } + + public interface TableNameStage { + /** + * Name of the table to upload the file to. + */ + ColumnNameStage tableName(@NotNull String tableName); + + Builder from(UploadFileV2Request other); + } + + public interface ColumnNameStage { + /** + * Name of the column to upload the file to. The column must have a `file` data type. + */ + _FinalStage columnName(@NotNull String columnName); + } + + public interface _FinalStage { + UploadFileV2Request build(); + + /** + *

Skyflow ID of the record to upload the file to. If skyflowID isn't specified, a new record will be created.

+ */ + _FinalStage skyflowId(Optional skyflowId); + + _FinalStage skyflowId(String skyflowId); + + /** + *

If true, returns metadata about the uploaded file.

+ */ + _FinalStage returnFileMetadata(Optional returnFileMetadata); + + _FinalStage returnFileMetadata(Boolean returnFileMetadata); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements TableNameStage, ColumnNameStage, _FinalStage { + private String tableName; + + private String columnName; + + private Optional returnFileMetadata = Optional.empty(); + + private Optional skyflowId = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(UploadFileV2Request other) { + tableName(other.getTableName()); + columnName(other.getColumnName()); + skyflowId(other.getSkyflowId()); + returnFileMetadata(other.getReturnFileMetadata()); + return this; + } + + /** + * Name of the table to upload the file to.

Name of the table to upload the file to.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("tableName") + public ColumnNameStage tableName(@NotNull String tableName) { + this.tableName = Objects.requireNonNull(tableName, "tableName must not be null"); + return this; + } + + /** + * Name of the column to upload the file to. The column must have a `file` data type.

Name of the column to upload the file to. The column must have a file data type.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("columnName") + public _FinalStage columnName(@NotNull String columnName) { + this.columnName = Objects.requireNonNull(columnName, "columnName must not be null"); + return this; + } + + /** + *

If true, returns metadata about the uploaded file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage returnFileMetadata(Boolean returnFileMetadata) { + this.returnFileMetadata = Optional.ofNullable(returnFileMetadata); + return this; + } + + /** + *

If true, returns metadata about the uploaded file.

+ */ + @java.lang.Override + @JsonSetter(value = "returnFileMetadata", nulls = Nulls.SKIP) + public _FinalStage returnFileMetadata(Optional returnFileMetadata) { + this.returnFileMetadata = returnFileMetadata; + return this; + } + + /** + *

Skyflow ID of the record to upload the file to. If skyflowID isn't specified, a new record will be created.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + public _FinalStage skyflowId(String skyflowId) { + this.skyflowId = Optional.ofNullable(skyflowId); + return this; + } + + /** + *

Skyflow ID of the record to upload the file to. If skyflowID isn't specified, a new record will be created.

+ */ + @java.lang.Override + @JsonSetter(value = "skyflowID", nulls = Nulls.SKIP) + public _FinalStage skyflowId(Optional skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + @java.lang.Override + public UploadFileV2Request build() { + return new UploadFileV2Request(tableName, columnName, skyflowId, returnFileMetadata, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/strings/requests/DeidentifyStringRequest.java b/src/main/java/com/skyflow/generated/rest/resources/strings/requests/DeidentifyStringRequest.java index 4a74fcba..18b6cd98 100644 --- a/src/main/java/com/skyflow/generated/rest/resources/strings/requests/DeidentifyStringRequest.java +++ b/src/main/java/com/skyflow/generated/rest/resources/strings/requests/DeidentifyStringRequest.java @@ -29,6 +29,8 @@ public final class DeidentifyStringRequest { private final String text; + private final Optional configurationId; + private final Optional> entityTypes; private final Optional tokenType; @@ -44,6 +46,7 @@ public final class DeidentifyStringRequest { private DeidentifyStringRequest( String vaultId, String text, + Optional configurationId, Optional> entityTypes, Optional tokenType, Optional> allowRegex, @@ -52,6 +55,7 @@ private DeidentifyStringRequest( Map additionalProperties) { this.vaultId = vaultId; this.text = text; + this.configurationId = configurationId; this.entityTypes = entityTypes; this.tokenType = tokenType; this.allowRegex = allowRegex; @@ -73,6 +77,11 @@ public String getText() { return text; } + @JsonProperty("configuration_id") + public Optional getConfigurationId() { + return configurationId; + } + @JsonProperty("entity_types") public Optional> getEntityTypes() { return entityTypes; @@ -112,6 +121,7 @@ public Map getAdditionalProperties() { private boolean equalTo(DeidentifyStringRequest other) { return vaultId.equals(other.vaultId) && text.equals(other.text) + && configurationId.equals(other.configurationId) && entityTypes.equals(other.entityTypes) && tokenType.equals(other.tokenType) && allowRegex.equals(other.allowRegex) @@ -124,6 +134,7 @@ public int hashCode() { return Objects.hash( this.vaultId, this.text, + this.configurationId, this.entityTypes, this.tokenType, this.allowRegex, @@ -156,6 +167,10 @@ public interface TextStage { public interface _FinalStage { DeidentifyStringRequest build(); + _FinalStage configurationId(Optional configurationId); + + _FinalStage configurationId(String configurationId); + _FinalStage entityTypes(Optional> entityTypes); _FinalStage entityTypes(List entityTypes); @@ -193,6 +208,8 @@ public static final class Builder implements VaultIdStage, TextStage, _FinalStag private Optional> entityTypes = Optional.empty(); + private Optional configurationId = Optional.empty(); + @JsonAnySetter private Map additionalProperties = new HashMap<>(); @@ -202,6 +219,7 @@ private Builder() {} public Builder from(DeidentifyStringRequest other) { vaultId(other.getVaultId()); text(other.getText()); + configurationId(other.getConfigurationId()); entityTypes(other.getEntityTypes()); tokenType(other.getTokenType()); allowRegex(other.getAllowRegex()); @@ -293,11 +311,25 @@ public _FinalStage entityTypes(Optional> entityTypes) { return this; } + @java.lang.Override + public _FinalStage configurationId(String configurationId) { + this.configurationId = Optional.ofNullable(configurationId); + return this; + } + + @java.lang.Override + @JsonSetter(value = "configuration_id", nulls = Nulls.SKIP) + public _FinalStage configurationId(Optional configurationId) { + this.configurationId = configurationId; + return this; + } + @java.lang.Override public DeidentifyStringRequest build() { return new DeidentifyStringRequest( vaultId, text, + configurationId, entityTypes, tokenType, allowRegex, diff --git a/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsColumnMapping.java b/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsColumnMapping.java deleted file mode 100644 index 0f5d1fc2..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsColumnMapping.java +++ /dev/null @@ -1,194 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import org.jetbrains.annotations.NotNull; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = AdvancedOptionsColumnMapping.Builder.class) -public final class AdvancedOptionsColumnMapping { - private final String sessionId; - - private final String default_; - - private final Optional> entityColumnMap; - - private final Map additionalProperties; - - private AdvancedOptionsColumnMapping( - String sessionId, - String default_, - Optional> entityColumnMap, - Map additionalProperties) { - this.sessionId = sessionId; - this.default_ = default_; - this.entityColumnMap = entityColumnMap; - this.additionalProperties = additionalProperties; - } - - /** - * @return Table name of the vault. - */ - @JsonProperty("session_id") - public String getSessionId() { - return sessionId; - } - - /** - * @return Name of column to store data in when no explicit mapping exists. - */ - @JsonProperty("default") - public String getDefault() { - return default_; - } - - /** - * @return Column mapping for different entities. - */ - @JsonProperty("entity_column_map") - public Optional> getEntityColumnMap() { - return entityColumnMap; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof AdvancedOptionsColumnMapping && equalTo((AdvancedOptionsColumnMapping) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(AdvancedOptionsColumnMapping other) { - return sessionId.equals(other.sessionId) - && default_.equals(other.default_) - && entityColumnMap.equals(other.entityColumnMap); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.sessionId, this.default_, this.entityColumnMap); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static SessionIdStage builder() { - return new Builder(); - } - - public interface SessionIdStage { - /** - * Table name of the vault. - */ - DefaultStage sessionId(@NotNull String sessionId); - - Builder from(AdvancedOptionsColumnMapping other); - } - - public interface DefaultStage { - /** - * Name of column to store data in when no explicit mapping exists. - */ - _FinalStage default_(@NotNull String default_); - } - - public interface _FinalStage { - AdvancedOptionsColumnMapping build(); - - /** - *

Column mapping for different entities.

- */ - _FinalStage entityColumnMap(Optional> entityColumnMap); - - _FinalStage entityColumnMap(List entityColumnMap); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements SessionIdStage, DefaultStage, _FinalStage { - private String sessionId; - - private String default_; - - private Optional> entityColumnMap = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @java.lang.Override - public Builder from(AdvancedOptionsColumnMapping other) { - sessionId(other.getSessionId()); - default_(other.getDefault()); - entityColumnMap(other.getEntityColumnMap()); - return this; - } - - /** - * Table name of the vault.

Table name of the vault.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - @JsonSetter("session_id") - public DefaultStage sessionId(@NotNull String sessionId) { - this.sessionId = Objects.requireNonNull(sessionId, "sessionId must not be null"); - return this; - } - - /** - * Name of column to store data in when no explicit mapping exists.

Name of column to store data in when no explicit mapping exists.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - @JsonSetter("default") - public _FinalStage default_(@NotNull String default_) { - this.default_ = Objects.requireNonNull(default_, "default_ must not be null"); - return this; - } - - /** - *

Column mapping for different entities.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage entityColumnMap(List entityColumnMap) { - this.entityColumnMap = Optional.ofNullable(entityColumnMap); - return this; - } - - /** - *

Column mapping for different entities.

- */ - @java.lang.Override - @JsonSetter(value = "entity_column_map", nulls = Nulls.SKIP) - public _FinalStage entityColumnMap(Optional> entityColumnMap) { - this.entityColumnMap = entityColumnMap; - return this; - } - - @java.lang.Override - public AdvancedOptionsColumnMapping build() { - return new AdvancedOptionsColumnMapping(sessionId, default_, entityColumnMap, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsEntityColumnMap.java b/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsEntityColumnMap.java deleted file mode 100644 index 3df03da3..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsEntityColumnMap.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = AdvancedOptionsEntityColumnMap.Builder.class) -public final class AdvancedOptionsEntityColumnMap { - private final Optional entityType; - - private final Optional columnName; - - private final Map additionalProperties; - - private AdvancedOptionsEntityColumnMap( - Optional entityType, - Optional columnName, - Map additionalProperties) { - this.entityType = entityType; - this.columnName = columnName; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("entity_type") - public Optional getEntityType() { - return entityType; - } - - /** - * @return Column name where the entity has to be stored. - */ - @JsonProperty("column_name") - public Optional getColumnName() { - return columnName; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof AdvancedOptionsEntityColumnMap && equalTo((AdvancedOptionsEntityColumnMap) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(AdvancedOptionsEntityColumnMap other) { - return entityType.equals(other.entityType) && columnName.equals(other.columnName); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.entityType, this.columnName); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional entityType = Optional.empty(); - - private Optional columnName = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(AdvancedOptionsEntityColumnMap other) { - entityType(other.getEntityType()); - columnName(other.getColumnName()); - return this; - } - - @JsonSetter(value = "entity_type", nulls = Nulls.SKIP) - public Builder entityType(Optional entityType) { - this.entityType = entityType; - return this; - } - - public Builder entityType(DetectDataEntities entityType) { - this.entityType = Optional.ofNullable(entityType); - return this; - } - - /** - *

Column name where the entity has to be stored.

- */ - @JsonSetter(value = "column_name", nulls = Nulls.SKIP) - public Builder columnName(Optional columnName) { - this.columnName = columnName; - return this; - } - - public Builder columnName(String columnName) { - this.columnName = Optional.ofNullable(columnName); - return this; - } - - public AdvancedOptionsEntityColumnMap build() { - return new AdvancedOptionsEntityColumnMap(entityType, columnName, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsVaultSchema.java b/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsVaultSchema.java deleted file mode 100644 index dcacb09f..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/AdvancedOptionsVaultSchema.java +++ /dev/null @@ -1,135 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import org.jetbrains.annotations.NotNull; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = AdvancedOptionsVaultSchema.Builder.class) -public final class AdvancedOptionsVaultSchema { - private final String tableName; - - private final AdvancedOptionsColumnMapping mapping; - - private final Map additionalProperties; - - private AdvancedOptionsVaultSchema( - String tableName, AdvancedOptionsColumnMapping mapping, Map additionalProperties) { - this.tableName = tableName; - this.mapping = mapping; - this.additionalProperties = additionalProperties; - } - - /** - * @return Table name of the vault. - */ - @JsonProperty("table_name") - public String getTableName() { - return tableName; - } - - @JsonProperty("mapping") - public AdvancedOptionsColumnMapping getMapping() { - return mapping; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof AdvancedOptionsVaultSchema && equalTo((AdvancedOptionsVaultSchema) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(AdvancedOptionsVaultSchema other) { - return tableName.equals(other.tableName) && mapping.equals(other.mapping); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.tableName, this.mapping); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static TableNameStage builder() { - return new Builder(); - } - - public interface TableNameStage { - /** - * Table name of the vault. - */ - MappingStage tableName(@NotNull String tableName); - - Builder from(AdvancedOptionsVaultSchema other); - } - - public interface MappingStage { - _FinalStage mapping(@NotNull AdvancedOptionsColumnMapping mapping); - } - - public interface _FinalStage { - AdvancedOptionsVaultSchema build(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements TableNameStage, MappingStage, _FinalStage { - private String tableName; - - private AdvancedOptionsColumnMapping mapping; - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @java.lang.Override - public Builder from(AdvancedOptionsVaultSchema other) { - tableName(other.getTableName()); - mapping(other.getMapping()); - return this; - } - - /** - * Table name of the vault.

Table name of the vault.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - @JsonSetter("table_name") - public MappingStage tableName(@NotNull String tableName) { - this.tableName = Objects.requireNonNull(tableName, "tableName must not be null"); - return this; - } - - @java.lang.Override - @JsonSetter("mapping") - public _FinalStage mapping(@NotNull AdvancedOptionsColumnMapping mapping) { - this.mapping = Objects.requireNonNull(mapping, "mapping must not be null"); - return this; - } - - @java.lang.Override - public AdvancedOptionsVaultSchema build() { - return new AdvancedOptionsVaultSchema(tableName, mapping, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/AudioConfigTranscriptionType.java b/src/main/java/com/skyflow/generated/rest/types/AudioConfigTranscriptionType.java deleted file mode 100644 index e9052d16..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/AudioConfigTranscriptionType.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum AudioConfigTranscriptionType { - NONE("none"), - - SKYFLOW_TRANSCRIPTION("skyflow_transcription"), - - AWS_TRANSCRIPTION("aws_transcription"), - - AWS_TRANSCRIPTION_DIARIZE("aws_transcription_diarize"), - - AWS_MEDICAL_TRANSCRIPTION("aws_medical_transcription"), - - AWS_MEDICAL_TRANSCRIPTION_DIARIZE("aws_medical_transcription_diarize"), - - AWS_TRANSCRIPTION_DIARIZE_JSON("aws_transcription_diarize_json"), - - DEEPGRAM_TRANSCRIPTION_DIARIZE("deepgram_transcription_diarize"), - - DEEPGRAM_TRANSCRIPTION_JSON("deepgram_transcription_json"), - - DEEPGRAM_WRAPPER("deepgram_wrapper"); - - private final String value; - - AudioConfigTranscriptionType(String value) { - this.value = value; - } - - @JsonValue - @java.lang.Override - public String toString() { - return this.value; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/CheckGuardrailsResponse.java b/src/main/java/com/skyflow/generated/rest/types/CheckGuardrailsResponse.java new file mode 100644 index 00000000..324cd1e6 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/CheckGuardrailsResponse.java @@ -0,0 +1,193 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = CheckGuardrailsResponse.Builder.class) +public final class CheckGuardrailsResponse { + private final Optional text; + + private final Optional toxicity; + + private final Optional deniedTopics; + + private final Optional validation; + + private final Map additionalProperties; + + private CheckGuardrailsResponse( + Optional text, + Optional toxicity, + Optional deniedTopics, + Optional validation, + Map additionalProperties) { + this.text = text; + this.toxicity = toxicity; + this.deniedTopics = deniedTopics; + this.validation = validation; + this.additionalProperties = additionalProperties; + } + + /** + * @return Text that was checked against guardrails. + */ + @JsonProperty("text") + public Optional getText() { + return text; + } + + /** + * @return Whether the text is toxic. + */ + @JsonProperty("toxicity") + public Optional getToxicity() { + return toxicity; + } + + /** + * @return Whether any denied topics were found. + */ + @JsonProperty("denied_topics") + public Optional getDeniedTopics() { + return deniedTopics; + } + + /** + * @return Validation result. + */ + @JsonProperty("validation") + public Optional getValidation() { + return validation; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof CheckGuardrailsResponse && equalTo((CheckGuardrailsResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(CheckGuardrailsResponse other) { + return text.equals(other.text) + && toxicity.equals(other.toxicity) + && deniedTopics.equals(other.deniedTopics) + && validation.equals(other.validation); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.text, this.toxicity, this.deniedTopics, this.validation); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional text = Optional.empty(); + + private Optional toxicity = Optional.empty(); + + private Optional deniedTopics = Optional.empty(); + + private Optional validation = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(CheckGuardrailsResponse other) { + text(other.getText()); + toxicity(other.getToxicity()); + deniedTopics(other.getDeniedTopics()); + validation(other.getValidation()); + return this; + } + + /** + *

Text that was checked against guardrails.

+ */ + @JsonSetter(value = "text", nulls = Nulls.SKIP) + public Builder text(Optional text) { + this.text = text; + return this; + } + + public Builder text(String text) { + this.text = Optional.ofNullable(text); + return this; + } + + /** + *

Whether the text is toxic.

+ */ + @JsonSetter(value = "toxicity", nulls = Nulls.SKIP) + public Builder toxicity(Optional toxicity) { + this.toxicity = toxicity; + return this; + } + + public Builder toxicity(Boolean toxicity) { + this.toxicity = Optional.ofNullable(toxicity); + return this; + } + + /** + *

Whether any denied topics were found.

+ */ + @JsonSetter(value = "denied_topics", nulls = Nulls.SKIP) + public Builder deniedTopics(Optional deniedTopics) { + this.deniedTopics = deniedTopics; + return this; + } + + public Builder deniedTopics(Boolean deniedTopics) { + this.deniedTopics = Optional.ofNullable(deniedTopics); + return this; + } + + /** + *

Validation result.

+ */ + @JsonSetter(value = "validation", nulls = Nulls.SKIP) + public Builder validation(Optional validation) { + this.validation = validation; + return this; + } + + public Builder validation(CheckGuardrailsResponseValidation validation) { + this.validation = Optional.ofNullable(validation); + return this; + } + + public CheckGuardrailsResponse build() { + return new CheckGuardrailsResponse(text, toxicity, deniedTopics, validation, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DetectFileRequestDataType.java b/src/main/java/com/skyflow/generated/rest/types/CheckGuardrailsResponseValidation.java similarity index 70% rename from src/main/java/com/skyflow/generated/rest/types/DetectFileRequestDataType.java rename to src/main/java/com/skyflow/generated/rest/types/CheckGuardrailsResponseValidation.java index e039bc86..2ff9edb8 100644 --- a/src/main/java/com/skyflow/generated/rest/types/DetectFileRequestDataType.java +++ b/src/main/java/com/skyflow/generated/rest/types/CheckGuardrailsResponseValidation.java @@ -5,14 +5,14 @@ import com.fasterxml.jackson.annotation.JsonValue; -public enum DetectFileRequestDataType { - UNKNOWN("UNKNOWN"), +public enum CheckGuardrailsResponseValidation { + FAILED("failed"), - BASE_64("BASE64"); + PASSED("passed"); private final String value; - DetectFileRequestDataType(String value) { + CheckGuardrailsResponseValidation(String value) { this.value = value; } diff --git a/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponse.java b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponse.java index 9f73e9ad..9beef0a2 100644 --- a/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponse.java +++ b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponse.java @@ -35,9 +35,9 @@ public final class DeidentifyStatusResponse { private final Optional characterCount; - private final Optional size; + private final Optional size; - private final Optional duration; + private final Optional duration; private final Optional pages; @@ -52,8 +52,8 @@ private DeidentifyStatusResponse( String message, Optional wordCount, Optional characterCount, - Optional size, - Optional duration, + Optional size, + Optional duration, Optional pages, Optional slides, Map additionalProperties) { @@ -122,7 +122,7 @@ public Optional getCharacterCount() { * @return Size of the processed text in kilobytes (KB). */ @JsonProperty("size") - public Optional getSize() { + public Optional getSize() { return size; } @@ -130,7 +130,7 @@ public Optional getSize() { * @return Duration of the processed audio in seconds. */ @JsonProperty("duration") - public Optional getDuration() { + public Optional getDuration() { return duration; } @@ -250,16 +250,16 @@ public interface _FinalStage { /** *

Size of the processed text in kilobytes (KB).

*/ - _FinalStage size(Optional size); + _FinalStage size(Optional size); - _FinalStage size(Integer size); + _FinalStage size(Double size); /** *

Duration of the processed audio in seconds.

*/ - _FinalStage duration(Optional duration); + _FinalStage duration(Optional duration); - _FinalStage duration(Integer duration); + _FinalStage duration(Double duration); /** *

Number of pages in the processed PDF.

@@ -288,9 +288,9 @@ public static final class Builder implements StatusStage, OutputTypeStage, Messa private Optional pages = Optional.empty(); - private Optional duration = Optional.empty(); + private Optional duration = Optional.empty(); - private Optional size = Optional.empty(); + private Optional size = Optional.empty(); private Optional characterCount = Optional.empty(); @@ -396,7 +396,7 @@ public _FinalStage pages(Optional pages) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage duration(Integer duration) { + public _FinalStage duration(Double duration) { this.duration = Optional.ofNullable(duration); return this; } @@ -406,7 +406,7 @@ public _FinalStage duration(Integer duration) { */ @java.lang.Override @JsonSetter(value = "duration", nulls = Nulls.SKIP) - public _FinalStage duration(Optional duration) { + public _FinalStage duration(Optional duration) { this.duration = duration; return this; } @@ -416,7 +416,7 @@ public _FinalStage duration(Optional duration) { * @return Reference to {@code this} so that method calls can be chained together. */ @java.lang.Override - public _FinalStage size(Integer size) { + public _FinalStage size(Double size) { this.size = Optional.ofNullable(size); return this; } @@ -426,7 +426,7 @@ public _FinalStage size(Integer size) { */ @java.lang.Override @JsonSetter(value = "size", nulls = Nulls.SKIP) - public _FinalStage size(Optional size) { + public _FinalStage size(Optional size) { this.size = size; return this; } diff --git a/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseOutputType.java b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseOutputType.java index 547bf414..4db4d813 100644 --- a/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseOutputType.java +++ b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseOutputType.java @@ -8,8 +8,6 @@ public enum DeidentifyStatusResponseOutputType { BASE_64("BASE64"), - EFS_PATH("EFS_PATH"), - UNKNOWN("UNKNOWN"); private final String value; diff --git a/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseStatus.java b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseStatus.java index 4e51e5cf..f03db2ed 100644 --- a/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseStatus.java +++ b/src/main/java/com/skyflow/generated/rest/types/DeidentifyStatusResponseStatus.java @@ -10,7 +10,9 @@ public enum DeidentifyStatusResponseStatus { IN_PROGRESS("IN_PROGRESS"), - SUCCESS("SUCCESS"); + SUCCESS("SUCCESS"), + + UNKNOWN("UNKNOWN"); private final String value; diff --git a/src/main/java/com/skyflow/generated/rest/types/DetectDataAccuracy.java b/src/main/java/com/skyflow/generated/rest/types/DetectDataAccuracy.java deleted file mode 100644 index 64afed64..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/DetectDataAccuracy.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DetectDataAccuracy { - UNKNOWN("unknown"), - - STANDARD("standard"), - - STANDARD_PLUS("standard_plus"), - - STANDARD_PLUS_MULTILINGUAL("standard_plus_multilingual"), - - STANDARD_PLUS_AUTOMATIC("standard_plus_automatic"), - - HIGH("high"), - - HIGH_MULTILINGUAL("high_multilingual"), - - HIGH_AUTOMATIC("high_automatic"); - - private final String value; - - DetectDataAccuracy(String value) { - this.value = value; - } - - @JsonValue - @java.lang.Override - public String toString() { - return this.value; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/DetectDataEntities.java b/src/main/java/com/skyflow/generated/rest/types/DetectDataEntities.java deleted file mode 100644 index d655bb64..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/DetectDataEntities.java +++ /dev/null @@ -1,146 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DetectDataEntities { - AGE("age"), - - BANK_ACCOUNT("bank_account"), - - CREDIT_CARD("credit_card"), - - CREDIT_CARD_EXPIRATION("credit_card_expiration"), - - CVV("cvv"), - - DATE("date"), - - DATE_INTERVAL("date_interval"), - - DOB("dob"), - - DRIVER_LICENSE("driver_license"), - - EMAIL_ADDRESS("email_address"), - - HEALTHCARE_NUMBER("healthcare_number"), - - IP_ADDRESS("ip_address"), - - LOCATION("location"), - - NAME("name"), - - NUMERICAL_PII("numerical_pii"), - - PHONE_NUMBER("phone_number"), - - SSN("ssn"), - - URL("url"), - - VEHICLE_ID("vehicle_id"), - - MEDICAL_CODE("medical_code"), - - NAME_FAMILY("name_family"), - - NAME_GIVEN("name_given"), - - ACCOUNT_NUMBER("account_number"), - - EVENT("event"), - - FILENAME("filename"), - - GENDER_SEXUALITY("gender_sexuality"), - - LANGUAGE("language"), - - LOCATION_ADDRESS("location_address"), - - LOCATION_CITY("location_city"), - - LOCATION_COORDINATE("location_coordinate"), - - LOCATION_COUNTRY("location_country"), - - LOCATION_STATE("location_state"), - - LOCATION_ZIP("location_zip"), - - MARITAL_STATUS("marital_status"), - - MONEY("money"), - - NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), - - OCCUPATION("occupation"), - - ORGANIZATION("organization"), - - ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), - - ORIGIN("origin"), - - PASSPORT_NUMBER("passport_number"), - - PASSWORD("password"), - - PHYSICAL_ATTRIBUTE("physical_attribute"), - - POLITICAL_AFFILIATION("political_affiliation"), - - RELIGION("religion"), - - TIME("time"), - - USERNAME("username"), - - ZODIAC_SIGN("zodiac_sign"), - - BLOOD_TYPE("blood_type"), - - CONDITION("condition"), - - DOSE("dose"), - - DRUG("drug"), - - INJURY("injury"), - - MEDICAL_PROCESS("medical_process"), - - STATISTICS("statistics"), - - ROUTING_NUMBER("routing_number"), - - CORPORATE_ACTION("corporate_action"), - - FINANCIAL_METRIC("financial_metric"), - - PRODUCT("product"), - - TREND("trend"), - - DURATION("duration"), - - LOCATION_ADDRESS_STREET("location_address_street"), - - ALL("all"); - - private final String value; - - DetectDataEntities(String value) { - this.value = value; - } - - @JsonValue - @java.lang.Override - public String toString() { - return this.value; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/EntityType.java b/src/main/java/com/skyflow/generated/rest/types/EntityType.java index 605282ed..e6dcf699 100644 --- a/src/main/java/com/skyflow/generated/rest/types/EntityType.java +++ b/src/main/java/com/skyflow/generated/rest/types/EntityType.java @@ -30,6 +30,8 @@ public enum EntityType { DATE_INTERVAL("date_interval"), + DAY("day"), + DOB("dob"), DOSE("dose"), @@ -40,6 +42,8 @@ public enum EntityType { DURATION("duration"), + EFFECT("effect"), + EMAIL_ADDRESS("email_address"), EVENT("event"), @@ -48,7 +52,7 @@ public enum EntityType { FINANCIAL_METRIC("financial_metric"), - GENDER_SEXUALITY("gender_sexuality"), + GENDER("gender"), HEALTHCARE_NUMBER("healthcare_number"), @@ -82,6 +86,8 @@ public enum EntityType { MONEY("money"), + MONTH("month"), + NAME("name"), NAME_FAMILY("name_family"), @@ -96,6 +102,8 @@ public enum EntityType { ORGANIZATION("organization"), + ORGANIZATION_ID("organization_id"), + ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), ORIGIN("origin"), @@ -112,10 +120,14 @@ public enum EntityType { PRODUCT("product"), + PROJECT("project"), + RELIGION("religion"), ROUTING_NUMBER("routing_number"), + SEXUALITY("sexuality"), + SSN("ssn"), STATISTICS("statistics"), @@ -130,6 +142,8 @@ public enum EntityType { VEHICLE_ID("vehicle_id"), + YEAR("year"), + ZODIAC_SIGN("zodiac_sign"); private final String value; diff --git a/src/main/java/com/skyflow/generated/rest/types/ProcessedFileOutputProcessedFileType.java b/src/main/java/com/skyflow/generated/rest/types/ProcessedFileOutputProcessedFileType.java deleted file mode 100644 index 0563503c..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/ProcessedFileOutputProcessedFileType.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum ProcessedFileOutputProcessedFileType { - NONE("none"), - - REDACTED_AUDIO("redacted_audio"), - - REDACTED_IMAGE("redacted_image"), - - REDACTED_TRANSCRIPTION("redacted_transcription"), - - REDACTED_FILE("redacted_file"), - - REDACTED_TEXT("redacted_text"), - - ENTITIES("entities"), - - REDACTED_AWS_TRANSCRIPTION_DIARIZE_JSON("redacted_aws_transcription_diarize_json"), - - REDACTED_DEEPGRAM_TRANSCRIPTION_DIARIZE_JSON("redacted_deepgram_transcription_diarize_json"), - - PLAINTEXT_TRANSCRIBED("plaintext_transcribed"); - - private final String value; - - ProcessedFileOutputProcessedFileType(String value) { - this.value = value; - } - - @JsonValue - @java.lang.Override - public String toString() { - return this.value; - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponse.java b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponse.java new file mode 100644 index 00000000..46804db0 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponse.java @@ -0,0 +1,170 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyFileResponse.Builder.class) +public final class ReidentifyFileResponse { + private final ReidentifyFileResponseStatus status; + + private final ReidentifyFileResponseOutputType outputType; + + private final ReidentifyFileResponseOutput output; + + private final Map additionalProperties; + + private ReidentifyFileResponse( + ReidentifyFileResponseStatus status, + ReidentifyFileResponseOutputType outputType, + ReidentifyFileResponseOutput output, + Map additionalProperties) { + this.status = status; + this.outputType = outputType; + this.output = output; + this.additionalProperties = additionalProperties; + } + + /** + * @return Status of the re-identify operation. + */ + @JsonProperty("status") + public ReidentifyFileResponseStatus getStatus() { + return status; + } + + /** + * @return Format of the output file. + */ + @JsonProperty("output_type") + public ReidentifyFileResponseOutputType getOutputType() { + return outputType; + } + + @JsonProperty("output") + public ReidentifyFileResponseOutput getOutput() { + return output; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyFileResponse && equalTo((ReidentifyFileResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyFileResponse other) { + return status.equals(other.status) && outputType.equals(other.outputType) && output.equals(other.output); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.status, this.outputType, this.output); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static StatusStage builder() { + return new Builder(); + } + + public interface StatusStage { + /** + * Status of the re-identify operation. + */ + OutputTypeStage status(@NotNull ReidentifyFileResponseStatus status); + + Builder from(ReidentifyFileResponse other); + } + + public interface OutputTypeStage { + /** + * Format of the output file. + */ + OutputStage outputType(@NotNull ReidentifyFileResponseOutputType outputType); + } + + public interface OutputStage { + _FinalStage output(@NotNull ReidentifyFileResponseOutput output); + } + + public interface _FinalStage { + ReidentifyFileResponse build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements StatusStage, OutputTypeStage, OutputStage, _FinalStage { + private ReidentifyFileResponseStatus status; + + private ReidentifyFileResponseOutputType outputType; + + private ReidentifyFileResponseOutput output; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ReidentifyFileResponse other) { + status(other.getStatus()); + outputType(other.getOutputType()); + output(other.getOutput()); + return this; + } + + /** + * Status of the re-identify operation.

Status of the re-identify operation.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("status") + public OutputTypeStage status(@NotNull ReidentifyFileResponseStatus status) { + this.status = Objects.requireNonNull(status, "status must not be null"); + return this; + } + + /** + * Format of the output file.

Format of the output file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("output_type") + public OutputStage outputType(@NotNull ReidentifyFileResponseOutputType outputType) { + this.outputType = Objects.requireNonNull(outputType, "outputType must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("output") + public _FinalStage output(@NotNull ReidentifyFileResponseOutput output) { + this.output = Objects.requireNonNull(output, "output must not be null"); + return this; + } + + @java.lang.Override + public ReidentifyFileResponse build() { + return new ReidentifyFileResponse(status, outputType, output, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseOutput.java b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseOutput.java new file mode 100644 index 00000000..266a9475 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseOutput.java @@ -0,0 +1,154 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyFileResponseOutput.Builder.class) +public final class ReidentifyFileResponseOutput { + private final String processedFile; + + private final String processedFileExtension; + + private final Map additionalProperties; + + private ReidentifyFileResponseOutput( + String processedFile, String processedFileExtension, Map additionalProperties) { + this.processedFile = processedFile; + this.processedFileExtension = processedFileExtension; + this.additionalProperties = additionalProperties; + } + + /** + * @return Re-identified file content in base64 format. + */ + @JsonProperty("processed_file") + public String getProcessedFile() { + return processedFile; + } + + /** + * @return Type of the processed file. + */ + @JsonProperty("processed_file_type") + public String getProcessedFileType() { + return "reidentified_file"; + } + + /** + * @return Extension of the processed file. + */ + @JsonProperty("processed_file_extension") + public String getProcessedFileExtension() { + return processedFileExtension; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyFileResponseOutput && equalTo((ReidentifyFileResponseOutput) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyFileResponseOutput other) { + return processedFile.equals(other.processedFile) && processedFileExtension.equals(other.processedFileExtension); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.processedFile, this.processedFileExtension); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static ProcessedFileStage builder() { + return new Builder(); + } + + public interface ProcessedFileStage { + /** + * Re-identified file content in base64 format. + */ + ProcessedFileExtensionStage processedFile(@NotNull String processedFile); + + Builder from(ReidentifyFileResponseOutput other); + } + + public interface ProcessedFileExtensionStage { + /** + * Extension of the processed file. + */ + _FinalStage processedFileExtension(@NotNull String processedFileExtension); + } + + public interface _FinalStage { + ReidentifyFileResponseOutput build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements ProcessedFileStage, ProcessedFileExtensionStage, _FinalStage { + private String processedFile; + + private String processedFileExtension; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ReidentifyFileResponseOutput other) { + processedFile(other.getProcessedFile()); + processedFileExtension(other.getProcessedFileExtension()); + return this; + } + + /** + * Re-identified file content in base64 format.

Re-identified file content in base64 format.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("processed_file") + public ProcessedFileExtensionStage processedFile(@NotNull String processedFile) { + this.processedFile = Objects.requireNonNull(processedFile, "processedFile must not be null"); + return this; + } + + /** + * Extension of the processed file.

Extension of the processed file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("processed_file_extension") + public _FinalStage processedFileExtension(@NotNull String processedFileExtension) { + this.processedFileExtension = + Objects.requireNonNull(processedFileExtension, "processedFileExtension must not be null"); + return this; + } + + @java.lang.Override + public ReidentifyFileResponseOutput build() { + return new ReidentifyFileResponseOutput(processedFile, processedFileExtension, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DetectRequestDeidentifyOption.java b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseOutputType.java similarity index 63% rename from src/main/java/com/skyflow/generated/rest/types/DetectRequestDeidentifyOption.java rename to src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseOutputType.java index bdc82ccf..167cb387 100644 --- a/src/main/java/com/skyflow/generated/rest/types/DetectRequestDeidentifyOption.java +++ b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseOutputType.java @@ -5,16 +5,14 @@ import com.fasterxml.jackson.annotation.JsonValue; -public enum DetectRequestDeidentifyOption { - UNKNOWN("UNKNOWN"), +public enum ReidentifyFileResponseOutputType { + BASE_64("BASE64"), - ENTITY_UNQ_COUNTER("ENTITY_UNQ_COUNTER"), - - ENTITY_ONLY("ENTITY_ONLY"); + UNKNOWN("UNKNOWN"); private final String value; - DetectRequestDeidentifyOption(String value) { + ReidentifyFileResponseOutputType(String value) { this.value = value; } diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponseStatus.java b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseStatus.java similarity index 72% rename from src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponseStatus.java rename to src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseStatus.java index c819b167..7b56adcf 100644 --- a/src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponseStatus.java +++ b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseStatus.java @@ -5,18 +5,18 @@ import com.fasterxml.jackson.annotation.JsonValue; -public enum V1DetectStatusResponseStatus { - UNKNOWN("UNKNOWN"), - +public enum ReidentifyFileResponseStatus { FAILED("FAILED"), + IN_PROGRESS("IN_PROGRESS"), + SUCCESS("SUCCESS"), - IN_PROGRESS("IN_PROGRESS"); + UNKNOWN("UNKNOWN"); private final String value; - V1DetectStatusResponseStatus(String value) { + ReidentifyFileResponseStatus(String value) { this.value = value; } diff --git a/src/main/java/com/skyflow/generated/rest/types/UploadFileV2Response.java b/src/main/java/com/skyflow/generated/rest/types/UploadFileV2Response.java new file mode 100644 index 00000000..85f98bd1 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/UploadFileV2Response.java @@ -0,0 +1,124 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = UploadFileV2Response.Builder.class) +public final class UploadFileV2Response { + private final Optional skyflowId; + + private final Optional fileMetadata; + + private final Map additionalProperties; + + private UploadFileV2Response( + Optional skyflowId, Optional fileMetadata, Map additionalProperties) { + this.skyflowId = skyflowId; + this.fileMetadata = fileMetadata; + this.additionalProperties = additionalProperties; + } + + /** + * @return Skyflow ID of the record the file was uploaded to. + */ + @JsonProperty("skyflowID") + public Optional getSkyflowId() { + return skyflowId; + } + + @JsonProperty("fileMetadata") + public Optional getFileMetadata() { + return fileMetadata; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof UploadFileV2Response && equalTo((UploadFileV2Response) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(UploadFileV2Response other) { + return skyflowId.equals(other.skyflowId) && fileMetadata.equals(other.fileMetadata); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.skyflowId, this.fileMetadata); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional skyflowId = Optional.empty(); + + private Optional fileMetadata = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(UploadFileV2Response other) { + skyflowId(other.getSkyflowId()); + fileMetadata(other.getFileMetadata()); + return this; + } + + /** + *

Skyflow ID of the record the file was uploaded to.

+ */ + @JsonSetter(value = "skyflowID", nulls = Nulls.SKIP) + public Builder skyflowId(Optional skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + public Builder skyflowId(String skyflowId) { + this.skyflowId = Optional.ofNullable(skyflowId); + return this; + } + + @JsonSetter(value = "fileMetadata", nulls = Nulls.SKIP) + public Builder fileMetadata(Optional fileMetadata) { + this.fileMetadata = fileMetadata; + return this; + } + + public Builder fileMetadata(Object fileMetadata) { + this.fileMetadata = Optional.ofNullable(fileMetadata); + return this; + } + + public UploadFileV2Response build() { + return new UploadFileV2Response(skyflowId, fileMetadata, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1AdvancedOptions.java b/src/main/java/com/skyflow/generated/rest/types/V1AdvancedOptions.java deleted file mode 100644 index 999153e4..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/V1AdvancedOptions.java +++ /dev/null @@ -1,157 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1AdvancedOptions.Builder.class) -public final class V1AdvancedOptions { - private final Optional dateShift; - - private final Optional customClient; - - private final Optional schema; - - private final Map additionalProperties; - - private V1AdvancedOptions( - Optional dateShift, - Optional customClient, - Optional schema, - Map additionalProperties) { - this.dateShift = dateShift; - this.customClient = customClient; - this.schema = schema; - this.additionalProperties = additionalProperties; - } - - /** - * @return No. of days by which original date has to be shifted to. - */ - @JsonProperty("date_shift") - public Optional getDateShift() { - return dateShift; - } - - /** - * @return Custom client specific logic. - */ - @JsonProperty("custom_client") - public Optional getCustomClient() { - return customClient; - } - - @JsonProperty("schema") - public Optional getSchema() { - return schema; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1AdvancedOptions && equalTo((V1AdvancedOptions) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1AdvancedOptions other) { - return dateShift.equals(other.dateShift) - && customClient.equals(other.customClient) - && schema.equals(other.schema); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.dateShift, this.customClient, this.schema); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional dateShift = Optional.empty(); - - private Optional customClient = Optional.empty(); - - private Optional schema = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1AdvancedOptions other) { - dateShift(other.getDateShift()); - customClient(other.getCustomClient()); - schema(other.getSchema()); - return this; - } - - /** - *

No. of days by which original date has to be shifted to.

- */ - @JsonSetter(value = "date_shift", nulls = Nulls.SKIP) - public Builder dateShift(Optional dateShift) { - this.dateShift = dateShift; - return this; - } - - public Builder dateShift(Integer dateShift) { - this.dateShift = Optional.ofNullable(dateShift); - return this; - } - - /** - *

Custom client specific logic.

- */ - @JsonSetter(value = "custom_client", nulls = Nulls.SKIP) - public Builder customClient(Optional customClient) { - this.customClient = customClient; - return this; - } - - public Builder customClient(Boolean customClient) { - this.customClient = Optional.ofNullable(customClient); - return this; - } - - @JsonSetter(value = "schema", nulls = Nulls.SKIP) - public Builder schema(Optional schema) { - this.schema = schema; - return this; - } - - public Builder schema(AdvancedOptionsVaultSchema schema) { - this.schema = Optional.ofNullable(schema); - return this; - } - - public V1AdvancedOptions build() { - return new V1AdvancedOptions(dateShift, customClient, schema, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1AudioConfig.java b/src/main/java/com/skyflow/generated/rest/types/V1AudioConfig.java deleted file mode 100644 index 50e5508a..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/V1AudioConfig.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1AudioConfig.Builder.class) -public final class V1AudioConfig { - private final Optional outputTranscription; - - private final Optional outputProcessedAudio; - - private final Optional options; - - private final Map additionalProperties; - - private V1AudioConfig( - Optional outputTranscription, - Optional outputProcessedAudio, - Optional options, - Map additionalProperties) { - this.outputTranscription = outputTranscription; - this.outputProcessedAudio = outputProcessedAudio; - this.options = options; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("output_transcription") - public Optional getOutputTranscription() { - return outputTranscription; - } - - /** - * @return If true, includes processed audio file in the response. - */ - @JsonProperty("output_processed_audio") - public Optional getOutputProcessedAudio() { - return outputProcessedAudio; - } - - @JsonProperty("options") - public Optional getOptions() { - return options; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1AudioConfig && equalTo((V1AudioConfig) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1AudioConfig other) { - return outputTranscription.equals(other.outputTranscription) - && outputProcessedAudio.equals(other.outputProcessedAudio) - && options.equals(other.options); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.outputTranscription, this.outputProcessedAudio, this.options); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional outputTranscription = Optional.empty(); - - private Optional outputProcessedAudio = Optional.empty(); - - private Optional options = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1AudioConfig other) { - outputTranscription(other.getOutputTranscription()); - outputProcessedAudio(other.getOutputProcessedAudio()); - options(other.getOptions()); - return this; - } - - @JsonSetter(value = "output_transcription", nulls = Nulls.SKIP) - public Builder outputTranscription(Optional outputTranscription) { - this.outputTranscription = outputTranscription; - return this; - } - - public Builder outputTranscription(AudioConfigTranscriptionType outputTranscription) { - this.outputTranscription = Optional.ofNullable(outputTranscription); - return this; - } - - /** - *

If true, includes processed audio file in the response.

- */ - @JsonSetter(value = "output_processed_audio", nulls = Nulls.SKIP) - public Builder outputProcessedAudio(Optional outputProcessedAudio) { - this.outputProcessedAudio = outputProcessedAudio; - return this; - } - - public Builder outputProcessedAudio(Boolean outputProcessedAudio) { - this.outputProcessedAudio = Optional.ofNullable(outputProcessedAudio); - return this; - } - - @JsonSetter(value = "options", nulls = Nulls.SKIP) - public Builder options(Optional options) { - this.options = options; - return this; - } - - public Builder options(V1AudioOptions options) { - this.options = Optional.ofNullable(options); - return this; - } - - public V1AudioConfig build() { - return new V1AudioConfig(outputTranscription, outputProcessedAudio, options, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1AudioOptions.java b/src/main/java/com/skyflow/generated/rest/types/V1AudioOptions.java deleted file mode 100644 index d71b77a0..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/V1AudioOptions.java +++ /dev/null @@ -1,234 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1AudioOptions.Builder.class) -public final class V1AudioOptions { - private final Optional bleepStartPadding; - - private final Optional bleepEndPadding; - - private final Optional distortionSteps; - - private final Optional bleepFrequency; - - private final Optional bleepGain; - - private final Map additionalProperties; - - private V1AudioOptions( - Optional bleepStartPadding, - Optional bleepEndPadding, - Optional distortionSteps, - Optional bleepFrequency, - Optional bleepGain, - Map additionalProperties) { - this.bleepStartPadding = bleepStartPadding; - this.bleepEndPadding = bleepEndPadding; - this.distortionSteps = distortionSteps; - this.bleepFrequency = bleepFrequency; - this.bleepGain = bleepGain; - this.additionalProperties = additionalProperties; - } - - /** - * @return Padding added to the beginning of a bleep, in seconds. - */ - @JsonProperty("bleep_start_padding") - public Optional getBleepStartPadding() { - return bleepStartPadding; - } - - /** - * @return Padding added to the end of a bleep, in seconds. - */ - @JsonProperty("bleep_end_padding") - public Optional getBleepEndPadding() { - return bleepEndPadding; - } - - /** - * @return Specifies how the distortion will be made. Providing a number more than 0 will result in a higher tone and a coefficient less than 0 will result in a lower tone. - */ - @JsonProperty("distortion_steps") - public Optional getDistortionSteps() { - return distortionSteps; - } - - /** - * @return This parameter configures the frequency of the sine wave used for the bleep sound in an audio segment. - */ - @JsonProperty("bleep_frequency") - public Optional getBleepFrequency() { - return bleepFrequency; - } - - /** - * @return It controls the relative loudness of the bleep,positive values increase its loudness, and negative values decrease it. - */ - @JsonProperty("bleep_gain") - public Optional getBleepGain() { - return bleepGain; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1AudioOptions && equalTo((V1AudioOptions) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1AudioOptions other) { - return bleepStartPadding.equals(other.bleepStartPadding) - && bleepEndPadding.equals(other.bleepEndPadding) - && distortionSteps.equals(other.distortionSteps) - && bleepFrequency.equals(other.bleepFrequency) - && bleepGain.equals(other.bleepGain); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash( - this.bleepStartPadding, - this.bleepEndPadding, - this.distortionSteps, - this.bleepFrequency, - this.bleepGain); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional bleepStartPadding = Optional.empty(); - - private Optional bleepEndPadding = Optional.empty(); - - private Optional distortionSteps = Optional.empty(); - - private Optional bleepFrequency = Optional.empty(); - - private Optional bleepGain = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1AudioOptions other) { - bleepStartPadding(other.getBleepStartPadding()); - bleepEndPadding(other.getBleepEndPadding()); - distortionSteps(other.getDistortionSteps()); - bleepFrequency(other.getBleepFrequency()); - bleepGain(other.getBleepGain()); - return this; - } - - /** - *

Padding added to the beginning of a bleep, in seconds.

- */ - @JsonSetter(value = "bleep_start_padding", nulls = Nulls.SKIP) - public Builder bleepStartPadding(Optional bleepStartPadding) { - this.bleepStartPadding = bleepStartPadding; - return this; - } - - public Builder bleepStartPadding(Float bleepStartPadding) { - this.bleepStartPadding = Optional.ofNullable(bleepStartPadding); - return this; - } - - /** - *

Padding added to the end of a bleep, in seconds.

- */ - @JsonSetter(value = "bleep_end_padding", nulls = Nulls.SKIP) - public Builder bleepEndPadding(Optional bleepEndPadding) { - this.bleepEndPadding = bleepEndPadding; - return this; - } - - public Builder bleepEndPadding(Float bleepEndPadding) { - this.bleepEndPadding = Optional.ofNullable(bleepEndPadding); - return this; - } - - /** - *

Specifies how the distortion will be made. Providing a number more than 0 will result in a higher tone and a coefficient less than 0 will result in a lower tone.

- */ - @JsonSetter(value = "distortion_steps", nulls = Nulls.SKIP) - public Builder distortionSteps(Optional distortionSteps) { - this.distortionSteps = distortionSteps; - return this; - } - - public Builder distortionSteps(Integer distortionSteps) { - this.distortionSteps = Optional.ofNullable(distortionSteps); - return this; - } - - /** - *

This parameter configures the frequency of the sine wave used for the bleep sound in an audio segment.

- */ - @JsonSetter(value = "bleep_frequency", nulls = Nulls.SKIP) - public Builder bleepFrequency(Optional bleepFrequency) { - this.bleepFrequency = bleepFrequency; - return this; - } - - public Builder bleepFrequency(Integer bleepFrequency) { - this.bleepFrequency = Optional.ofNullable(bleepFrequency); - return this; - } - - /** - *

It controls the relative loudness of the bleep,positive values increase its loudness, and negative values decrease it.

- */ - @JsonSetter(value = "bleep_gain", nulls = Nulls.SKIP) - public Builder bleepGain(Optional bleepGain) { - this.bleepGain = bleepGain; - return this; - } - - public Builder bleepGain(Integer bleepGain) { - this.bleepGain = Optional.ofNullable(bleepGain); - return this; - } - - public V1AudioOptions build() { - return new V1AudioOptions( - bleepStartPadding, - bleepEndPadding, - distortionSteps, - bleepFrequency, - bleepGain, - additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DetectFileResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1DetectFileResponse.java deleted file mode 100644 index 0c309cb9..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/V1DetectFileResponse.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1DetectFileResponse.Builder.class) -public final class V1DetectFileResponse { - private final Optional statusUrl; - - private final Map additionalProperties; - - private V1DetectFileResponse(Optional statusUrl, Map additionalProperties) { - this.statusUrl = statusUrl; - this.additionalProperties = additionalProperties; - } - - /** - * @return Status URL for the deidentification request. - */ - @JsonProperty("status_url") - public Optional getStatusUrl() { - return statusUrl; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1DetectFileResponse && equalTo((V1DetectFileResponse) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1DetectFileResponse other) { - return statusUrl.equals(other.statusUrl); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.statusUrl); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional statusUrl = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1DetectFileResponse other) { - statusUrl(other.getStatusUrl()); - return this; - } - - /** - *

Status URL for the deidentification request.

- */ - @JsonSetter(value = "status_url", nulls = Nulls.SKIP) - public Builder statusUrl(Optional statusUrl) { - this.statusUrl = statusUrl; - return this; - } - - public Builder statusUrl(String statusUrl) { - this.statusUrl = Optional.ofNullable(statusUrl); - return this; - } - - public V1DetectFileResponse build() { - return new V1DetectFileResponse(statusUrl, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponse.java deleted file mode 100644 index 95e7845c..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/V1DetectStatusResponse.java +++ /dev/null @@ -1,156 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1DetectStatusResponse.Builder.class) -public final class V1DetectStatusResponse { - private final Optional status; - - private final Optional> output; - - private final Optional message; - - private final Map additionalProperties; - - private V1DetectStatusResponse( - Optional status, - Optional> output, - Optional message, - Map additionalProperties) { - this.status = status; - this.output = output; - this.message = message; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("status") - public Optional getStatus() { - return status; - } - - /** - * @return How the input file was specified. - */ - @JsonProperty("output") - public Optional> getOutput() { - return output; - } - - /** - * @return Status details about the deidentification request. - */ - @JsonProperty("message") - public Optional getMessage() { - return message; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1DetectStatusResponse && equalTo((V1DetectStatusResponse) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1DetectStatusResponse other) { - return status.equals(other.status) && output.equals(other.output) && message.equals(other.message); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.status, this.output, this.message); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional status = Optional.empty(); - - private Optional> output = Optional.empty(); - - private Optional message = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1DetectStatusResponse other) { - status(other.getStatus()); - output(other.getOutput()); - message(other.getMessage()); - return this; - } - - @JsonSetter(value = "status", nulls = Nulls.SKIP) - public Builder status(Optional status) { - this.status = status; - return this; - } - - public Builder status(V1DetectStatusResponseStatus status) { - this.status = Optional.ofNullable(status); - return this; - } - - /** - *

How the input file was specified.

- */ - @JsonSetter(value = "output", nulls = Nulls.SKIP) - public Builder output(Optional> output) { - this.output = output; - return this; - } - - public Builder output(List output) { - this.output = Optional.ofNullable(output); - return this; - } - - /** - *

Status details about the deidentification request.

- */ - @JsonSetter(value = "message", nulls = Nulls.SKIP) - public Builder message(Optional message) { - this.message = message; - return this; - } - - public Builder message(String message) { - this.message = Optional.ofNullable(message); - return this; - } - - public V1DetectStatusResponse build() { - return new V1DetectStatusResponse(status, output, message, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DetectTextRequest.java b/src/main/java/com/skyflow/generated/rest/types/V1DetectTextRequest.java deleted file mode 100644 index 57778d80..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/V1DetectTextRequest.java +++ /dev/null @@ -1,522 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import org.jetbrains.annotations.NotNull; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1DetectTextRequest.Builder.class) -public final class V1DetectTextRequest { - private final String text; - - private final String vaultId; - - private final Optional sessionId; - - private final Optional> restrictEntityTypes; - - private final Optional deidentifyTokenFormat; - - private final Optional> allowRegex; - - private final Optional> restrictRegex; - - private final Optional returnEntities; - - private final Optional accuracy; - - private final Optional advancedOptions; - - private final Optional storeEntities; - - private final Map additionalProperties; - - private V1DetectTextRequest( - String text, - String vaultId, - Optional sessionId, - Optional> restrictEntityTypes, - Optional deidentifyTokenFormat, - Optional> allowRegex, - Optional> restrictRegex, - Optional returnEntities, - Optional accuracy, - Optional advancedOptions, - Optional storeEntities, - Map additionalProperties) { - this.text = text; - this.vaultId = vaultId; - this.sessionId = sessionId; - this.restrictEntityTypes = restrictEntityTypes; - this.deidentifyTokenFormat = deidentifyTokenFormat; - this.allowRegex = allowRegex; - this.restrictRegex = restrictRegex; - this.returnEntities = returnEntities; - this.accuracy = accuracy; - this.advancedOptions = advancedOptions; - this.storeEntities = storeEntities; - this.additionalProperties = additionalProperties; - } - - /** - * @return Data to deidentify. - */ - @JsonProperty("text") - public String getText() { - return text; - } - - /** - * @return ID of the vault. - */ - @JsonProperty("vault_id") - public String getVaultId() { - return vaultId; - } - - /** - * @return Will give a handle to delete the tokens generated during a specific interaction. - */ - @JsonProperty("session_id") - public Optional getSessionId() { - return sessionId; - } - - /** - * @return Entities to detect and deidentify. - */ - @JsonProperty("restrict_entity_types") - public Optional> getRestrictEntityTypes() { - return restrictEntityTypes; - } - - @JsonProperty("deidentify_token_format") - public Optional getDeidentifyTokenFormat() { - return deidentifyTokenFormat; - } - - /** - * @return Regular expressions to ignore when detecting entities. - */ - @JsonProperty("allow_regex") - public Optional> getAllowRegex() { - return allowRegex; - } - - /** - * @return Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'. - */ - @JsonProperty("restrict_regex") - public Optional> getRestrictRegex() { - return restrictRegex; - } - - /** - * @return If true, returns the details for the detected entities. - */ - @JsonProperty("return_entities") - public Optional getReturnEntities() { - return returnEntities; - } - - @JsonProperty("accuracy") - public Optional getAccuracy() { - return accuracy; - } - - @JsonProperty("advanced_options") - public Optional getAdvancedOptions() { - return advancedOptions; - } - - /** - * @return Indicates whether entities should be stored in the vault. - */ - @JsonProperty("store_entities") - public Optional getStoreEntities() { - return storeEntities; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1DetectTextRequest && equalTo((V1DetectTextRequest) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1DetectTextRequest other) { - return text.equals(other.text) - && vaultId.equals(other.vaultId) - && sessionId.equals(other.sessionId) - && restrictEntityTypes.equals(other.restrictEntityTypes) - && deidentifyTokenFormat.equals(other.deidentifyTokenFormat) - && allowRegex.equals(other.allowRegex) - && restrictRegex.equals(other.restrictRegex) - && returnEntities.equals(other.returnEntities) - && accuracy.equals(other.accuracy) - && advancedOptions.equals(other.advancedOptions) - && storeEntities.equals(other.storeEntities); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash( - this.text, - this.vaultId, - this.sessionId, - this.restrictEntityTypes, - this.deidentifyTokenFormat, - this.allowRegex, - this.restrictRegex, - this.returnEntities, - this.accuracy, - this.advancedOptions, - this.storeEntities); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static TextStage builder() { - return new Builder(); - } - - public interface TextStage { - /** - * Data to deidentify. - */ - VaultIdStage text(@NotNull String text); - - Builder from(V1DetectTextRequest other); - } - - public interface VaultIdStage { - /** - * ID of the vault. - */ - _FinalStage vaultId(@NotNull String vaultId); - } - - public interface _FinalStage { - V1DetectTextRequest build(); - - /** - *

Will give a handle to delete the tokens generated during a specific interaction.

- */ - _FinalStage sessionId(Optional sessionId); - - _FinalStage sessionId(String sessionId); - - /** - *

Entities to detect and deidentify.

- */ - _FinalStage restrictEntityTypes(Optional> restrictEntityTypes); - - _FinalStage restrictEntityTypes(List restrictEntityTypes); - - _FinalStage deidentifyTokenFormat(Optional deidentifyTokenFormat); - - _FinalStage deidentifyTokenFormat(DetectRequestDeidentifyOption deidentifyTokenFormat); - - /** - *

Regular expressions to ignore when detecting entities.

- */ - _FinalStage allowRegex(Optional> allowRegex); - - _FinalStage allowRegex(List allowRegex); - - /** - *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

- */ - _FinalStage restrictRegex(Optional> restrictRegex); - - _FinalStage restrictRegex(List restrictRegex); - - /** - *

If true, returns the details for the detected entities.

- */ - _FinalStage returnEntities(Optional returnEntities); - - _FinalStage returnEntities(Boolean returnEntities); - - _FinalStage accuracy(Optional accuracy); - - _FinalStage accuracy(DetectDataAccuracy accuracy); - - _FinalStage advancedOptions(Optional advancedOptions); - - _FinalStage advancedOptions(V1AdvancedOptions advancedOptions); - - /** - *

Indicates whether entities should be stored in the vault.

- */ - _FinalStage storeEntities(Optional storeEntities); - - _FinalStage storeEntities(Boolean storeEntities); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder implements TextStage, VaultIdStage, _FinalStage { - private String text; - - private String vaultId; - - private Optional storeEntities = Optional.empty(); - - private Optional advancedOptions = Optional.empty(); - - private Optional accuracy = Optional.empty(); - - private Optional returnEntities = Optional.empty(); - - private Optional> restrictRegex = Optional.empty(); - - private Optional> allowRegex = Optional.empty(); - - private Optional deidentifyTokenFormat = Optional.empty(); - - private Optional> restrictEntityTypes = Optional.empty(); - - private Optional sessionId = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - @java.lang.Override - public Builder from(V1DetectTextRequest other) { - text(other.getText()); - vaultId(other.getVaultId()); - sessionId(other.getSessionId()); - restrictEntityTypes(other.getRestrictEntityTypes()); - deidentifyTokenFormat(other.getDeidentifyTokenFormat()); - allowRegex(other.getAllowRegex()); - restrictRegex(other.getRestrictRegex()); - returnEntities(other.getReturnEntities()); - accuracy(other.getAccuracy()); - advancedOptions(other.getAdvancedOptions()); - storeEntities(other.getStoreEntities()); - return this; - } - - /** - * Data to deidentify.

Data to deidentify.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - @JsonSetter("text") - public VaultIdStage text(@NotNull String text) { - this.text = Objects.requireNonNull(text, "text must not be null"); - return this; - } - - /** - * ID of the vault.

ID of the vault.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - @JsonSetter("vault_id") - public _FinalStage vaultId(@NotNull String vaultId) { - this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); - return this; - } - - /** - *

Indicates whether entities should be stored in the vault.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage storeEntities(Boolean storeEntities) { - this.storeEntities = Optional.ofNullable(storeEntities); - return this; - } - - /** - *

Indicates whether entities should be stored in the vault.

- */ - @java.lang.Override - @JsonSetter(value = "store_entities", nulls = Nulls.SKIP) - public _FinalStage storeEntities(Optional storeEntities) { - this.storeEntities = storeEntities; - return this; - } - - @java.lang.Override - public _FinalStage advancedOptions(V1AdvancedOptions advancedOptions) { - this.advancedOptions = Optional.ofNullable(advancedOptions); - return this; - } - - @java.lang.Override - @JsonSetter(value = "advanced_options", nulls = Nulls.SKIP) - public _FinalStage advancedOptions(Optional advancedOptions) { - this.advancedOptions = advancedOptions; - return this; - } - - @java.lang.Override - public _FinalStage accuracy(DetectDataAccuracy accuracy) { - this.accuracy = Optional.ofNullable(accuracy); - return this; - } - - @java.lang.Override - @JsonSetter(value = "accuracy", nulls = Nulls.SKIP) - public _FinalStage accuracy(Optional accuracy) { - this.accuracy = accuracy; - return this; - } - - /** - *

If true, returns the details for the detected entities.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage returnEntities(Boolean returnEntities) { - this.returnEntities = Optional.ofNullable(returnEntities); - return this; - } - - /** - *

If true, returns the details for the detected entities.

- */ - @java.lang.Override - @JsonSetter(value = "return_entities", nulls = Nulls.SKIP) - public _FinalStage returnEntities(Optional returnEntities) { - this.returnEntities = returnEntities; - return this; - } - - /** - *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage restrictRegex(List restrictRegex) { - this.restrictRegex = Optional.ofNullable(restrictRegex); - return this; - } - - /** - *

Regular expressions to always restrict. Strings matching these regular expressions are replaced with 'RESTRICTED'.

- */ - @java.lang.Override - @JsonSetter(value = "restrict_regex", nulls = Nulls.SKIP) - public _FinalStage restrictRegex(Optional> restrictRegex) { - this.restrictRegex = restrictRegex; - return this; - } - - /** - *

Regular expressions to ignore when detecting entities.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage allowRegex(List allowRegex) { - this.allowRegex = Optional.ofNullable(allowRegex); - return this; - } - - /** - *

Regular expressions to ignore when detecting entities.

- */ - @java.lang.Override - @JsonSetter(value = "allow_regex", nulls = Nulls.SKIP) - public _FinalStage allowRegex(Optional> allowRegex) { - this.allowRegex = allowRegex; - return this; - } - - @java.lang.Override - public _FinalStage deidentifyTokenFormat(DetectRequestDeidentifyOption deidentifyTokenFormat) { - this.deidentifyTokenFormat = Optional.ofNullable(deidentifyTokenFormat); - return this; - } - - @java.lang.Override - @JsonSetter(value = "deidentify_token_format", nulls = Nulls.SKIP) - public _FinalStage deidentifyTokenFormat(Optional deidentifyTokenFormat) { - this.deidentifyTokenFormat = deidentifyTokenFormat; - return this; - } - - /** - *

Entities to detect and deidentify.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage restrictEntityTypes(List restrictEntityTypes) { - this.restrictEntityTypes = Optional.ofNullable(restrictEntityTypes); - return this; - } - - /** - *

Entities to detect and deidentify.

- */ - @java.lang.Override - @JsonSetter(value = "restrict_entity_types", nulls = Nulls.SKIP) - public _FinalStage restrictEntityTypes(Optional> restrictEntityTypes) { - this.restrictEntityTypes = restrictEntityTypes; - return this; - } - - /** - *

Will give a handle to delete the tokens generated during a specific interaction.

- * @return Reference to {@code this} so that method calls can be chained together. - */ - @java.lang.Override - public _FinalStage sessionId(String sessionId) { - this.sessionId = Optional.ofNullable(sessionId); - return this; - } - - /** - *

Will give a handle to delete the tokens generated during a specific interaction.

- */ - @java.lang.Override - @JsonSetter(value = "session_id", nulls = Nulls.SKIP) - public _FinalStage sessionId(Optional sessionId) { - this.sessionId = sessionId; - return this; - } - - @java.lang.Override - public V1DetectTextRequest build() { - return new V1DetectTextRequest( - text, - vaultId, - sessionId, - restrictEntityTypes, - deidentifyTokenFormat, - allowRegex, - restrictRegex, - returnEntities, - accuracy, - advancedOptions, - storeEntities, - additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1DetectTextResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1DetectTextResponse.java deleted file mode 100644 index a07c3344..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/V1DetectTextResponse.java +++ /dev/null @@ -1,133 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1DetectTextResponse.Builder.class) -public final class V1DetectTextResponse { - private final Optional processedText; - - private final Optional> entities; - - private final Map additionalProperties; - - private V1DetectTextResponse( - Optional processedText, - Optional> entities, - Map additionalProperties) { - this.processedText = processedText; - this.entities = entities; - this.additionalProperties = additionalProperties; - } - - /** - * @return Deidentified text. If the input was a file, text that was extracted or transcribed from the file and deidentified. - */ - @JsonProperty("processed_text") - public Optional getProcessedText() { - return processedText; - } - - /** - * @return Detected entities. - */ - @JsonProperty("entities") - public Optional> getEntities() { - return entities; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1DetectTextResponse && equalTo((V1DetectTextResponse) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1DetectTextResponse other) { - return processedText.equals(other.processedText) && entities.equals(other.entities); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.processedText, this.entities); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional processedText = Optional.empty(); - - private Optional> entities = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1DetectTextResponse other) { - processedText(other.getProcessedText()); - entities(other.getEntities()); - return this; - } - - /** - *

Deidentified text. If the input was a file, text that was extracted or transcribed from the file and deidentified.

- */ - @JsonSetter(value = "processed_text", nulls = Nulls.SKIP) - public Builder processedText(Optional processedText) { - this.processedText = processedText; - return this; - } - - public Builder processedText(String processedText) { - this.processedText = Optional.ofNullable(processedText); - return this; - } - - /** - *

Detected entities.

- */ - @JsonSetter(value = "entities", nulls = Nulls.SKIP) - public Builder entities(Optional> entities) { - this.entities = entities; - return this; - } - - public Builder entities(List entities) { - this.entities = Optional.ofNullable(entities); - return this; - } - - public V1DetectTextResponse build() { - return new V1DetectTextResponse(processedText, entities, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1ImageOptions.java b/src/main/java/com/skyflow/generated/rest/types/V1ImageOptions.java deleted file mode 100644 index cd40fb5b..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/V1ImageOptions.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1ImageOptions.Builder.class) -public final class V1ImageOptions { - private final Optional outputProcessedImage; - - private final Optional outputOcrText; - - private final Map additionalProperties; - - private V1ImageOptions( - Optional outputProcessedImage, - Optional outputOcrText, - Map additionalProperties) { - this.outputProcessedImage = outputProcessedImage; - this.outputOcrText = outputOcrText; - this.additionalProperties = additionalProperties; - } - - /** - * @return If true, includes processed image in the output. - */ - @JsonProperty("output_processed_image") - public Optional getOutputProcessedImage() { - return outputProcessedImage; - } - - /** - * @return If true, includes OCR text output in the response. - */ - @JsonProperty("output_ocr_text") - public Optional getOutputOcrText() { - return outputOcrText; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1ImageOptions && equalTo((V1ImageOptions) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1ImageOptions other) { - return outputProcessedImage.equals(other.outputProcessedImage) && outputOcrText.equals(other.outputOcrText); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.outputProcessedImage, this.outputOcrText); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional outputProcessedImage = Optional.empty(); - - private Optional outputOcrText = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1ImageOptions other) { - outputProcessedImage(other.getOutputProcessedImage()); - outputOcrText(other.getOutputOcrText()); - return this; - } - - /** - *

If true, includes processed image in the output.

- */ - @JsonSetter(value = "output_processed_image", nulls = Nulls.SKIP) - public Builder outputProcessedImage(Optional outputProcessedImage) { - this.outputProcessedImage = outputProcessedImage; - return this; - } - - public Builder outputProcessedImage(Boolean outputProcessedImage) { - this.outputProcessedImage = Optional.ofNullable(outputProcessedImage); - return this; - } - - /** - *

If true, includes OCR text output in the response.

- */ - @JsonSetter(value = "output_ocr_text", nulls = Nulls.SKIP) - public Builder outputOcrText(Optional outputOcrText) { - this.outputOcrText = outputOcrText; - return this; - } - - public Builder outputOcrText(Boolean outputOcrText) { - this.outputOcrText = Optional.ofNullable(outputOcrText); - return this; - } - - public V1ImageOptions build() { - return new V1ImageOptions(outputProcessedImage, outputOcrText, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1Locations.java b/src/main/java/com/skyflow/generated/rest/types/V1Locations.java deleted file mode 100644 index ef1593ca..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/V1Locations.java +++ /dev/null @@ -1,193 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1Locations.Builder.class) -public final class V1Locations { - private final Optional startIndex; - - private final Optional endIndex; - - private final Optional startIndexProcessed; - - private final Optional endIndexProcessed; - - private final Map additionalProperties; - - private V1Locations( - Optional startIndex, - Optional endIndex, - Optional startIndexProcessed, - Optional endIndexProcessed, - Map additionalProperties) { - this.startIndex = startIndex; - this.endIndex = endIndex; - this.startIndexProcessed = startIndexProcessed; - this.endIndexProcessed = endIndexProcessed; - this.additionalProperties = additionalProperties; - } - - /** - * @return Index of the first character of the string in the original text. - */ - @JsonProperty("start_index") - public Optional getStartIndex() { - return startIndex; - } - - /** - * @return Index of the last character of the string in the original text. - */ - @JsonProperty("end_index") - public Optional getEndIndex() { - return endIndex; - } - - /** - * @return Index of the first character of the string in the processed text. - */ - @JsonProperty("start_index_processed") - public Optional getStartIndexProcessed() { - return startIndexProcessed; - } - - /** - * @return Index of the last character of the string in the processed text. - */ - @JsonProperty("end_index_processed") - public Optional getEndIndexProcessed() { - return endIndexProcessed; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1Locations && equalTo((V1Locations) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1Locations other) { - return startIndex.equals(other.startIndex) - && endIndex.equals(other.endIndex) - && startIndexProcessed.equals(other.startIndexProcessed) - && endIndexProcessed.equals(other.endIndexProcessed); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.startIndex, this.endIndex, this.startIndexProcessed, this.endIndexProcessed); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional startIndex = Optional.empty(); - - private Optional endIndex = Optional.empty(); - - private Optional startIndexProcessed = Optional.empty(); - - private Optional endIndexProcessed = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1Locations other) { - startIndex(other.getStartIndex()); - endIndex(other.getEndIndex()); - startIndexProcessed(other.getStartIndexProcessed()); - endIndexProcessed(other.getEndIndexProcessed()); - return this; - } - - /** - *

Index of the first character of the string in the original text.

- */ - @JsonSetter(value = "start_index", nulls = Nulls.SKIP) - public Builder startIndex(Optional startIndex) { - this.startIndex = startIndex; - return this; - } - - public Builder startIndex(Integer startIndex) { - this.startIndex = Optional.ofNullable(startIndex); - return this; - } - - /** - *

Index of the last character of the string in the original text.

- */ - @JsonSetter(value = "end_index", nulls = Nulls.SKIP) - public Builder endIndex(Optional endIndex) { - this.endIndex = endIndex; - return this; - } - - public Builder endIndex(Integer endIndex) { - this.endIndex = Optional.ofNullable(endIndex); - return this; - } - - /** - *

Index of the first character of the string in the processed text.

- */ - @JsonSetter(value = "start_index_processed", nulls = Nulls.SKIP) - public Builder startIndexProcessed(Optional startIndexProcessed) { - this.startIndexProcessed = startIndexProcessed; - return this; - } - - public Builder startIndexProcessed(Integer startIndexProcessed) { - this.startIndexProcessed = Optional.ofNullable(startIndexProcessed); - return this; - } - - /** - *

Index of the last character of the string in the processed text.

- */ - @JsonSetter(value = "end_index_processed", nulls = Nulls.SKIP) - public Builder endIndexProcessed(Optional endIndexProcessed) { - this.endIndexProcessed = endIndexProcessed; - return this; - } - - public Builder endIndexProcessed(Integer endIndexProcessed) { - this.endIndexProcessed = Optional.ofNullable(endIndexProcessed); - return this; - } - - public V1Locations build() { - return new V1Locations(startIndex, endIndex, startIndexProcessed, endIndexProcessed, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1PdfConfig.java b/src/main/java/com/skyflow/generated/rest/types/V1PdfConfig.java deleted file mode 100644 index 8731c1b9..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/V1PdfConfig.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1PdfConfig.Builder.class) -public final class V1PdfConfig { - private final Optional options; - - private final Map additionalProperties; - - private V1PdfConfig(Optional options, Map additionalProperties) { - this.options = options; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("options") - public Optional getOptions() { - return options; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1PdfConfig && equalTo((V1PdfConfig) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1PdfConfig other) { - return options.equals(other.options); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.options); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional options = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1PdfConfig other) { - options(other.getOptions()); - return this; - } - - @JsonSetter(value = "options", nulls = Nulls.SKIP) - public Builder options(Optional options) { - this.options = options; - return this; - } - - public Builder options(V1PdfOptions options) { - this.options = Optional.ofNullable(options); - return this; - } - - public V1PdfConfig build() { - return new V1PdfConfig(options, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1PdfOptions.java b/src/main/java/com/skyflow/generated/rest/types/V1PdfOptions.java deleted file mode 100644 index 63de909b..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/V1PdfOptions.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1PdfOptions.Builder.class) -public final class V1PdfOptions { - private final Optional density; - - private final Optional maxResolution; - - private final Map additionalProperties; - - private V1PdfOptions( - Optional density, Optional maxResolution, Map additionalProperties) { - this.density = density; - this.maxResolution = maxResolution; - this.additionalProperties = additionalProperties; - } - - /** - * @return Pixel density at which to process the PDF file. - */ - @JsonProperty("density") - public Optional getDensity() { - return density; - } - - /** - * @return Max resolution at which to process the PDF file. - */ - @JsonProperty("max_resolution") - public Optional getMaxResolution() { - return maxResolution; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1PdfOptions && equalTo((V1PdfOptions) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1PdfOptions other) { - return density.equals(other.density) && maxResolution.equals(other.maxResolution); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.density, this.maxResolution); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional density = Optional.empty(); - - private Optional maxResolution = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1PdfOptions other) { - density(other.getDensity()); - maxResolution(other.getMaxResolution()); - return this; - } - - /** - *

Pixel density at which to process the PDF file.

- */ - @JsonSetter(value = "density", nulls = Nulls.SKIP) - public Builder density(Optional density) { - this.density = density; - return this; - } - - public Builder density(Integer density) { - this.density = Optional.ofNullable(density); - return this; - } - - /** - *

Max resolution at which to process the PDF file.

- */ - @JsonSetter(value = "max_resolution", nulls = Nulls.SKIP) - public Builder maxResolution(Optional maxResolution) { - this.maxResolution = maxResolution; - return this; - } - - public Builder maxResolution(Integer maxResolution) { - this.maxResolution = Optional.ofNullable(maxResolution); - return this; - } - - public V1PdfOptions build() { - return new V1PdfOptions(density, maxResolution, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1ProcessedFileOutput.java b/src/main/java/com/skyflow/generated/rest/types/V1ProcessedFileOutput.java deleted file mode 100644 index e4117109..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/V1ProcessedFileOutput.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1ProcessedFileOutput.Builder.class) -public final class V1ProcessedFileOutput { - private final Optional outputType; - - private final Optional processedFile; - - private final Optional processedFileType; - - private final Map additionalProperties; - - private V1ProcessedFileOutput( - Optional outputType, - Optional processedFile, - Optional processedFileType, - Map additionalProperties) { - this.outputType = outputType; - this.processedFile = processedFile; - this.processedFileType = processedFileType; - this.additionalProperties = additionalProperties; - } - - @JsonProperty("output_type") - public Optional getOutputType() { - return outputType; - } - - /** - * @return URL or base64-encoded data of the output. - */ - @JsonProperty("processed_file") - public Optional getProcessedFile() { - return processedFile; - } - - @JsonProperty("processed_file_type") - public Optional getProcessedFileType() { - return processedFileType; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1ProcessedFileOutput && equalTo((V1ProcessedFileOutput) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1ProcessedFileOutput other) { - return outputType.equals(other.outputType) - && processedFile.equals(other.processedFile) - && processedFileType.equals(other.processedFileType); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.outputType, this.processedFile, this.processedFileType); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional outputType = Optional.empty(); - - private Optional processedFile = Optional.empty(); - - private Optional processedFileType = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1ProcessedFileOutput other) { - outputType(other.getOutputType()); - processedFile(other.getProcessedFile()); - processedFileType(other.getProcessedFileType()); - return this; - } - - @JsonSetter(value = "output_type", nulls = Nulls.SKIP) - public Builder outputType(Optional outputType) { - this.outputType = outputType; - return this; - } - - public Builder outputType(DetectFileRequestDataType outputType) { - this.outputType = Optional.ofNullable(outputType); - return this; - } - - /** - *

URL or base64-encoded data of the output.

- */ - @JsonSetter(value = "processed_file", nulls = Nulls.SKIP) - public Builder processedFile(Optional processedFile) { - this.processedFile = processedFile; - return this; - } - - public Builder processedFile(String processedFile) { - this.processedFile = Optional.ofNullable(processedFile); - return this; - } - - @JsonSetter(value = "processed_file_type", nulls = Nulls.SKIP) - public Builder processedFileType(Optional processedFileType) { - this.processedFileType = processedFileType; - return this; - } - - public Builder processedFileType(ProcessedFileOutputProcessedFileType processedFileType) { - this.processedFileType = Optional.ofNullable(processedFileType); - return this; - } - - public V1ProcessedFileOutput build() { - return new V1ProcessedFileOutput(outputType, processedFile, processedFileType, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1ResponseEntities.java b/src/main/java/com/skyflow/generated/rest/types/V1ResponseEntities.java deleted file mode 100644 index c02ab39f..00000000 --- a/src/main/java/com/skyflow/generated/rest/types/V1ResponseEntities.java +++ /dev/null @@ -1,218 +0,0 @@ -/** - * This file was auto-generated by Fern from our API Definition. - */ -package com.skyflow.generated.rest.types; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; -import com.fasterxml.jackson.annotation.Nulls; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.skyflow.generated.rest.core.ObjectMappers; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -@JsonInclude(JsonInclude.Include.NON_ABSENT) -@JsonDeserialize(builder = V1ResponseEntities.Builder.class) -public final class V1ResponseEntities { - private final Optional processedText; - - private final Optional originalText; - - private final Optional location; - - private final Optional bestLabel; - - private final Optional> labels; - - private final Map additionalProperties; - - private V1ResponseEntities( - Optional processedText, - Optional originalText, - Optional location, - Optional bestLabel, - Optional> labels, - Map additionalProperties) { - this.processedText = processedText; - this.originalText = originalText; - this.location = location; - this.bestLabel = bestLabel; - this.labels = labels; - this.additionalProperties = additionalProperties; - } - - /** - * @return Processed text of the entity. - */ - @JsonProperty("processed_text") - public Optional getProcessedText() { - return processedText; - } - - /** - * @return Original text of the entity. - */ - @JsonProperty("original_text") - public Optional getOriginalText() { - return originalText; - } - - @JsonProperty("location") - public Optional getLocation() { - return location; - } - - /** - * @return Highest rated label. - */ - @JsonProperty("best_label") - public Optional getBestLabel() { - return bestLabel; - } - - /** - * @return Labels and their scores. - */ - @JsonProperty("labels") - public Optional> getLabels() { - return labels; - } - - @java.lang.Override - public boolean equals(Object other) { - if (this == other) return true; - return other instanceof V1ResponseEntities && equalTo((V1ResponseEntities) other); - } - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - private boolean equalTo(V1ResponseEntities other) { - return processedText.equals(other.processedText) - && originalText.equals(other.originalText) - && location.equals(other.location) - && bestLabel.equals(other.bestLabel) - && labels.equals(other.labels); - } - - @java.lang.Override - public int hashCode() { - return Objects.hash(this.processedText, this.originalText, this.location, this.bestLabel, this.labels); - } - - @java.lang.Override - public String toString() { - return ObjectMappers.stringify(this); - } - - public static Builder builder() { - return new Builder(); - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static final class Builder { - private Optional processedText = Optional.empty(); - - private Optional originalText = Optional.empty(); - - private Optional location = Optional.empty(); - - private Optional bestLabel = Optional.empty(); - - private Optional> labels = Optional.empty(); - - @JsonAnySetter - private Map additionalProperties = new HashMap<>(); - - private Builder() {} - - public Builder from(V1ResponseEntities other) { - processedText(other.getProcessedText()); - originalText(other.getOriginalText()); - location(other.getLocation()); - bestLabel(other.getBestLabel()); - labels(other.getLabels()); - return this; - } - - /** - *

Processed text of the entity.

- */ - @JsonSetter(value = "processed_text", nulls = Nulls.SKIP) - public Builder processedText(Optional processedText) { - this.processedText = processedText; - return this; - } - - public Builder processedText(String processedText) { - this.processedText = Optional.ofNullable(processedText); - return this; - } - - /** - *

Original text of the entity.

- */ - @JsonSetter(value = "original_text", nulls = Nulls.SKIP) - public Builder originalText(Optional originalText) { - this.originalText = originalText; - return this; - } - - public Builder originalText(String originalText) { - this.originalText = Optional.ofNullable(originalText); - return this; - } - - @JsonSetter(value = "location", nulls = Nulls.SKIP) - public Builder location(Optional location) { - this.location = location; - return this; - } - - public Builder location(V1Locations location) { - this.location = Optional.ofNullable(location); - return this; - } - - /** - *

Highest rated label.

- */ - @JsonSetter(value = "best_label", nulls = Nulls.SKIP) - public Builder bestLabel(Optional bestLabel) { - this.bestLabel = bestLabel; - return this; - } - - public Builder bestLabel(String bestLabel) { - this.bestLabel = Optional.ofNullable(bestLabel); - return this; - } - - /** - *

Labels and their scores.

- */ - @JsonSetter(value = "labels", nulls = Nulls.SKIP) - public Builder labels(Optional> labels) { - this.labels = labels; - return this; - } - - public Builder labels(Map labels) { - this.labels = Optional.ofNullable(labels); - return this; - } - - public V1ResponseEntities build() { - return new V1ResponseEntities( - processedText, originalText, location, bestLabel, labels, additionalProperties); - } - } -} diff --git a/src/main/java/com/skyflow/logs/ErrorLogs.java b/src/main/java/com/skyflow/logs/ErrorLogs.java index 3415860c..eb5ea742 100644 --- a/src/main/java/com/skyflow/logs/ErrorLogs.java +++ b/src/main/java/com/skyflow/logs/ErrorLogs.java @@ -109,6 +109,15 @@ public enum ErrorLogs { INVALID_REQUEST_BODY("Invalid %s1 request. Request body can not be empty."), INVOKE_CONNECTION_REQUEST_REJECTED("Invoke connection request resulted in failure."), + // File upload interface + COLUMN_NAME_IS_REQUIRED_FILE_UPLOAD("Invalid %s1 request. Column name is required."), + EMPTY_COLUMN_NAME_FILE_UPLOAD("Invalid %s1 request. Column name can not be empty."), + FILE_IS_REQUIRED("Invalid %s1 request. File is required."), + EMPTY_FILE("Invalid %s1 request. File can not be empty."), + INVALID_FILE_TYPE("Invalid %s1 request. File should be of type java.io.File"), + MISSING_FILE_SOURCE_IN_UPLOAD_FILE("Invalid %s1 request. Provide exactly one of filePath, base64, or fileObject."), + UPLOAD_FILE_REQUEST_REJECTED("Upload file request resulted in failure."), + // detect interface INVALID_TEXT_IN_DEIDENTIFY("Invalid %s1 request. The text field is required and must be a non-empty string. Specify a valid text."), diff --git a/src/main/java/com/skyflow/logs/InfoLogs.java b/src/main/java/com/skyflow/logs/InfoLogs.java index efd81a49..f71fc416 100644 --- a/src/main/java/com/skyflow/logs/InfoLogs.java +++ b/src/main/java/com/skyflow/logs/InfoLogs.java @@ -69,6 +69,11 @@ public enum InfoLogs { TOKENIZE_REQUEST_RESOLVED("Tokenize request resolved."), TOKENIZE_SUCCESS("Data tokenized."), + // File upload interface + FILE_UPLOAD_TRIGGERED("File upload method triggered."), + VALIDATING_FILE_UPLOAD_REQUEST("Validating file upload request."), + FILE_UPLOAD_REQUEST_RESOLVED("File upload request resolved."), + FILE_UPLOAD_SUCCESS("File uploaded successfully."), // Invoke connection interface INVOKE_CONNECTION_TRIGGERED("Invoke connection method triggered."), diff --git a/src/main/java/com/skyflow/utils/Constants.java b/src/main/java/com/skyflow/utils/Constants.java index b9264a22..f12e6a48 100644 --- a/src/main/java/com/skyflow/utils/Constants.java +++ b/src/main/java/com/skyflow/utils/Constants.java @@ -26,6 +26,6 @@ public final class Constants { public static final String SDK_METRICS_HEADER_KEY = "sky-metadata"; public static final String REQUEST_ID_HEADER_KEY = "x-request-id"; public static final String PROCESSED_FILE_NAME_PREFIX = "processed-"; - public static final String ERROR_FROM_CLIENT_HEADER_KEY = "eror-from-client"; - public static final String DEIDENTIFIED_FILE_PREFIX = "deidentified";; + public static final String ERROR_FROM_CLIENT_HEADER_KEY = "error-from-client"; + public static final String DEIDENTIFIED_FILE_PREFIX = "deidentified"; } diff --git a/src/main/java/com/skyflow/utils/validations/Validations.java b/src/main/java/com/skyflow/utils/validations/Validations.java index 841c03b6..0372749a 100644 --- a/src/main/java/com/skyflow/utils/validations/Validations.java +++ b/src/main/java/com/skyflow/utils/validations/Validations.java @@ -408,12 +408,7 @@ public static void validateGetRequest(GetRequest getRequest) throws SkyflowExcep } } } - if (redactionType == null && (tokenization == null || !tokenization)) { - LogUtil.printErrorLog(Utils.parameterizedString( - ErrorLogs.REDACTION_IS_REQUIRED.getLog(), InterfaceName.GET.getName() - )); - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.RedactionKeyError.getMessage()); - } + if (tokenization != null && tokenization) { if (redactionType != null) { LogUtil.printErrorLog(Utils.parameterizedString( @@ -687,6 +682,99 @@ public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) thro } } + public static void validateFileUploadRequest(FileUploadRequest fileUploadRequest) throws SkyflowException { + if (fileUploadRequest == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_REQUEST_BODY.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestBody.getMessage()); + } + + String table = fileUploadRequest.getTable(); + if (table == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.TABLE_IS_REQUIRED.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TableKeyError.getMessage()); + } else if (table.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_TABLE_NAME.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); + } + + String skyflowId = fileUploadRequest.getSkyflowId(); + if (skyflowId == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.SKYFLOW_ID_IS_REQUIRED.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.SkyflowIdKeyError.getMessage()); + } else if (skyflowId.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_SKYFLOW_ID.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptySkyflowId.getMessage()); + } + + String columnName = fileUploadRequest.getColumnName(); + if (columnName == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.COLUMN_NAME_IS_REQUIRED_FILE_UPLOAD.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ColumnNameKeyErrorFileUpload.getMessage()); + } else if (columnName.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_COLUMN_NAME.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyColumnName.getMessage()); + } + + String filePath = fileUploadRequest.getFilePath(); + String base64 = fileUploadRequest.getBase64(); + File fileObject = fileUploadRequest.getFileObject(); + String fileName = fileUploadRequest.getFileName(); + + // Check if at least one (path, base64, fileObject) is provided + if (isNullOrEmpty(filePath) && isNullOrEmpty(base64) && fileObject == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.MISSING_FILE_SOURCE_IN_UPLOAD_FILE.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingFileSourceInUploadFileRequest.getMessage()); + } + + // Check filePath + if (!isNullOrEmpty(filePath)) { + File f = new File(filePath); + if (!f.exists() || !f.isFile()) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidFilePath.getMessage()); + } + } + + // Check base64 + if (!isNullOrEmpty(base64)) { + if (isNullOrEmpty(fileName)) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FileNameMustBeProvidedWithFileObject.getMessage()); + } + // Validate if Base64 is actually valid + try { + java.util.Base64.getDecoder().decode(base64); + } catch (IllegalArgumentException e) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidBase64.getMessage()); + } + } + + // Check fileObject + if (fileObject != null) { + if (!fileObject.exists() || !fileObject.isFile()) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidFileObject.getMessage()); + } + } + } + + private static boolean isNullOrEmpty(String str) { + return str == null || str.trim().isEmpty(); + } + public static void validateDeidentifyTextRequest(DeidentifyTextRequest deidentifyTextRequest) throws SkyflowException { // Validate required fields String deidentifyText = deidentifyTextRequest.getText(); @@ -788,6 +876,11 @@ public static void validateDeidentifyFileRequest(DeidentifyFileRequest request) throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestBody.getMessage()); } + TokenFormat tokenFormat = request.getTokenFormat(); + if (tokenFormat != null && tokenFormat.getVaultToken() != null && !tokenFormat.getVaultToken().isEmpty()) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultTokenFormatIsNotAllowedForFiles.getMessage()); + } + File file = request.getFileInput().getFile(); String filePath = request.getFileInput().getFilePath(); @@ -842,9 +935,6 @@ public static void validateDeidentifyFileRequest(DeidentifyFileRequest request) )); throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); } - if (request.getBleep().getGain() == null) { - throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); - } if (request.getBleep().getStartPadding() == null || request.getBleep().getStartPadding() < 0) { throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); } diff --git a/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java b/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java index a2d44d99..1a81eca0 100644 --- a/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java +++ b/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java @@ -3,15 +3,18 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import java.util.ArrayList; import java.util.HashMap; public class InvokeConnectionResponse { private final Object data; private final HashMap metadata; + private final ArrayList> errors; - public InvokeConnectionResponse(Object data, HashMap metadata) { + public InvokeConnectionResponse(Object data, HashMap metadata, ArrayList> errors) { this.data = data; this.metadata = metadata; + this.errors = errors; } public Object getData() { @@ -22,9 +25,13 @@ public HashMap getMetadata() { return metadata; } + public ArrayList> getErrors() { + return errors; + } + @Override public String toString() { - Gson gson = new GsonBuilder().serializeNulls().create(); + Gson gson = new Gson().newBuilder().serializeNulls().create(); return gson.toJson(this); } } diff --git a/src/main/java/com/skyflow/vault/controller/ConnectionController.java b/src/main/java/com/skyflow/vault/controller/ConnectionController.java index 68a39751..4a9334d4 100644 --- a/src/main/java/com/skyflow/vault/controller/ConnectionController.java +++ b/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -67,7 +67,7 @@ public InvokeConnectionResponse invoke(InvokeConnectionRequest invokeConnectionR JsonObject data = JsonParser.parseString(response).getAsJsonObject(); HashMap metadata = new HashMap<>(); metadata.put("requestId", HttpUtility.getRequestID()); - connectionResponse = new InvokeConnectionResponse(data, metadata); + connectionResponse = new InvokeConnectionResponse(data, metadata, null); LogUtil.printInfoLog(InfoLogs.INVOKE_CONNECTION_REQUEST_RESOLVED.getLog()); } catch (IOException e) { LogUtil.printErrorLog(ErrorLogs.INVOKE_CONNECTION_REQUEST_REJECTED.getLog()); diff --git a/src/main/java/com/skyflow/vault/controller/DetectController.java b/src/main/java/com/skyflow/vault/controller/DetectController.java index 411658ae..c92e6b2c 100644 --- a/src/main/java/com/skyflow/vault/controller/DetectController.java +++ b/src/main/java/com/skyflow/vault/controller/DetectController.java @@ -12,6 +12,7 @@ import com.skyflow.generated.rest.resources.files.requests.*; import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; +import com.skyflow.generated.rest.types.DeidentifyStatusResponseOutputType; import com.skyflow.generated.rest.types.*; import com.skyflow.logs.ErrorLogs; import com.skyflow.logs.InfoLogs; @@ -28,7 +29,11 @@ import java.util.*; public final class DetectController extends VaultClient { - private static final Gson gson = new GsonBuilder().serializeNulls().create(); + Gson gson = new GsonBuilder() + .registerTypeAdapter(Optional.class, (JsonSerializer>) (src, typeOfSrc, context) -> + src.map(context::serialize).orElse(null)) + .serializeNulls() + .create(); public DetectController(VaultConfig vaultConfig, Credentials credentials) { super(vaultConfig, credentials); @@ -55,7 +60,7 @@ public DeidentifyTextResponse deidentifyText(DeidentifyTextRequest deidentifyTex deidentifyTextResponse = getDeIdentifyTextResponse(deidentifyStringResponse); LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_TEXT_REQUEST_RESOLVED.getLog()); } catch (ApiClientApiException ex) { - String bodyString = gson.toJson(ex.body()); + String bodyString = extractBodyAsString(ex); LogUtil.printErrorLog(ErrorLogs.DEIDENTIFY_TEXT_REQUEST_REJECTED.getLog()); throw new SkyflowException(ex.statusCode(), ex, ex.headers(), bodyString); } @@ -82,7 +87,7 @@ public ReidentifyTextResponse reidentifyText(ReidentifyTextRequest reidentifyTex reidentifyTextResponse = new ReidentifyTextResponse(reidentifyStringResponse.getText().orElse(null)); LogUtil.printInfoLog(InfoLogs.REIDENTIFY_TEXT_REQUEST_RESOLVED.getLog()); } catch (ApiClientApiException ex) { - String bodyString = gson.toJson(ex.body()); + String bodyString = extractBodyAsString(ex); LogUtil.printErrorLog(ErrorLogs.REIDENTIFY_TEXT_REQUEST_REJECTED.getLog()); throw new SkyflowException(ex.statusCode(), ex, ex.headers(), bodyString); } @@ -126,10 +131,11 @@ public DeidentifyFileResponse deidentifyFile(DeidentifyFileRequest request) thro if (DeidentifyFileStatus.SUCCESS.value().equalsIgnoreCase(response.getStatus())) { String base64File = response.getFileBase64(); + response.getEntities().get(0).getFile(); if (base64File != null) { byte[] decodedBytes = Base64.getDecoder().decode(base64File); String outputDir = request.getOutputDirectory(); - String outputFileName = Constants.PROCESSED_FILE_NAME_PREFIX + fileName; + String outputFileName = Constants.PROCESSED_FILE_NAME_PREFIX + fileName.substring(0, fileName.lastIndexOf('.')) + "."+response.getExtension(); File outputFile; if (outputDir != null && !outputDir.isEmpty()) { outputFile = new File(outputDir, outputFileName); @@ -143,9 +149,31 @@ public DeidentifyFileResponse deidentifyFile(DeidentifyFileRequest request) thro } } + + List entities = response.getEntities(); + if (entities != null && !entities.isEmpty()) { + FileEntityInfo entityInfo = entities.get(0); + String entityBase64 = entityInfo.getFile(); + String outputDir = request.getOutputDirectory(); + if (entityBase64 != null) { + byte[] entityDecodedBytes = Base64.getDecoder().decode(entityBase64); + String entityFileName = Constants.PROCESSED_FILE_NAME_PREFIX + fileName.substring(0, fileName.lastIndexOf('.')) + ".json"; + File entityFile; + if (outputDir != null && !outputDir.isEmpty()) { + entityFile = new File(outputDir, entityFileName); + } else { + entityFile = new File(entityFileName); + } + try { + java.nio.file.Files.write(entityFile.toPath(), entityDecodedBytes); + } catch (IOException ioe) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FailedtoSaveProcessedFile.getMessage()); + } + } + } } } catch (ApiClientApiException e) { - String bodyString = gson.toJson(e.body()); + String bodyString = extractBodyAsString(e); LogUtil.printErrorLog(ErrorLogs.DEIDENTIFY_FILE_REQUEST_REJECTED.getLog()); throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); } @@ -212,6 +240,24 @@ private static synchronized DeidentifyFileResponse parseDeidentifyFileResponse(D String runId, String status) throws SkyflowException { DeidentifyFileOutput firstOutput = getFirstOutput(response); + if (firstOutput == null) { + return new DeidentifyFileResponse( + null, + null, + response.getOutputType().name(), + null, + null, + null, + response.getSize().orElse(null), + response.getDuration().orElse(null), + response.getPages().orElse(null), + response.getSlides().orElse(null), + getEntities(response), + runId, + response.getStatus().name() + ); + } + Object wordCharObj = response.getAdditionalProperties().get("word_character_count"); Integer wordCount = null; Integer charCount = null; @@ -230,9 +276,8 @@ private static synchronized DeidentifyFileResponse parseDeidentifyFileResponse(D File processedFileObject = null; FileInfo fileInfo = null; - Optional processedFileBase64 = firstOutput != null ? firstOutput.getProcessedFile() : Optional.empty(); - Optional processedFileExtension = firstOutput != null ? firstOutput.getProcessedFileExtension() : Optional.empty(); - + Optional processedFileBase64 = Optional.of(firstOutput).flatMap(DeidentifyFileOutput::getProcessedFile); + Optional processedFileExtension = Optional.of(firstOutput).flatMap(DeidentifyFileOutput::getProcessedFileExtension); if (processedFileBase64.isPresent() && processedFileExtension.isPresent()) { try { byte[] decodedBytes = Base64.getDecoder().decode(processedFileBase64.get()); @@ -247,21 +292,27 @@ private static synchronized DeidentifyFileResponse parseDeidentifyFileResponse(D } } + String processedFileType = firstOutput.getProcessedFileType() + .map(Object::toString) + .orElse(DeidentifyStatusResponseOutputType.UNKNOWN.toString()); + + String fileExtension = firstOutput.getProcessedFileExtension() + .orElse(DeidentifyStatusResponseOutputType.UNKNOWN.toString()); + return new DeidentifyFileResponse( fileInfo, firstOutput.getProcessedFile().orElse(null), - firstOutput.getProcessedFileType().get().toString(), - firstOutput.getProcessedFileExtension().get(), + processedFileType, + fileExtension, wordCount, charCount, - response.getSize().map(Double::valueOf).orElse(null), - response.getDuration().map(Double::valueOf).orElse(null), + response.getSize().orElse(null), + response.getDuration().orElse(null), response.getPages().orElse(null), response.getSlides().orElse(null), getEntities(response), runId, - status, - null + status ); } @@ -287,6 +338,13 @@ private static synchronized List getEntities(DeidentifyStatusRes return entities; } + private String extractBodyAsString(ApiClientApiException e) { + return e.statusCode() == 500 + ? e.body().toString() + : gson.toJson(e.body()); + } + + private com.skyflow.generated.rest.types.DeidentifyFileResponse processFileByType(String fileExtension, String base64Content, DeidentifyFileRequest request, String vaultId) throws SkyflowException { switch (fileExtension.toLowerCase()) { case "txt": @@ -367,7 +425,7 @@ public DeidentifyFileResponse getDetectRun(GetDetectRunRequest request) throws S return parseDeidentifyFileResponse(apiResponse, runId, apiResponse.getStatus().toString()); } catch (ApiClientApiException e) { - String bodyString = gson.toJson(e.body()); + String bodyString = extractBodyAsString(e); LogUtil.printErrorLog(ErrorLogs.GET_DETECT_RUN_REQUEST_REJECTED.getLog()); throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); } diff --git a/src/main/java/com/skyflow/vault/controller/VaultController.java b/src/main/java/com/skyflow/vault/controller/VaultController.java index 84e528b0..3493227c 100644 --- a/src/main/java/com/skyflow/vault/controller/VaultController.java +++ b/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -22,6 +22,9 @@ import com.skyflow.utils.validations.Validations; import com.skyflow.vault.data.*; import com.skyflow.vault.tokens.*; + +import java.io.File; +import java.io.IOException; import java.util.*; public final class VaultController extends VaultClient { @@ -31,7 +34,7 @@ public VaultController(VaultConfig vaultConfig, Credentials credentials) { super(vaultConfig, credentials); } - private static synchronized HashMap getFormattedBatchInsertRecord(Object record, int requestIndex) { + private static synchronized HashMap getFormattedBatchInsertRecord(Object record, Integer requestIndex) { HashMap insertRecord = new HashMap<>(); String jsonString = gson.toJson(record); JsonObject bodyObject = JsonParser.parseString(jsonString).getAsJsonObject().get("Body").getAsJsonObject(); @@ -95,11 +98,9 @@ private static synchronized HashMap getFormattedUpdateRecord(V1U private static synchronized HashMap getFormattedQueryRecord(V1FieldRecords record) { HashMap queryRecord = new HashMap<>(); - Object fields = record.getFields(); - if (fields != null) { - String fieldsString = gson.toJson(fields); - JsonObject fieldsObject = JsonParser.parseString(fieldsString).getAsJsonObject(); - queryRecord.putAll(fieldsObject.asMap()); + Optional> fieldsOpt = record.getFields(); + if (fieldsOpt.isPresent()) { + queryRecord.putAll(fieldsOpt.get()); } return queryRecord; } @@ -124,7 +125,7 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio if (records.isPresent()) { List> recordList = records.get(); - for (int index = 0; index < recordList.size(); index++) { + for (Integer index = (Integer) 0; index < recordList.size(); index++) { Map record = recordList.get(index); HashMap insertRecord = getFormattedBatchInsertRecord(record, index); @@ -132,6 +133,7 @@ public InsertResponse insert(InsertRequest insertRequest) throws SkyflowExceptio insertedFields.add(insertRecord); } else { insertRecord.put("requestId", batchInsertResult.headers().get("x-request-id").get(0)); + insertRecord.put("httpCode", 400); errorFields.add(insertRecord); } } @@ -232,6 +234,7 @@ public GetResponse get(GetRequest getRequest) throws SkyflowException { .downloadUrl(getRequest.getDownloadURL()) .columnName(getRequest.getColumnName()) .columnValues(getRequest.getColumnValues()) + .fields(getRequest.getFields()) .orderBy(RecordServiceBulkGetRecordRequestOrderBy.valueOf(getRequest.getOrderBy())) .build(); @@ -359,4 +362,40 @@ public TokenizeResponse tokenize(TokenizeRequest tokenizeRequest) throws Skyflow LogUtil.printInfoLog(InfoLogs.TOKENIZE_SUCCESS.getLog()); return new TokenizeResponse(list); } + + public FileUploadResponse uploadFile(FileUploadRequest fileUploadRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.FILE_UPLOAD_TRIGGERED.getLog()); + FileUploadResponse fileUploadResponse = null; + + try { + LogUtil.printInfoLog(InfoLogs.VALIDATING_FILE_UPLOAD_REQUEST.getLog()); + Validations.validateFileUploadRequest(fileUploadRequest); + setBearerToken(); + File file = super.getFileForFileUpload(fileUploadRequest); + + UploadFileV2Request uploadFileV2Request = UploadFileV2Request.builder() + .tableName(fileUploadRequest.getTable()) + .columnName(fileUploadRequest.getColumnName()) + .skyflowId(fileUploadRequest.getSkyflowId()) + .returnFileMetadata(false) + .build(); + + UploadFileV2Response uploadFileV2Response = super.getRecordsApi().uploadFileV2(super.getVaultConfig().getVaultId(), file, uploadFileV2Request); + + fileUploadResponse = new FileUploadResponse( + uploadFileV2Response.getSkyflowId().orElse(null), + null + ); + + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.UPLOAD_FILE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } catch (IOException e) { + LogUtil.printErrorLog(ErrorLogs.UPLOAD_FILE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.getMessage(), e); + } + LogUtil.printInfoLog(InfoLogs.FILE_UPLOAD_SUCCESS.getLog()); + return fileUploadResponse; + } } diff --git a/src/main/java/com/skyflow/vault/data/FileUploadRequest.java b/src/main/java/com/skyflow/vault/data/FileUploadRequest.java new file mode 100644 index 00000000..1d6ba6be --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/FileUploadRequest.java @@ -0,0 +1,97 @@ +package com.skyflow.vault.data; + +import java.io.File; + +public class FileUploadRequest { + + private final FileUploadRequest.FileUploadRequestBuilder builder; + + private FileUploadRequest(FileUploadRequest.FileUploadRequestBuilder builder) { + this.builder = builder; + } + + public static FileUploadRequest.FileUploadRequestBuilder builder() { + return new FileUploadRequest.FileUploadRequestBuilder(); + } + + public String getTable() { + return this.builder.table; + } + + public String getSkyflowId() { + return this.builder.skyflowId; + } + + public String getColumnName() { + return this.builder.columnName; + } + + public String getFilePath() { + return this.builder.filePath; + } + + public String getBase64() { + return this.builder.base64; + } + + public File getFileObject() { + return this.builder.fileObject; + } + + public String getFileName() { + return this.builder.fileName; + } + + public static final class FileUploadRequestBuilder { + + private String table; + private String skyflowId; + private String columnName; + private String filePath; + private String base64; + private File fileObject; + private String fileName; + + private FileUploadRequestBuilder() { + } + + public FileUploadRequest.FileUploadRequestBuilder table(String table) { + this.table = table; + return this; + } + + public FileUploadRequest.FileUploadRequestBuilder skyflowId(String skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + public FileUploadRequest.FileUploadRequestBuilder columnName(String columnName) { + this.columnName = columnName; + return this; + } + + public FileUploadRequest.FileUploadRequestBuilder filePath(String filePath) { + this.filePath = filePath; + return this; + } + + public FileUploadRequest.FileUploadRequestBuilder base64(String base64) { + this.base64 = base64; + return this; + } + + public FileUploadRequest.FileUploadRequestBuilder fileObject(File fileObject) { + this.fileObject = fileObject; + return this; + } + + public FileUploadRequest.FileUploadRequestBuilder fileName(String fileName) { + this.fileName = fileName; + return this; + } + + public FileUploadRequest build() { + return new FileUploadRequest(this); + } + } +} diff --git a/src/main/java/com/skyflow/vault/data/FileUploadResponse.java b/src/main/java/com/skyflow/vault/data/FileUploadResponse.java new file mode 100644 index 00000000..9e4557a3 --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/FileUploadResponse.java @@ -0,0 +1,31 @@ +package com.skyflow.vault.data; + +import com.google.gson.Gson; + +import java.util.ArrayList; +import java.util.HashMap; + +public class FileUploadResponse { + private final String skyflowId; + private final ArrayList> errors; + + public FileUploadResponse(String skyflowId, ArrayList> errors) { + this.skyflowId = skyflowId; + this.errors = errors; + } + + public String getSkyflowId() { + return skyflowId; + } + + public ArrayList> getErrors() { + return errors; + } + + @Override + public String toString() { + Gson gson = new Gson().newBuilder().serializeNulls().create(); + return gson.toJson(this); + } + +} diff --git a/src/main/java/com/skyflow/vault/data/GetResponse.java b/src/main/java/com/skyflow/vault/data/GetResponse.java index 41821969..34a01303 100644 --- a/src/main/java/com/skyflow/vault/data/GetResponse.java +++ b/src/main/java/com/skyflow/vault/data/GetResponse.java @@ -24,7 +24,7 @@ public ArrayList> getErrors() { @Override public String toString() { - Gson gson = new Gson(); + Gson gson = new Gson().newBuilder().serializeNulls().create(); return gson.toJson(this); } } diff --git a/src/main/java/com/skyflow/vault/data/InsertResponse.java b/src/main/java/com/skyflow/vault/data/InsertResponse.java index a4f97967..3d311525 100644 --- a/src/main/java/com/skyflow/vault/data/InsertResponse.java +++ b/src/main/java/com/skyflow/vault/data/InsertResponse.java @@ -24,7 +24,7 @@ public ArrayList> getErrors() { @Override public String toString() { - Gson gson = new Gson(); + Gson gson = new Gson().newBuilder().serializeNulls().create(); return gson.toJson(this); } } diff --git a/src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java b/src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java index 95effea0..66590f8e 100644 --- a/src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java +++ b/src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java @@ -20,13 +20,12 @@ public class DeidentifyFileResponse { private final List entities; private final String runId; private final String status; - private final List errors; public DeidentifyFileResponse(FileInfo file, String fileBase64, String type, String extension, Integer wordCount, Integer charCount, Double sizeInKb, Double durationInSeconds, Integer pageCount, Integer slideCount, - List entities, String runId, String status, List errors) { + List entities, String runId, String status) { this.file = file; this.fileBase64 = fileBase64; this.type = type; @@ -40,11 +39,10 @@ public DeidentifyFileResponse(FileInfo file, String fileBase64, String type, Str this.entities = entities; this.runId = runId; this.status = status; - this.errors = errors; } public DeidentifyFileResponse(String runId, String status) { - this(null, null, null, null, null, null, null, null, null, null, null, runId, status, null); + this(null, null, null, null, null, null, null, null, null, null, null, runId, status); } public FileInfo getFile() { @@ -99,10 +97,6 @@ public String getStatus() { return status; } - public List getErrors() { - return errors; - } - @Override public String toString() { Gson gson = new GsonBuilder().serializeNulls().create(); diff --git a/src/main/java/com/skyflow/vault/tokens/DetokenizeData.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeData.java index 33bba2b9..0e1b6b63 100644 --- a/src/main/java/com/skyflow/vault/tokens/DetokenizeData.java +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeData.java @@ -8,12 +8,12 @@ public class DetokenizeData { public DetokenizeData(String token) { this.token = token; - this.redactionType = RedactionType.PLAIN_TEXT; + this.redactionType = RedactionType.DEFAULT; } public DetokenizeData(String token, RedactionType redactionType) { this.token = token; - this.redactionType = redactionType == null ? RedactionType.PLAIN_TEXT : redactionType; + this.redactionType = redactionType == null ? RedactionType.DEFAULT : redactionType; } public String getToken() { diff --git a/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java index 31ff64b2..bd1d7cde 100644 --- a/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java @@ -1,6 +1,9 @@ package com.skyflow.vault.tokens; +import com.google.gson.ExclusionStrategy; +import com.google.gson.FieldAttributes; import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import java.util.ArrayList; @@ -23,7 +26,29 @@ public ArrayList getErrors() { @Override public String toString() { - Gson gson = new Gson(); + Gson gson = new GsonBuilder() + .serializeNulls() + .registerTypeAdapter( + DetokenizeRecordResponse.class, + (com.google.gson.JsonSerializer) (src, typeOfSrc, context) -> { + com.google.gson.JsonObject obj = new com.google.gson.JsonObject(); + obj.addProperty("token", src.getToken()); + if (src.getValue() != null) { + obj.addProperty("value", src.getValue()); + } + if (src.getType() != null) { + obj.addProperty("type", src.getType()); + } + if (src.getError() != null) { + obj.add("error", context.serialize(src.getError())); + } + if (src.getRequestId() != null) { + obj.addProperty("requestId", src.getRequestId()); + } + return obj; + } + ) + .create(); return gson.toJson(this); } } diff --git a/src/test/java/com/skyflow/errors/SkyflowExceptionTest.java b/src/test/java/com/skyflow/errors/SkyflowExceptionTest.java index 89e0643b..e2a1d921 100644 --- a/src/test/java/com/skyflow/errors/SkyflowExceptionTest.java +++ b/src/test/java/com/skyflow/errors/SkyflowExceptionTest.java @@ -3,10 +3,7 @@ import org.junit.Assert; import org.junit.Test; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; public class SkyflowExceptionTest { @@ -38,6 +35,8 @@ public void testConstructorWithCodeAndMessage() { Assert.assertEquals(Integer.valueOf(400), Integer.valueOf(ex.getHttpCode())); Assert.assertEquals("Bad Request", ex.getMessage()); Assert.assertEquals("Bad Request", ex.toString().contains("Bad Request") ? "Bad Request" : null); + Assert.assertNotNull(ex.getDetails()); + Assert.assertEquals(0, ex.getDetails().size()); } @Test @@ -49,7 +48,7 @@ public void testToStringFormat() { } @Test - public void testConstructorWithJsonErrorBody() { + public void testConstructorWithJsonErrorBodyArrayDetailsNonEmpty() { String json = "{\"error\":{\"message\":\"json error\",\"grpc_code\":7,\"http_status\":\"NOT_FOUND\",\"details\":[{\"info\":\"detail1\"}]}}"; Map> headers = new HashMap<>(); headers.put("x-request-id", Collections.singletonList("req-123")); @@ -62,21 +61,29 @@ public void testConstructorWithJsonErrorBody() { Assert.assertTrue(ex.getDetails().size() > 0); } + @Test + public void testConstructorWithJsonErrorBodyArrayDetailsEmpty() { + String json = "{\"error\":{\"message\":\"json error\",\"grpc_code\":7,\"http_status\":\"NOT_FOUND\",\"details\":[]}}"; + Map> headers = new HashMap<>(); + SkyflowException ex = new SkyflowException(404, new RuntimeException("fail"), headers, json); + Assert.assertEquals("json error", ex.getMessage()); + Assert.assertEquals(Integer.valueOf(7), ex.getGrpcCode()); + Assert.assertEquals("NOT_FOUND", ex.getHttpStatus()); + Assert.assertNotNull(ex.getDetails()); + Assert.assertEquals(0, ex.getDetails().size()); + } @Test public void testConstructorWithNullErrorBody() { Map> headers = new HashMap<>(); SkyflowException ex = new SkyflowException(500, new RuntimeException("fail"), headers, null); - Assert.assertNull(ex.getMessage()); + Assert.assertEquals("fail", ex.getMessage()); Assert.assertNull(ex.getGrpcCode()); - Assert.assertNull(ex.getHttpStatus()); } @Test public void testGettersAndSetters() { SkyflowException ex = new SkyflowException("msg"); - // Simulate setting fields via reflection or constructor - // (getters are already tested above) Assert.assertNull(ex.getRequestId()); Assert.assertNull(ex.getDetails()); Assert.assertNull(ex.getGrpcCode()); @@ -95,4 +102,39 @@ public void testSetDetailsWithErrorFromClientHeader() { Assert.assertEquals(1, ex.getDetails().size()); Assert.assertEquals("client error", ex.getDetails().get(0).getAsJsonObject().get("errorFromClient").getAsString()); } + + @Test + public void testSetDetailsWithErrorFromClientHeaderAndNullDetails() { + String json = "{\"error\":{\"message\":\"test error\",\"grpc_code\":13}}"; + Map> headers = new HashMap<>(); + headers.put("error-from-client", Collections.singletonList("client error")); + + SkyflowException ex = new SkyflowException(500, new RuntimeException("fail"), headers, json); + + Assert.assertNotNull(ex.getDetails()); + Assert.assertEquals(1, ex.getDetails().size()); + Assert.assertEquals("client error", ex.getDetails().get(0).getAsJsonObject().get("errorFromClient").getAsString()); + } + + @Test + public void testSetDetailsWithNoErrorFromClientHeaderAndEmptyDetails() { + String json = "{\"error\":{\"message\":\"test error\",\"grpc_code\":13,\"details\":[]}}"; + Map> headers = new HashMap<>(); + + SkyflowException ex = new SkyflowException(500, new RuntimeException("fail"), headers, json); + + Assert.assertNotNull(ex.getDetails()); + Assert.assertEquals(0, ex.getDetails().size()); + } + + @Test + public void testToStringWithNullFields() { + SkyflowException ex = new SkyflowException("msg"); + String str = ex.toString(); + Assert.assertTrue(str.contains("requestId: null")); + Assert.assertTrue(str.contains("grpcCode: null")); + Assert.assertTrue(str.contains("httpCode: null")); + Assert.assertTrue(str.contains("httpStatus: null")); + Assert.assertTrue(str.contains("details: null")); + } } \ No newline at end of file diff --git a/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java index 42ad9bc7..04083077 100644 --- a/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java +++ b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java @@ -214,8 +214,11 @@ public void testSignedDataTokenResponse() { try { String signedToken = "test_signed_data_token"; SignedDataTokenResponse response = new SignedDataTokenResponse(dataToken, signedToken); - String responseString = "{\"token\":\"" + dataToken + "\"," + - "\"signedToken\":\"signed_token_" + signedToken + "\"}"; + String responseString = "{" + + "\"token\":\"" + dataToken + "\"," + + "\"signedToken\":\"signed_token_" + signedToken + "\"" + + "}"; + Assert.assertEquals(responseString, response.toString()); Assert.assertEquals(dataToken, response.getToken()); Assert.assertEquals("signed_token_" + signedToken, response.getSignedToken()); diff --git a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java index a29a3335..63717b5c 100644 --- a/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java +++ b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java @@ -425,9 +425,11 @@ public void testInvokeConnectionResponse() { data.addProperty("test_key_2", "test_value_2"); HashMap metadata = new HashMap<>(); metadata.put("requestId", "12345"); - InvokeConnectionResponse connectionResponse = new InvokeConnectionResponse(data, metadata); + InvokeConnectionResponse connectionResponse = new InvokeConnectionResponse(data, metadata, null); String responseString = "{\"data\":{\"test_key_1\":\"test_value_1\",\"test_key_2\":\"test_value_2\"}," + - "\"metadata\":{\"requestId\":\"12345\"}}"; + "\"metadata\":{\"requestId\":\"12345\"}," + + "\"errors\":null}"; + Assert.assertNotNull(connectionResponse.getData()); Assert.assertEquals(responseString, connectionResponse.toString()); Assert.assertEquals(1, connectionResponse.getMetadata().size()); diff --git a/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java index 5f3ae771..4115bc2c 100644 --- a/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java +++ b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java @@ -165,4 +165,24 @@ public void testInvalidRequestInTokenizeMethod() { } } + @Test + public void testInvalidRequestInFileUploadMethod() { + try { + FileUploadRequest request = FileUploadRequest.builder().build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.vault().uploadFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertNull(e.getRequestId()); + Assert.assertNull(e.getGrpcCode()); + Assert.assertTrue(e.getDetails().isEmpty()); + Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + } + } + } diff --git a/src/test/java/com/skyflow/vault/data/FileUploadTests.java b/src/test/java/com/skyflow/vault/data/FileUploadTests.java new file mode 100644 index 00000000..7758fe36 --- /dev/null +++ b/src/test/java/com/skyflow/vault/data/FileUploadTests.java @@ -0,0 +1,222 @@ +package com.skyflow.vault.data; + +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; + +public class FileUploadTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String table; + private static String skyflowId; + private static String columnName; + private static String filePath; + private static String base64Content; + private static File fileObject; + private static String fileName; + + @BeforeClass + public static void setup() { + table = "test_table"; + skyflowId = "test_id"; + columnName = "file_column"; + filePath = "src/test/resources/notJson.txt"; + base64Content = "SGVsbG8gV29ybGQ="; + fileObject = new File(filePath); + fileName = "notJson.txt"; + } + + @Test + public void testValidFileUploadRequestWithFilePath() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId(skyflowId) + .columnName(columnName) + .filePath(filePath) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.assertEquals(table, request.getTable()); + Assert.assertEquals(skyflowId, request.getSkyflowId()); + Assert.assertEquals(columnName, request.getColumnName()); + Assert.assertEquals(filePath, request.getFilePath()); + Assert.assertEquals(fileName, request.getFileName()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testValidFileUploadRequestWithBase64() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId(skyflowId) + .columnName(columnName) + .base64(base64Content) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.assertEquals(base64Content, request.getBase64()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testValidFileUploadRequestWithFileObject() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId(skyflowId) + .columnName(columnName) + .fileObject(fileObject) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.assertEquals(fileObject, request.getFileObject()); + } catch (SkyflowException e) { + System.out.println("## e:" + e.getMessage()); + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testMissingTable() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .skyflowId(skyflowId) + .columnName(columnName) + .filePath(filePath) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testMissingSkyflowId() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .columnName(columnName) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.SkyflowIdKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptySkyflowId() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId("") + .columnName(columnName) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptySkyflowId.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testMissingColumnName() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId(skyflowId) + .filePath(filePath) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.ColumnNameKeyErrorFileUpload.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testMissingFileData() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId(skyflowId) + .columnName(columnName) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.MissingFileSourceInUploadFileRequest.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testMissingFileNameWithBase64Invalid() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId(skyflowId) + .columnName(columnName) + .base64(base64Content) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.FileNameMustBeProvidedWithFileObject.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + +} diff --git a/src/test/java/com/skyflow/vault/data/GetTests.java b/src/test/java/com/skyflow/vault/data/GetTests.java index 43b3f132..74306d4b 100644 --- a/src/test/java/com/skyflow/vault/data/GetTests.java +++ b/src/test/java/com/skyflow/vault/data/GetTests.java @@ -271,9 +271,9 @@ public void testNoRedactionInGetRequestValidations() { } catch (SkyflowException e) { Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); Assert.assertEquals( - Utils.parameterizedString(ErrorMessage.RedactionKeyError.getMessage(), Constants.SDK_PREFIX), - e.getMessage() - ); + Utils.parameterizedString(ErrorMessage.UniqueColumnOrIdsKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); } } diff --git a/src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java b/src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java index a1243eea..89cf5114 100644 --- a/src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java +++ b/src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java @@ -26,12 +26,11 @@ public void testAllGettersAndToString() { java.util.List entities = Collections.singletonList(entityInfo); String runId = "run-123"; String status = "SUCCESS"; - java.util.List errors = Arrays.asList("error1", "error2"); FileInfo fileInfo = new FileInfo(fileObject); DeidentifyFileResponse response = new DeidentifyFileResponse( fileInfo, file, type, extension, wordCount, charCount, sizeInKb, - durationInSeconds, pageCount, slideCount, entities, runId, status, errors + durationInSeconds, pageCount, slideCount, entities, runId, status ); Assert.assertEquals(type, response.getType()); @@ -45,7 +44,6 @@ public void testAllGettersAndToString() { Assert.assertEquals(entities, response.getEntities()); Assert.assertEquals(runId, response.getRunId()); Assert.assertEquals(status, response.getStatus()); - Assert.assertEquals(errors, response.getErrors()); // toString should return a JSON string containing all fields String json = response.toString(); @@ -54,7 +52,6 @@ public void testAllGettersAndToString() { Assert.assertTrue(json.contains(extension)); Assert.assertTrue(json.contains(runId)); Assert.assertTrue(json.contains(status)); - Assert.assertTrue(json.contains("error1")); Assert.assertTrue(json.contains("PERSON")); } } \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java index ed6804b5..d417aeb7 100644 --- a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java +++ b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -136,7 +136,7 @@ public void testRedactionAndContinueOnErrorInDetokenizeRequestValidations() { detokenizeData(detokenizeData).continueOnError(null).build(); try { Validations.validateDetokenizeRequest(request); - Assert.assertEquals(RedactionType.PLAIN_TEXT, request.getDetokenizeData().get(0).getRedactionType()); + Assert.assertEquals(RedactionType.DEFAULT, request.getDetokenizeData().get(0).getRedactionType()); Assert.assertFalse(request.getContinueOnError()); Assert.assertFalse(request.getDownloadURL()); } catch (SkyflowException e) { From 4ef720a1177dd8dc6c1a31ad3a3d3b6fd08e5ebe Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow Date: Wed, 10 Sep 2025 13:12:07 +0000 Subject: [PATCH 122/126] [AUTOMATED] Public Release - 2.0.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index fb6a5d0e..38869a73 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 2.0.0-beta.4 + 2.0.0 jar ${project.groupId}:${project.artifactId} From a490c809b54b8c8e05f3bf7df4cd0ea5618f576d Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow <156889717+saileshwar-skyflow@users.noreply.github.com> Date: Mon, 13 Oct 2025 15:41:59 +0530 Subject: [PATCH 123/126] SK-2342: Update README and samples for V2 (#254) * SK-2342: update readme and samples --- README.md | 176 ++++++++++++++---- samples/pom.xml | 2 +- .../BearerTokenExpiryExample.java | 12 +- .../com/example/vault/DetokenizeExample.java | 3 +- .../com/example/vault/FileUploadExample.java | 69 +++++++ 5 files changed, 215 insertions(+), 47 deletions(-) create mode 100644 samples/src/main/java/com/example/vault/FileUploadExample.java diff --git a/README.md b/README.md index 7c80d174..ed471ba4 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ The Skyflow Java SDK is designed to help with integrating Skyflow into a Java ba - [Update](#update) - [Delete](#delete) - [Query](#query) + - [Upload File](#upload-file) - [Detect](#detect) - [Deidentify Text](#deidentify-text) - [Reidentify Text](#reidentify-text) @@ -309,7 +310,7 @@ InsertOptions insertOptions = new InsertOptions(true); **V2 (New)** ```java -InsertRequest upsertRequest = new InsertRequest.builder() +InsertRequest upsertRequest = InsertRequest.builder() .table("") // Replace with the table name .continueOnError(false) // Stop inserting if any record fails .tokenMode(TokenMode.DISABLE) // Disable BYOT @@ -559,7 +560,7 @@ Skyflow returns tokens for the record that was just inserted. # Vault -The [Vault](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault) module performs operations on the vault, including inserting records, detokenizing tokens, and retrieving tokens associated with a `skyflow_id`. +The [Vault](https://github.com/skyflowapi/skyflow-java/tree/main/samples/src/main/java/com/example/vault) module performs operations on the vault, including inserting records, detokenizing tokens, and retrieving tokens associated with a `skyflow_id`. ## Insert data into the vault @@ -621,7 +622,7 @@ public class InsertSchema { } ``` -### Insert call [example](https://github.com/skyflowapi/skyflow-java/blob/SK-1893-update-readme-for-v2/samples/src/main/java/com/example/vault/InsertExample.java) with `continueOnError` option +### Insert call [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/InsertExample.java) with `continueOnError` option The `continueOnError` flag is a boolean that determines whether insert operation should proceed despite encountering partial errors. Set to `true` to allow the process to continue even if some errors occur. @@ -802,16 +803,16 @@ public class DetokenizeSchema { try { // Initialize Skyflow client // Step 1: Initialize a list of tokens to be detokenized (replace with actual tokens) - ArrayList tokens = new ArrayList<>(); - tokens.add(""); // Replace with your actual token value - tokens.add(""); // Replace with your actual token value - tokens.add(""); // Replace with your actual token value + ArrayList detokenizeData1 = new ArrayList<>(); + DetokenizeData detokenizeDataRecord1 = new DetokenizeData("", RedactionType.PLAIN_TEXT); // Replace with a token to detokenize with PLAIN_TEXT redaction + DetokenizeData detokenizeDataRecord2 = new DetokenizeData("", RedactionType.PLAIN_TEXT); // Replace with another token to detokenize with PLAIN_TEXT redaction + detokenizeData1.add(detokenizeDataRecord1); + detokenizeData1.add(detokenizeDataRecord2); // Step 2: Create the DetokenizeRequest object with the tokens and redaction type DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() - .tokens(tokens) // Provide the list of tokens to be detokenized + .detokenizeData(detokenizeData1) // Specify detokenize data with specified redaction types .continueOnError(true) // Continue even if one token cannot be detokenized - .redactionType(RedactionType.PLAIN_TEXT) // Specify how the detokenized data should be returned (plain text) .build(); // Build the detokenization request // Step 3: Call the Skyflow vault to detokenize the provided tokens @@ -858,16 +859,16 @@ public class DetokenizeExample { try { // Initialize Skyflow client // Step 1: Initialize a list of tokens to be detokenized (replace with actual token values) - ArrayList tokens = new ArrayList<>(); - tokens.add("9738-1683-0486-1480"); // Replace with your actual token value - tokens.add("6184-6357-8409-6668"); // Replace with your actual token value - tokens.add("4914-9088-2814-3840"); // Replace with your actual token value + ArrayList detokenizeData1 = new ArrayList<>(); + DetokenizeData detokenizeDataRecord1 = new DetokenizeData("9738-1683-0486-1480", RedactionType.PLAIN_TEXT); // Replace with a token to detokenize with PLAIN_TEXT redaction + DetokenizeData detokenizeDataRecord2 = new DetokenizeData("6184-6357-8409-6668", RedactionType.PLAIN_TEXT); // Replace with another token to detokenize with PLAIN_TEXT redaction + detokenizeData1.add(detokenizeDataRecord1); + detokenizeData1.add(detokenizeDataRecord2); // Step 2: Create the DetokenizeRequest object with the tokens and redaction type DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() - .tokens(tokens) // Provide the list of tokens to be detokenized - .continueOnError(false) // Stop the process if any token cannot be detokenized - .redactionType(RedactionType.PLAIN_TEXT) // Specify how the detokenized data should be returned (plain text) + .detokenizeData(detokenizeData1) // Specify detokenize data with specified redaction types + .continueOnError(true) // Continue even if one token cannot be detokenized .build(); // Build the detokenization request // Step 3: Call the Skyflow vault to detokenize the provided tokens @@ -897,11 +898,7 @@ Sample response: "token": "6184-6357-8409-6668", "value": "4111111111111119", "type": "STRING", - }, { - "token": "4914-9088-2814-3840", - "value": "4111111111111118", - "type": "STRING", - }] + }], "errors": [] } @@ -931,16 +928,19 @@ public class DetokenizeExample { try { // Initialize Skyflow client // Step 1: Initialize a list of tokens to be detokenized (replace with actual token values) - ArrayList tokens = new ArrayList<>(); - tokens.add("9738-1683-0486-1480"); // Example token value 1 - tokens.add("6184-6357-8409-6668"); // Example token value 2 - tokens.add("4914-9088-2814-384"); // Example token value 3 + // Step 1: Initialize a list of tokens to be detokenized (replace with actual token values) + ArrayList detokenizeData1 = new ArrayList<>(); + DetokenizeData detokenizeDataRecord1 = new DetokenizeData("9738-1683-0486-1480", RedactionType.PLAIN_TEXT); // Replace with a token to detokenize with PLAIN_TEXT redaction + DetokenizeData detokenizeDataRecord2 = new DetokenizeData("6184-6357-8409-6668", RedactionType.PLAIN_TEXT); // Replace with another token to detokenize with PLAIN_TEXT redaction + DetokenizeData detokenizeDataRecord2 = new DetokenizeData("4914-9088-2814-384", RedactionType.PLAIN_TEXT); // Replace with another token to detokenize with PLAIN_TEXT redaction + + detokenizeData1.add(detokenizeDataRecord1); + detokenizeData1.add(detokenizeDataRecord2); // Step 2: Create the DetokenizeRequest object with the tokens and redaction type DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() - .tokens(tokens) // Provide the list of tokens to detokenize - .continueOnError(true) // Continue even if some tokens cannot be detokenized - .redactionType(RedactionType.PLAIN_TEXT) // Specify the format for the detokenized data (plain text) + .detokenizeData(detokenizeData1) // Specify detokenize data with specified redaction types + .continueOnError(true) // Continue even if one token cannot be detokenized .build(); // Build the detokenization request // Step 3: Call the Skyflow vault to detokenize the provided tokens @@ -970,7 +970,7 @@ Sample response: "token": "6184-6357-8409-6668", "value": "4111111111111119", "type": "STRING", - }] + }], "errors": [{ "token": "4914-9088-2814-384", "error": "Token Not Found", @@ -1170,7 +1170,7 @@ public class GetSchema { Retrieve specific records using `skyflow_ids`. Ideal for fetching exact records when IDs are known. -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/GetExample.java) of a get call to retrieve data using Redaction type: +#### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/GetExample.java) of a get call to retrieve data using Redaction type: ```java import com.skyflow.enums.RedactionType; @@ -1250,7 +1250,7 @@ Sample response: Return tokens for records. Ideal for securely processing sensitive data while maintaining data privacy. -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/getExample.java) of get call to retrieve tokens using Skyflow IDs: +#### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/getExample.java) of get call to retrieve tokens using Skyflow IDs: ```java import com.skyflow.enums.RedactionType; @@ -1326,7 +1326,7 @@ Sample response: Retrieve records by unique column values. Ideal for querying data without knowing Skyflow IDs, using alternate unique identifiers. -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/GetExample.java) of get call to retrieve data using column name and column values: +#### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/GetExample.java) of get call to retrieve data using column name and column values: ```java import com.skyflow.enums.RedactionType; @@ -1761,6 +1761,102 @@ Sample response: } ``` +## Upload File + +To upload files to a Skyflow vault, use the `uploadFile` method. The `UploadFileRequest` class accepts parameters such as the file path, table name, and file name. + +### Construct a file upload request + +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.FileUploadRequest; +import com.skyflow.vault.data.FileUploadResponse; + +/** + * This example demonstrates how to upload a file to a Skyflow vault, along with the UploadFileRequest schema. + * + */ +public class UploadFileSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Specify file Object + File file = new File(""); + + // Step 2: Create an UploadFileRequest with the file details + FileUploadRequest uploadFileRequest = FileUploadRequest.builder() + .fileObject(file) // File object + .table("") // Vault table to upload into + .columnName("") // Column to assign to the uploaded file + .skyflowId("") // Skyflow id of the record + .build(); + + // Step 3: Execute the file upload request on the specified Skyflow vault + FileUploadResponse fileUploadResponse = skyflowClient.vault().uploadFile(uploadFileRequest); + System.out.println("File Upload Response: " + fileUploadResponse); + + } catch (SkyflowException e) { + // Step 4: Handle any exceptions that occur during the upload + System.out.println("Error occurred during file upload:"); + e.printStackTrace(); // Print the exception stack trace for debugging + } + } +} + +``` + +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/FileUploadExample.java) of file upload call +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.FileUploadRequest; +import com.skyflow.vault.data.FileUploadResponse; + +/** + * This example demonstrates how to upload a file to a Skyflow vault. + * + * 1. Initializes the Skyflow client with the Vault ID. + * 2. Constructs a file upload request with the file path, table name, and file name. + * 3. Executes the upload request against the Skyflow vault. + * 4. Prints the response from the upload. + */ +public class UploadFileExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Specify file Object + File file = new File("test/sample.txt"); + + // Step 2: Create an UploadFileRequest with the file details + FileUploadRequest uploadFileRequest = FileUploadRequest.builder() + .fileObject(file) // File object + .table("cards") // Vault table to upload into + .columnName("file") // Column to assign to the uploaded file + .skyflowId("c9312531-2087-439a-bd26-74c41f24db83") // Skyflow id of the record + .build(); + + // Step 3: Execute the file upload request + FileUploadResponse uploadResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").uploadFile(uploadFileRequest); + System.out.println("File Upload Response: " + fileUploadResponse); + + } catch (SkyflowException e) { + // Step 4: Handle any exceptions during the upload + System.out.println("Error occurred during file upload:"); + e.printStackTrace(); // Print exception details for debugging + } + } +} + +``` + +Sample response: + +```json +{ + "skyflowId": "c9312531-2087-439a-bd26-74c41f24db83", + "errors": null +} +``` + # Detect Skyflow Detect enables you to deidentify and reidentify sensitive data in text and files, supporting advanced privacy-preserving workflows. The Detect API supports the following operations: @@ -1850,7 +1946,7 @@ public class DeidentifyTextSchema { ``` -## An [example](https://github.com/skyflowapi/skyflow-java/blob/beta-release/25.6.2/samples/src/main/java/com/example/detect/DeidentifyTextExample.java) of deidentify text: +## An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/detect/DeidentifyTextExample.java) of deidentify text: ```java import java.util.ArrayList; import java.util.List; @@ -2013,7 +2109,7 @@ public class ReidentifyTextSchema { } ``` -## An [example](https://github.com/skyflowapi/skyflow-java/blob/beta-release/25.6.2/samples/src/main/java/com/example/detect/ReidentifyTextExample.java) of Reidentify text +## An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/detect/ReidentifyTextExample.java) of Reidentify text ```java import com.skyflow.enums.DetectEntities; @@ -2164,7 +2260,7 @@ public class DeidentifyFileSchema { } ``` -## An [example](https://github.com/skyflowapi/skyflow-java/blob/beta-release/25.6.2/samples/src/main/java/com/example/detect/DeidentifyFileExample.java) of Deidentify file +## An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/detect/DeidentifyFileExample.java) of Deidentify file ```java import java.io.File; @@ -2205,7 +2301,7 @@ public class DeidentifyFileExample { .build(); // Output configuration - String outputDirectory = "deidenfied-file/"; // Replace with the desired output directory to save the deidentified file + String outputDirectory = "deidentified-file/"; // Replace with the desired output directory to save the deidentified file // Entities to detect // List detectEntities = new ArrayList<>(); @@ -2226,7 +2322,7 @@ public class DeidentifyFileExample { .build(); // Step 3: Invoking deidentifyFile - // Replace `9f27764a10f7946fe56b3258e117` with the acutal vault id + // Replace `9f27764a10f7946fe56b3258e117` with the actual vault id DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect("9f27764a10f7946fe56b3258e117").deidentifyFile(deidentifyFileRequest); System.out.println("Deidentify file response: " + deidentifyFileResponse.toString()); } catch (SkyflowException e) { @@ -2343,7 +2439,7 @@ public class GetDetectRunSchema { ``` -## An [example](https://github.com/skyflowapi/skyflow-java/blob/beta-release/25.6.2/samples/src/main/java/com/example/detect/GetDetectRunExample.java) of get run +## An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/detect/GetDetectRunExample.java) of get run ```java import com.skyflow.config.Credentials; import com.skyflow.config.VaultConfig; @@ -2606,7 +2702,7 @@ This section covers methods for generating and managing tokens to authenticate A ## Generate a bearer token -The [Service Account](https://github.com/skyflowapi/skyflow-java/tree/v2/src/main/java/com/skyflow/serviceaccount/util) Java module generates service account tokens using a service account credentials file, which is provided when a service account is created. The tokens generated by this module are valid for 60 minutes and can be used to make API calls to the [Data](https://docs.skyflow.com/record/) and [Management](https://docs.skyflow.com/management/) APIs, depending on the permissions assigned to the service account. +The [Service Account](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/serviceaccount/util) Java module generates service account tokens using a service account credentials file, which is provided when a service account is created. The tokens generated by this module are valid for 60 minutes and can be used to make API calls to the [Data](https://docs.skyflow.com/record/) and [Management](https://docs.skyflow.com/management/) APIs, depending on the permissions assigned to the service account. The `BearerToken` utility class generates bearer tokens using a credentials JSON file. Alternatively, you can pass the credentials as a string. @@ -2887,7 +2983,7 @@ message: Authentication failed. Bearer token is expired. Use a valid bearer toke If you encounter this kind of error, retry the request. During the retry, the SDK detects that the previous bearer token has expired and generates a new one for the current and subsequent requests. -#### [Example](https://github.com/skyflowapi/skyflow-java/blob/v2/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java): +#### [Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java): ```java package com.example.serviceaccount; diff --git a/samples/pom.xml b/samples/pom.xml index c48ba302..9d690678 100644 --- a/samples/pom.xml +++ b/samples/pom.xml @@ -18,7 +18,7 @@ com.skyflow skyflow-java - 1.15.0 + 2.0.0 diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java index 1f56296d..48889218 100644 --- a/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java @@ -7,6 +7,7 @@ import com.skyflow.enums.LogLevel; import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.DetokenizeData; import com.skyflow.vault.tokens.DetokenizeRequest; import com.skyflow.vault.tokens.DetokenizeResponse; import io.github.cdimascio.dotenv.Dotenv; @@ -66,15 +67,16 @@ public static void main(String[] args) { */ public static void detokenizeData(Skyflow skyflowClient) throws SkyflowException { // Creating a list of tokens to be detokenized - ArrayList tokenList = new ArrayList<>(); - tokenList.add(""); // First token - tokenList.add(""); // Second token + DetokenizeData detokenizeDataToken1 = new DetokenizeData("", RedactionType.PLAIN_TEXT); + DetokenizeData detokenizeDataToken2 = new DetokenizeData(""); + ArrayList detokenizeDataList = new ArrayList<>(); + detokenizeDataList.add(detokenizeDataToken1); // First token + detokenizeDataList.add(detokenizeDataToken2); // Second token // Building a detokenization request with the token list and configuration DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() - .tokens(tokenList) // Adding tokens to the request + .detokenizeData(detokenizeDataList) // Adding tokens to the request .continueOnError(false) // Stop on error - .redactionType(RedactionType.PLAIN_TEXT) // Redaction type (e.g., PLAIN_TEXT) .build(); // Sending the detokenization request and receiving the response diff --git a/samples/src/main/java/com/example/vault/DetokenizeExample.java b/samples/src/main/java/com/example/vault/DetokenizeExample.java index b5d87d49..c81aada5 100644 --- a/samples/src/main/java/com/example/vault/DetokenizeExample.java +++ b/samples/src/main/java/com/example/vault/DetokenizeExample.java @@ -5,6 +5,7 @@ import com.skyflow.config.VaultConfig; import com.skyflow.enums.Env; import com.skyflow.enums.LogLevel; +import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; import com.skyflow.vault.tokens.DetokenizeData; import com.skyflow.vault.tokens.DetokenizeRequest; @@ -53,7 +54,7 @@ public static void main(String[] args) throws SkyflowException { detokenizeData1.add(detokenizeDataRecord2); DetokenizeRequest detokenizeRequest1 = DetokenizeRequest.builder() - .detokenizeData(detokenizeData1) // Specify the tokens to detokenize with specified redaction types + .detokenizeData(detokenizeData1) // Specify detokenize data with specified redaction types .continueOnError(true) // Continue processing even if an error occurs for some tokens .build(); diff --git a/samples/src/main/java/com/example/vault/FileUploadExample.java b/samples/src/main/java/com/example/vault/FileUploadExample.java new file mode 100644 index 00000000..de83ae92 --- /dev/null +++ b/samples/src/main/java/com/example/vault/FileUploadExample.java @@ -0,0 +1,69 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.FileUploadRequest; +import com.skyflow.vault.data.FileUploadResponse; + +import java.io.File; + +/** + * This example demonstrates how to use the Skyflow SDK to securely upload a file into a vault. + * + * It includes: + * 1. Setting up vault configurations. + * 2. Creating a Skyflow client. + * 3. Uploading a file to the vault. + * 4. Handling errors during the upload process. + */ +public class FileUploadExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the vault configuration + Credentials credentials = new Credentials(); + credentials.setApiKey(""); // Replace with the actual API key + + // Step 2: Configure the vault connection + VaultConfig primaryVaultConfig = new VaultConfig(); + primaryVaultConfig.setVaultId(""); // Replace with your vault ID + primaryVaultConfig.setClusterId(""); // Replace with your vault cluster ID + primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, SANDBOX) + primaryVaultConfig.setCredentials(credentials); // Associate credentials with the vault configuration + + // Step 3: Set up general Skyflow client credentials + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(""); // Replace with the actual credentials string + + // Step 4: Create the Skyflow client and add vault configurations + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR to limit output + .addVaultConfig(primaryVaultConfig) // Add the vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials + .build(); + + // Example: Upload a file to the vault + try { + // Step 5: Specify the file to be uploaded + File file = new File(""); // Replace with the path to the file you want to upload + + // Step 6: Create the file upload request + FileUploadRequest uploadFileRequest = FileUploadRequest.builder() + .fileObject(file) // File object + .table("") // Vault table to upload into + .columnName("") // Column to assign to the uploaded file + .skyflowId("") // Skyflow id of the record + .build(); + + // Step 7: Perform the file upload operation + FileUploadResponse fileUploadResponse = skyflowClient.vault().uploadFile(uploadFileRequest); + System.out.println("File Upload Response: " + fileUploadResponse); + + } catch (SkyflowException e) { + // Handle any errors that occur during the file upload process + System.out.println("Error during file upload: " + e); + } + } +} From 72bf9a7630e457709efeddb75abc71413a56d29e Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow Date: Mon, 13 Oct 2025 15:50:44 +0530 Subject: [PATCH 124/126] SK-2342: add endorlabsScan yml file --- .github/workflows/endorlabsScan.yml | 50 +++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 .github/workflows/endorlabsScan.yml diff --git a/.github/workflows/endorlabsScan.yml b/.github/workflows/endorlabsScan.yml new file mode 100644 index 00000000..3c316417 --- /dev/null +++ b/.github/workflows/endorlabsScan.yml @@ -0,0 +1,50 @@ +name: Endor Labs Scan Java Project + +on: + workflow_dispatch: + inputs: + java_version: + description: "The version of Java to be used for build" + default: "8.0.422" + required: true + +jobs: + build-and-scan: + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: zulu + java-version: ${{ github.event.inputs.java_version }} + + - name: Create env + id: create-env + run: | + touch .env + echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env + echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + echo TEST_REUSABLE_TOKEN=${{ secrets.TEST_REUSABLE_TOKEN }} >> .env + + - name: create-json + id: create-json + uses: jsdaniell/create-json@1.1.2 + with: + name: "credentials.json" + json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} + + - name: Compile Package + run: mvn -B package -f pom.xml -Dmaven.javadoc.skip=true + + - name: Endor Labs SCA Scan + uses: endorlabs/github-action@main + with: + namespace: "skyflow" + api: "https://api.endorlabs.com" + pr: false + enable_github_action_token: true + scan_dependencies: true + additional_args: "--as-default-branch --call-graph-languages=java" \ No newline at end of file From 17ed385c776998a8c7b2351dea97404d1ff7852e Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow Date: Mon, 13 Oct 2025 19:34:12 +0530 Subject: [PATCH 125/126] SK-2342: update release workflows --- .github/workflows/main.yml | 4 ++-- .github/workflows/release.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index eb104010..db7c9850 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -13,7 +13,7 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-java@v1 with: - java-version: '1.8' + java-version: '11' - name: create-json id: create-json @@ -23,7 +23,7 @@ jobs: json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - name: Build & Run tests with Maven - run: mvn -B package -DTEST_VAULT_ID=${{ secrets.TEST_VAULT_ID }} -DTEST_VAULT_URL=${{ secrets.TEST_VAULT_URL }} -DTEST_SKYFLOW_ID=${{ secrets.TEST_SKYFLOW_ID }} -DTEST_TOKEN=${{ secrets.TEST_TOKEN }} -DTEST_CREDENTIALS=${{ secrets.TEST_CREDENTIALS_FILE_STRING }} -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -DTEST_REUSABLE_TOKEN=${{ secrets.TEST_REUSABLE_TOKEN }} -f pom.xml + run: mvn -B package -f pom.xml -Dmaven.javadoc.skip=true - name: Codecov uses: codecov/codecov-action@v2.1.0 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1cc20ca1..720e16d8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,7 +1,7 @@ name: Public release on: push: - tags: '*.*.*' + tags: '[0-9]+.[0-9]+.[0-9]+' jobs: build-and-deploy: uses: ./.github/workflows/shared-build-and-deploy.yml From 96649eefef732ed716518b82b3adc1782bf43864 Mon Sep 17 00:00:00 2001 From: saileshwar-skyflow Date: Mon, 13 Oct 2025 22:49:59 +0530 Subject: [PATCH 126/126] SK-2342: update samples --- .../example/detect/DeidentifyFileExample.java | 2 +- .../example/detect/DeidentifyTextExample.java | 4 +-- .../example/detect/GetDetectRunExample.java | 2 +- .../java/com/example/vault/DeleteExample.java | 16 ++++----- .../com/example/vault/DetokenizeExample.java | 36 +++++-------------- .../com/example/vault/FileUploadExample.java | 14 ++++---- .../java/com/example/vault/GetExample.java | 18 +++++----- .../java/com/example/vault/InsertExample.java | 18 +++++----- .../java/com/example/vault/UpdateExample.java | 14 ++++---- 9 files changed, 52 insertions(+), 72 deletions(-) diff --git a/samples/src/main/java/com/example/detect/DeidentifyFileExample.java b/samples/src/main/java/com/example/detect/DeidentifyFileExample.java index 7f573d33..214aa42d 100644 --- a/samples/src/main/java/com/example/detect/DeidentifyFileExample.java +++ b/samples/src/main/java/com/example/detect/DeidentifyFileExample.java @@ -42,7 +42,7 @@ public static void main(String[] args) throws SkyflowException { // Step 3: Create a Skyflow client Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR .addVaultConfig(vaultConfig) // Add the vault configuration .build(); diff --git a/samples/src/main/java/com/example/detect/DeidentifyTextExample.java b/samples/src/main/java/com/example/detect/DeidentifyTextExample.java index 837dde00..1611f9bb 100644 --- a/samples/src/main/java/com/example/detect/DeidentifyTextExample.java +++ b/samples/src/main/java/com/example/detect/DeidentifyTextExample.java @@ -36,7 +36,7 @@ public static void main(String[] args) throws SkyflowException { VaultConfig blitzConfig = new VaultConfig(); blitzConfig.setVaultId(""); // Replace with the ID of the first vault blitzConfig.setClusterId(""); // Replace with the cluster ID of the first vault - blitzConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) + blitzConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) blitzConfig.setCredentials(credentials); // Associate the credentials with the vault // Step 3: Configure the second vault (Stage) @@ -51,7 +51,7 @@ public static void main(String[] args) throws SkyflowException { // Step 5: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR .addVaultConfig(blitzConfig) // Add the first vault configuration .addVaultConfig(stageConfig) // Add the second vault configuration .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials diff --git a/samples/src/main/java/com/example/detect/GetDetectRunExample.java b/samples/src/main/java/com/example/detect/GetDetectRunExample.java index 09fc2bc4..a8f7f39d 100644 --- a/samples/src/main/java/com/example/detect/GetDetectRunExample.java +++ b/samples/src/main/java/com/example/detect/GetDetectRunExample.java @@ -34,7 +34,7 @@ public static void main(String[] args) throws SkyflowException { // Step 3: Create a Skyflow client Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR .addVaultConfig(vaultConfig) // Add the vault configuration .build(); diff --git a/samples/src/main/java/com/example/vault/DeleteExample.java b/samples/src/main/java/com/example/vault/DeleteExample.java index 9fe41f61..74a8e530 100644 --- a/samples/src/main/java/com/example/vault/DeleteExample.java +++ b/samples/src/main/java/com/example/vault/DeleteExample.java @@ -28,12 +28,12 @@ public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); credentials.setPath(""); // Replace with the actual path to the credentials file - // Step 2: Configure the first vault - VaultConfig primaryVaultConfig = new VaultConfig(); - primaryVaultConfig.setVaultId(""); // Replace with the ID of the first vault - primaryVaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault - primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) - primaryVaultConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the ID of the first vault + vaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate the credentials with the vault // Step 3: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); @@ -42,11 +42,11 @@ public static void main(String[] args) throws SkyflowException { // Step 4: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.ERROR) // Set log level for debugging and error tracking - .addVaultConfig(primaryVaultConfig) // Add the first vault configuration + .addVaultConfig(vaultConfig) // Add the vault configuration .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - // Step 5: Delete a record from the first vault + // Step 5: Delete a record from the vault try { ArrayList ids = new ArrayList<>(); ids.add(""); // Replace with the ID of the record to delete diff --git a/samples/src/main/java/com/example/vault/DetokenizeExample.java b/samples/src/main/java/com/example/vault/DetokenizeExample.java index c81aada5..ec9c37df 100644 --- a/samples/src/main/java/com/example/vault/DetokenizeExample.java +++ b/samples/src/main/java/com/example/vault/DetokenizeExample.java @@ -27,12 +27,12 @@ public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); credentials.setToken(""); // Replace with the actual bearer token - // Step 2: Configure the first vault - VaultConfig primaryVaultConfig = new VaultConfig(); - primaryVaultConfig.setVaultId(""); // Replace with the ID of the first vault - primaryVaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault - primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) - primaryVaultConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the ID of the first vault + vaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate the credentials with the vault // Step 3: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); @@ -41,11 +41,11 @@ public static void main(String[] args) throws SkyflowException { // Step 4: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.ERROR) // Set log level to ERROR to capture only critical logs - .addVaultConfig(primaryVaultConfig) // Add the first vault configuration + .addVaultConfig(vaultConfig) // Add the vault configuration .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - // Step 5: Detokenize tokens from the first vault + // Step 5: Detokenize tokens from the vault try { ArrayList detokenizeData1 = new ArrayList<>(); DetokenizeData detokenizeDataRecord1 = new DetokenizeData("", RedactionType.MASKED); // Replace with a token to detokenize with MASKED redaction @@ -64,25 +64,5 @@ public static void main(String[] args) throws SkyflowException { System.out.println("Error during detokenization in Vault 1:"); e.printStackTrace(); } - - // Example 2: Detokenize tokens from the second vault - try { - ArrayList detokenizeData2 = new ArrayList<>(); - DetokenizeData detokenizeDataRecord3 = new DetokenizeData("", RedactionType.DEFAULT); // Replace with a token to detokenize - DetokenizeData detokenizeDataRecord4 = new DetokenizeData(""); // Replace with another token to detokenize - detokenizeData2.add(detokenizeDataRecord3); - detokenizeData2.add(detokenizeDataRecord4); - - DetokenizeRequest detokenizeRequest2 = DetokenizeRequest.builder() - .detokenizeData(detokenizeData2) // Specify the tokens to detokenize with specified redaction types - .continueOnError(false) // Stop processing on the first error - .downloadURL(true) // Specify whether to return URLs for file data type - .build(); - - DetokenizeResponse detokenizeResponse2 = skyflowClient.vault("").detokenize(detokenizeRequest2); // Perform detokenization - System.out.println("Detokenize Response (Vault 2): " + detokenizeResponse2); - } catch (SkyflowException e) { - System.out.println("Error during detokenization in Vault: " + e); - } } } diff --git a/samples/src/main/java/com/example/vault/FileUploadExample.java b/samples/src/main/java/com/example/vault/FileUploadExample.java index de83ae92..0ad267c2 100644 --- a/samples/src/main/java/com/example/vault/FileUploadExample.java +++ b/samples/src/main/java/com/example/vault/FileUploadExample.java @@ -26,12 +26,12 @@ public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); credentials.setApiKey(""); // Replace with the actual API key - // Step 2: Configure the vault connection - VaultConfig primaryVaultConfig = new VaultConfig(); - primaryVaultConfig.setVaultId(""); // Replace with your vault ID - primaryVaultConfig.setClusterId(""); // Replace with your vault cluster ID - primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, SANDBOX) - primaryVaultConfig.setCredentials(credentials); // Associate credentials with the vault configuration + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with your vault ID + vaultConfig.setClusterId(""); // Replace with your vault cluster ID + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, SANDBOX) + vaultConfig.setCredentials(credentials); // Associate credentials with the vault configuration // Step 3: Set up general Skyflow client credentials Credentials skyflowCredentials = new Credentials(); @@ -40,7 +40,7 @@ public static void main(String[] args) throws SkyflowException { // Step 4: Create the Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.ERROR) // Set log level to ERROR to limit output - .addVaultConfig(primaryVaultConfig) // Add the vault configuration + .addVaultConfig(vaultConfig) // Add the vault configuration .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); diff --git a/samples/src/main/java/com/example/vault/GetExample.java b/samples/src/main/java/com/example/vault/GetExample.java index 6d300752..8d4cee2e 100644 --- a/samples/src/main/java/com/example/vault/GetExample.java +++ b/samples/src/main/java/com/example/vault/GetExample.java @@ -25,12 +25,12 @@ public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); credentials.setCredentialsString(""); // Replace with the actual credentials string - // Step 2: Configure the first vault - VaultConfig primaryVaultConfig = new VaultConfig(); - primaryVaultConfig.setVaultId(""); // Replace with the ID of the first vault - primaryVaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault - primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) - primaryVaultConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the ID of the first vault + vaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate the credentials with the vault // Step 3: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); @@ -39,11 +39,11 @@ public static void main(String[] args) throws SkyflowException { // Step 4: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.ERROR) // Set log level to ERROR to minimize log output - .addVaultConfig(primaryVaultConfig) // Add the first vault configuration + .addVaultConfig(vaultConfig) // Add the first vault configuration .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - // Example 1: Fetch records by Skyflow IDs from the first vault + // Example 1: Fetch records by Skyflow IDs from the vault try { ArrayList ids = new ArrayList<>(); ids.add(""); // Replace with the Skyflow ID to fetch the record @@ -60,7 +60,7 @@ public static void main(String[] args) throws SkyflowException { e.printStackTrace(); } - // Example 2: Fetch records by column values from the second vault + // Example 2: Fetch records by column values from the vault try { ArrayList columnValues = new ArrayList<>(); columnValues.add(""); // Replace with the column value to fetch the record diff --git a/samples/src/main/java/com/example/vault/InsertExample.java b/samples/src/main/java/com/example/vault/InsertExample.java index 25610b2b..a6b4ca83 100644 --- a/samples/src/main/java/com/example/vault/InsertExample.java +++ b/samples/src/main/java/com/example/vault/InsertExample.java @@ -27,12 +27,12 @@ public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); credentials.setApiKey(""); // Replace with the actual API key - // Step 2: Configure the first vault - VaultConfig primaryVaultConfig = new VaultConfig(); - primaryVaultConfig.setVaultId(""); // Replace with the first vault ID - primaryVaultConfig.setClusterId(""); // Replace with the first vault cluster ID - primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, SANDBOX) - primaryVaultConfig.setCredentials(credentials); // Associate credentials with the vault + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the vault ID + vaultConfig.setClusterId(""); // Replace with the first vault cluster ID + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, SANDBOX) + vaultConfig.setCredentials(credentials); // Associate credentials with the vault // Step 3: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); @@ -41,11 +41,11 @@ public static void main(String[] args) throws SkyflowException { // Step 4: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.ERROR) // Set log level to ERROR to limit output - .addVaultConfig(primaryVaultConfig) // Add the vault configuration + .addVaultConfig(vaultConfig) // Add the vault configuration .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build(); - // Example 1: Insert records into the first vault with TokenMode enabled + // Example 1: Insert records into the vault with TokenMode enabled try { ArrayList> values1 = new ArrayList<>(); HashMap value1 = new HashMap<>(); @@ -73,7 +73,7 @@ public static void main(String[] args) throws SkyflowException { System.out.println("Error during insertion with TokenMode enabled:" + e); } - // Example 2: Insert records into the first vault with TokenMode disabled and upsert enabled + // Example 2: Insert records into the vault with TokenMode disabled and upsert enabled try { ArrayList> values2 = new ArrayList<>(); HashMap value2 = new HashMap<>(); diff --git a/samples/src/main/java/com/example/vault/UpdateExample.java b/samples/src/main/java/com/example/vault/UpdateExample.java index d5c5ed02..a5947780 100644 --- a/samples/src/main/java/com/example/vault/UpdateExample.java +++ b/samples/src/main/java/com/example/vault/UpdateExample.java @@ -25,12 +25,12 @@ public static void main(String[] args) throws SkyflowException { Credentials credentials = new Credentials(); credentials.setApiKey(""); // Replace with the actual API key - // Step 2: Configure the first vault - VaultConfig primaryVaultConfig = new VaultConfig(); - primaryVaultConfig.setVaultId(""); // Replace with the ID of the first vault - primaryVaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault - primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) - primaryVaultConfig.setCredentials(credentials); // Associate the credentials with the vault + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the ID of the vault + vaultConfig.setClusterId(""); // Replace with the cluster ID of the vault + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate the credentials with the vault // Step 3: Set up credentials for the Skyflow client Credentials skyflowCredentials = new Credentials(); @@ -39,7 +39,7 @@ public static void main(String[] args) throws SkyflowException { // Step 4: Create a Skyflow client and add vault configurations Skyflow skyflowClient = Skyflow.builder() .setLogLevel(LogLevel.ERROR) // Enable debugging for detailed logs - .addVaultConfig(primaryVaultConfig) // Add the first vault configuration + .addVaultConfig(vaultConfig) // Add the vault configuration .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials .build();