diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml new file mode 100644 index 00000000..5d82fda1 --- /dev/null +++ b/.github/workflows/internal-release.yml @@ -0,0 +1,69 @@ +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@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 diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index c3a33dc8..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,6 +31,13 @@ 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 }} -f pom.xml 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 1b5060b0..08afca20 100644 --- a/pom.xml +++ b/pom.xml @@ -32,63 +32,77 @@ - 7 - 7 + 8 + 8 + 4.12.0 + 2.10.1 + 1.9.0 + UTF-8 + 4.12.0 + 4.13.2 + 2.3.1 + 1.3.5 - - - ossrh - https://s01.oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://s01.oss.sonatype.org/service/local/staging/deploy/maven2 - - - + - com.fasterxml.jackson.core - jackson-core - 2.13.0 + io.github.cdimascio + dotenv-java + 2.2.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.12.6 - 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 + javax.xml.bind + jaxb-api + ${javax-xml-bind-version} + junit junit - 4.13.2 + ${junit-version} test @@ -107,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 @@ -135,6 +149,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 @@ -153,11 +175,6 @@ org.jacoco jacoco-maven-plugin 0.8.7 - - - **/example/* - - prepare-agent @@ -173,6 +190,26 @@ + + + **/example/* + **/generated/** + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.3.0 + + + + test-jar + + + + + org.apache.maven.plugins @@ -197,5 +234,43 @@ + + + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ + + + + + + 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 + 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/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/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..431fd79d --- /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(); + skyflowCredentials.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/serviceaccount/BearerTokenGenerationExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java new file mode 100644 index 00000000..5dbd6372 --- /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 (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(); + } + } +} \ 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..8cfba8fa --- /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 = BearerToken.builder() + .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 = BearerToken.builder() + .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/BearerTokenWithContextGenerationExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java similarity index 76% rename from samples/src/main/java/com/example/BearerTokenWithContextGenerationExample.java rename to samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java index 668b7c81..b85de6df 100644 --- a/samples/src/main/java/com/example/BearerTokenWithContextGenerationExample.java +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java @@ -1,46 +1,40 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; +package com.example.serviceaccount; import com.skyflow.errors.SkyflowException; import com.skyflow.serviceaccount.util.BearerToken; import java.io.File; -public class BearerTokenWithContextGenerationExample { - public static void main(String args[]) { - +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() + 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(); 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..3fda1e07 --- /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 = BearerToken.builder() + .setCredentials(new File(filePath)) + .setRoles(roles) + .build(); + + scopedToken = bearerToken.getBearerToken(); + System.out.println(scopedToken); + } catch (SkyflowException 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 = BearerToken.builder() + .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/SignedTokenGenerationExample.java b/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java similarity index 53% rename from samples/src/main/java/com/example/SignedTokenGenerationExample.java rename to samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java index 1fde4236..0acca5fe 100644 --- a/samples/src/main/java/com/example/SignedTokenGenerationExample.java +++ b/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java @@ -1,33 +1,33 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; +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 signedTokenValue; + 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() + 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(new String[]{"dataToken1"}).build(); + .setDataTokens(dataTokens) + .build(); - signedTokenValue = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValue); - } catch (Exception e) { + signedTokenValues = signedToken.getSignedDataTokens(); + System.out.println(signedTokenValues); + } catch (SkyflowException e) { e.printStackTrace(); } @@ -35,19 +35,21 @@ public static void main(String args[]) { try { String fileContents = ""; String context = "abc"; - SignedDataTokens signedToken = new SignedDataTokens.SignedDataTokensBuilder() + ArrayList dataTokens = new ArrayList<>(); + dataTokens.add("YOUR_DATA_TOKEN_1"); + SignedDataTokens signedToken = SignedDataTokens.builder() .setCredentials(fileContents) .setCtx(context) .setTimeToLive(30) // in seconds - .setDataTokens(new String[]{"dataToken1"}).build(); + .setDataTokens(dataTokens) + .build(); - signedTokenValue = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValue); + 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 new file mode 100644 index 00000000..d14554ce --- /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(); + skyflowCredentials.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..cd6d38ad --- /dev/null +++ b/samples/src/main/java/com/example/vault/DetokenizeExample.java @@ -0,0 +1,57 @@ +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.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(); + skyflowCredentials.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..5dda25d3 --- /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(); + skyflowCredentials.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..20070e83 --- /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..d5928cd5 --- /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(); + skyflowCredentials.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..578e7ced --- /dev/null +++ b/samples/src/main/java/com/example/vault/TokenizeExample.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.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 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(); + skyflowCredentials.setPath(""); + + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addVaultConfig(blitzConfig) + .addVaultConfig(stageConfig) + .addSkyflowCredentials(skyflowCredentials) + .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); + } +} 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..1508fc25 --- /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(); + skyflowCredentials.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("") + .table("") + .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("") + .table("") + .tokenStrict(Byot.DISABLE) + .values(values2) + .returnTokens(false) + .build(); + UpdateResponse updateResponse2 = skyflowClient.vault("").update(updateRequest2); + System.out.println(updateResponse2); + } +} diff --git a/scripts/bump_version.sh b/scripts/bump_version.sh new file mode 100755 index 00000000..d729ea63 --- /dev/null +++ b/scripts/bump_version.sh @@ -0,0 +1,40 @@ +# Input Arguments +Version=$1 +CommitHash=$2 +PomFile="$GITHUB_WORKSPACE/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 diff --git a/src/main/java/com/skyflow/Configuration.java b/src/main/java/com/skyflow/Configuration.java deleted file mode 100644 index fac93b8b..00000000 --- a/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/src/main/java/com/skyflow/ConnectionClient.java b/src/main/java/com/skyflow/ConnectionClient.java new file mode 100644 index 00000000..72a70fef --- /dev/null +++ b/src/main/java/com/skyflow/ConnectionClient.java @@ -0,0 +1,86 @@ +package com.skyflow; + +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.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; + + protected ConnectionClient(ConnectionConfig connectionConfig, Credentials credentials) { + super(); + this.connectionConfig = connectionConfig; + this.commonCredentials = credentials; + } + + protected ConnectionConfig getConnectionConfig() { + return connectionConfig; + } + + protected void setCommonCredentials(Credentials commonCredentials) { + this.commonCredentials = commonCredentials; + prioritiseCredentials(); + } + + protected void updateConnectionConfig(ConnectionConfig connectionConfig) { + 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); + } 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() { + 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(Constants.ENV_CREDENTIALS_KEY_NAME); + if (sysCredentials == null) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.EmptyCredentials.getMessage()); + } else { + this.finalCredentials = new Credentials(); + this.finalCredentials.setCredentialsString(sysCredentials); + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/src/main/java/com/skyflow/Skyflow.java b/src/main/java/com/skyflow/Skyflow.java new file mode 100644 index 00000000..2a2e42cc --- /dev/null +++ b/src/main/java/com/skyflow/Skyflow.java @@ -0,0 +1,258 @@ +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 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; + +import java.util.LinkedHashMap; + +public final class Skyflow { + private final SkyflowClientBuilder builder; + + private Skyflow(SkyflowClientBuilder builder) { + this.builder = builder; + LogUtil.printInfoLog(InfoLogs.CLIENT_INITIALIZED.getLog()); + } + + 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) { + return this.builder.vaultConfigMap.get(vaultId); + } + + public Skyflow updateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { + this.builder.updateVaultConfig(vaultConfig); + return this; + } + + public Skyflow removeVaultConfig(String vaultId) throws SkyflowException { + this.builder.removeVaultConfig(vaultId); + return this; + } + + public Skyflow addConnectionConfig(ConnectionConfig connectionConfig) throws SkyflowException { + this.builder.addConnectionConfig(connectionConfig); + return this; + } + + public ConnectionConfig getConnectionConfig(String connectionId) { + return this.builder.connectionConfigMap.get(connectionId); + } + + public Skyflow updateConnectionConfig(ConnectionConfig connectionConfig) throws SkyflowException { + this.builder.updateConnectionConfig(connectionConfig); + return this; + } + + public Skyflow removeConnectionConfig(String connectionId) throws SkyflowException { + this.builder.removeConnectionConfig(connectionId); + return this; + } + + public Skyflow updateSkyflowCredentials(Credentials credentials) throws SkyflowException { + this.builder.addSkyflowCredentials(credentials); + return this; + } + + public Skyflow updateLogLevel(LogLevel logLevel) { + this.builder.setLogLevel(logLevel); + return this; + } + + public LogLevel getLogLevel() { + return this.builder.logLevel; + } + + public VaultController vault() { + String vaultId = (String) this.builder.vaultClientsMap.keySet().toArray()[0]; + return this.vault(vaultId); + } + + public VaultController vault(String vaultId) { + return this.builder.vaultClientsMap.get(vaultId); + } + + public ConnectionController connection() { + String connectionId = (String) this.builder.connectionsMap.keySet().toArray()[0]; + return this.connection(connectionId); + } + + public ConnectionController connection(String connectionId) { + return this.builder.connectionsMap.get(connectionId); + } + + 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; + + 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; + } + + public SkyflowClientBuilder addVaultConfig(VaultConfig vaultConfig) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.VALIDATING_VAULT_CONFIG.getLog()); + Validations.validateVaultConfig(vaultConfig); + if (this.vaultClientsMap.containsKey(vaultConfig.getVaultId())) { + 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(Utils.parameterizedString( + InfoLogs.VAULT_CONTROLLER_INITIALIZED.getLog(), vaultConfig.getVaultId())); + } + return this; + } + + 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(); + } else { + 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; + } + + public SkyflowClientBuilder removeVaultConfig(String vaultId) throws SkyflowException { + if (this.vaultClientsMap.containsKey(vaultId)) { + this.vaultClientsMap.remove(vaultId); + this.vaultConfigMap.remove(vaultId); + } else { + LogUtil.printErrorLog(Utils.parameterizedString(ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog(), vaultId)); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultIdNotInConfigList.getMessage()); + } + return this; + } + + public SkyflowClientBuilder addConnectionConfig(ConnectionConfig connectionConfig) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.VALIDATING_CONNECTION_CONFIG.getLog()); + Validations.validateConnectionConfig(connectionConfig); + if (this.connectionsMap.containsKey(connectionConfig.getConnectionId())) { + 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) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.VALIDATING_CONNECTION_CONFIG.getLog()); + Validations.validateConnectionConfig(connectionConfig); + if (this.connectionsMap.containsKey(connectionConfig.getConnectionId())) { + ConnectionConfig updatedConfig = findAndUpdateConnectionConfig(connectionConfig); + this.connectionsMap.get(updatedConfig.getConnectionId()).updateConnectionConfig(connectionConfig); + } else { + 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) throws SkyflowException { + if (this.connectionsMap.containsKey(connectionId)) { + this.connectionsMap.remove(connectionId); + this.connectionConfigMap.remove(connectionId); + } else { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.CONNECTION_CONFIG_DOES_NOT_EXIST.getLog(), connectionId + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.ConnectionIdNotInConfigList.getMessage()); + } + return this; + } + + 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 connection : this.connectionsMap.values()) { + connection.setCommonCredentials(this.skyflowCredentials); + } + return this; + } + + public SkyflowClientBuilder setLogLevel(LogLevel logLevel) { + this.logLevel = logLevel == null ? LogLevel.ERROR : logLevel; + LogUtil.setupLogger(this.logLevel); + LogUtil.printInfoLog(Utils.parameterizedString( + InfoLogs.CURRENT_LOG_LEVEL.getLog(), String.valueOf(logLevel) + )); + return this; + } + + public Skyflow build() { + return new Skyflow(this); + } + + 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(); + Credentials credentials = vaultConfig.getCredentials() != null ? vaultConfig.getCredentials() : previousConfig.getCredentials(); + previousConfig.setEnv(env); + previousConfig.setClusterId(clusterId); + 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/src/main/java/com/skyflow/VaultClient.java b/src/main/java/com/skyflow/VaultClient.java new file mode 100644 index 00000000..a6a63f64 --- /dev/null +++ b/src/main/java/com/skyflow/VaultClient.java @@ -0,0 +1,223 @@ +package com.skyflow; + +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.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; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +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; + private Credentials finalCredentials; + private String token; + private String apiKey; + + protected VaultClient(VaultConfig vaultConfig, Credentials credentials) { + super(); + this.vaultConfig = vaultConfig; + this.commonCredentials = credentials; + this.apiClient = new ApiClient(); + this.recordsApi = new RecordsApi(this.apiClient); + this.tokensApi = new TokensApi(this.apiClient); + this.queryApi = new QueryApi(this.apiClient); + updateVaultURL(); + } + + protected RecordsApi getRecordsApi() { + return recordsApi; + } + + protected TokensApi getTokensApi() { + return tokensApi; + } + + protected QueryApi getQueryApi() { + return queryApi; + } + + protected ApiClient getApiClient() { + return apiClient; + } + + protected VaultConfig getVaultConfig() { + return vaultConfig; + } + + protected void setCommonCredentials(Credentials commonCredentials) { + this.commonCredentials = commonCredentials; + prioritiseCredentials(); + } + + protected void updateVaultConfig() { + updateVaultURL(); + 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; + } + + protected RecordServiceInsertRecordBody getBulkInsertRequestBody(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)); + if (tokens != null && index < tokens.size()) { + record.setTokens(tokens.get(index)); + } + records.add(record); + } + insertRecordBody.setRecords(records); + 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 && index < tokens.size()) { + 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.getTokenStrict().getBYOT()); + updateRequestBody.setTokenization(request.getReturnTokens()); + HashMap values = request.getData(); + HashMap tokens = request.getTokens(); + V1FieldRecords record = new V1FieldRecords(); + record.setFields(values); + if (tokens != null) { + record.setTokens(tokens); + } + updateRequestBody.setRecord(record); + 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; + } + + 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); + } 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); + } + + 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(Constants.ENV_CREDENTIALS_KEY_NAME); + if (sysCredentials == null) { + 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/src/main/java/com/skyflow/common/utils/Constants.java b/src/main/java/com/skyflow/common/utils/Constants.java deleted file mode 100644 index 05e22578..00000000 --- a/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/src/main/java/com/skyflow/common/utils/Helpers.java b/src/main/java/com/skyflow/common/utils/Helpers.java deleted file mode 100644 index e5c3bbfe..00000000 --- a/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/src/main/java/com/skyflow/common/utils/HttpUtility.java b/src/main/java/com/skyflow/common/utils/HttpUtility.java deleted file mode 100644 index 60cf9aac..00000000 --- a/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/src/main/java/com/skyflow/common/utils/TokenUtils.java b/src/main/java/com/skyflow/common/utils/TokenUtils.java deleted file mode 100644 index 288f2faa..00000000 --- a/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/src/main/java/com/skyflow/common/utils/Validators.java b/src/main/java/com/skyflow/common/utils/Validators.java deleted file mode 100644 index c1eda9e1..00000000 --- a/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/src/main/java/com/skyflow/config/ConnectionConfig.java b/src/main/java/com/skyflow/config/ConnectionConfig.java new file mode 100644 index 00000000..c017b181 --- /dev/null +++ b/src/main/java/com/skyflow/config/ConnectionConfig.java @@ -0,0 +1,38 @@ +package com.skyflow.config; + +public class ConnectionConfig { + private String connectionId; + private String connectionUrl; + private Credentials credentials; + + public ConnectionConfig() { + this.connectionId = null; + this.connectionUrl = null; + this.credentials = null; + } + + public String getConnectionId() { + return connectionId; + } + + public void setConnectionId(String connectionId) { + this.connectionId = connectionId; + } + + public String getConnectionUrl() { + return connectionUrl; + } + + public void setConnectionUrl(String connectionUrl) { + this.connectionUrl = connectionUrl; + } + + public Credentials getCredentials() { + return credentials; + } + + public void setCredentials(Credentials credentials) { + this.credentials = credentials; + } + +} diff --git a/src/main/java/com/skyflow/config/Credentials.java b/src/main/java/com/skyflow/config/Credentials.java new file mode 100644 index 00000000..f1865dc7 --- /dev/null +++ b/src/main/java/com/skyflow/config/Credentials.java @@ -0,0 +1,66 @@ +package com.skyflow.config; + +import java.util.ArrayList; + +public class Credentials { + private String path; + private ArrayList roles; + private String context; + private String credentialsString; + private String token; + private String apiKey; + + public Credentials() { + this.path = null; + this.context = null; + this.credentialsString = null; + } + + 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; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } +} diff --git a/src/main/java/com/skyflow/config/ManagementConfig.java b/src/main/java/com/skyflow/config/ManagementConfig.java new file mode 100644 index 00000000..a054c8ea --- /dev/null +++ b/src/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/src/main/java/com/skyflow/config/VaultConfig.java b/src/main/java/com/skyflow/config/VaultConfig.java new file mode 100644 index 00000000..fd36d384 --- /dev/null +++ b/src/main/java/com/skyflow/config/VaultConfig.java @@ -0,0 +1,58 @@ +package com.skyflow.config; + +import com.skyflow.enums.Env; + +public class VaultConfig { + 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; + } + + public void setClusterId(String clusterId) { + this.clusterId = clusterId; + } + + public Env getEnv() { + return env; + } + + public void setEnv(Env env) { + this.env = env == null ? Env.PROD : env; + } + + public Credentials getCredentials() { + return credentials; + } + + 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/entities/DeleteInput.java b/src/main/java/com/skyflow/entities/DeleteInput.java deleted file mode 100644 index 422d929d..00000000 --- a/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/src/main/java/com/skyflow/entities/DeleteOptions.java b/src/main/java/com/skyflow/entities/DeleteOptions.java deleted file mode 100644 index affa26c6..00000000 --- a/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/src/main/java/com/skyflow/entities/DeleteRecordInput.java b/src/main/java/com/skyflow/entities/DeleteRecordInput.java deleted file mode 100644 index 6e11b2a4..00000000 --- a/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/src/main/java/com/skyflow/entities/DetokenizeInput.java b/src/main/java/com/skyflow/entities/DetokenizeInput.java deleted file mode 100644 index b8d8f908..00000000 --- a/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/src/main/java/com/skyflow/entities/DetokenizeRecord.java b/src/main/java/com/skyflow/entities/DetokenizeRecord.java deleted file mode 100644 index 4bd9ee40..00000000 --- a/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/src/main/java/com/skyflow/entities/GetByIdInput.java b/src/main/java/com/skyflow/entities/GetByIdInput.java deleted file mode 100644 index a31f4b49..00000000 --- a/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/src/main/java/com/skyflow/entities/GetByIdRecordInput.java b/src/main/java/com/skyflow/entities/GetByIdRecordInput.java deleted file mode 100644 index e858bb24..00000000 --- a/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/src/main/java/com/skyflow/entities/GetInput.java b/src/main/java/com/skyflow/entities/GetInput.java deleted file mode 100644 index 786be682..00000000 --- a/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/src/main/java/com/skyflow/entities/GetOptions.java b/src/main/java/com/skyflow/entities/GetOptions.java deleted file mode 100644 index 7620b761..00000000 --- a/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/src/main/java/com/skyflow/entities/GetRecordInput.java b/src/main/java/com/skyflow/entities/GetRecordInput.java deleted file mode 100644 index 169c0c18..00000000 --- a/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/src/main/java/com/skyflow/entities/InsertBulkOptions.java b/src/main/java/com/skyflow/entities/InsertBulkOptions.java deleted file mode 100644 index b7c03963..00000000 --- a/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/src/main/java/com/skyflow/entities/InsertInput.java b/src/main/java/com/skyflow/entities/InsertInput.java deleted file mode 100644 index 0163aace..00000000 --- a/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/src/main/java/com/skyflow/entities/InsertOptions.java b/src/main/java/com/skyflow/entities/InsertOptions.java deleted file mode 100644 index 16739892..00000000 --- a/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/src/main/java/com/skyflow/entities/InsertRecordInput.java b/src/main/java/com/skyflow/entities/InsertRecordInput.java deleted file mode 100644 index 6572b5c0..00000000 --- a/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/src/main/java/com/skyflow/entities/LogLevel.java b/src/main/java/com/skyflow/entities/LogLevel.java deleted file mode 100644 index 3bed5284..00000000 --- a/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/src/main/java/com/skyflow/entities/QueryInput.java b/src/main/java/com/skyflow/entities/QueryInput.java deleted file mode 100644 index 7e578d41..00000000 --- a/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/src/main/java/com/skyflow/entities/QueryOptions.java b/src/main/java/com/skyflow/entities/QueryOptions.java deleted file mode 100644 index 7cc1a3de..00000000 --- a/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/src/main/java/com/skyflow/entities/QueryRecordInput.java b/src/main/java/com/skyflow/entities/QueryRecordInput.java deleted file mode 100644 index 032c4fd0..00000000 --- a/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/src/main/java/com/skyflow/entities/RedactionType.java b/src/main/java/com/skyflow/entities/RedactionType.java deleted file mode 100644 index 7bf240fc..00000000 --- a/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/src/main/java/com/skyflow/entities/ResponseToken.java b/src/main/java/com/skyflow/entities/ResponseToken.java deleted file mode 100644 index d1e4e978..00000000 --- a/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/src/main/java/com/skyflow/entities/SkyflowConfiguration.java b/src/main/java/com/skyflow/entities/SkyflowConfiguration.java deleted file mode 100644 index a240e8ca..00000000 --- a/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/src/main/java/com/skyflow/entities/TokenProvider.java b/src/main/java/com/skyflow/entities/TokenProvider.java deleted file mode 100644 index 95863a21..00000000 --- a/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/src/main/java/com/skyflow/entities/UpdateInput.java b/src/main/java/com/skyflow/entities/UpdateInput.java deleted file mode 100644 index 9c7319d2..00000000 --- a/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/src/main/java/com/skyflow/entities/UpdateOptions.java b/src/main/java/com/skyflow/entities/UpdateOptions.java deleted file mode 100644 index 0f3703ec..00000000 --- a/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/src/main/java/com/skyflow/entities/UpdateRecordInput.java b/src/main/java/com/skyflow/entities/UpdateRecordInput.java deleted file mode 100644 index b6283e80..00000000 --- a/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/src/main/java/com/skyflow/entities/UpsertOption.java b/src/main/java/com/skyflow/entities/UpsertOption.java deleted file mode 100644 index 7c50eb71..00000000 --- a/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/src/main/java/com/skyflow/enums/Byot.java b/src/main/java/com/skyflow/enums/Byot.java new file mode 100644 index 00000000..9fe7d989 --- /dev/null +++ b/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/src/main/java/com/skyflow/enums/Env.java b/src/main/java/com/skyflow/enums/Env.java new file mode 100644 index 00000000..3d1466e9 --- /dev/null +++ b/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/src/main/java/com/skyflow/enums/InterfaceName.java b/src/main/java/com/skyflow/enums/InterfaceName.java new file mode 100644 index 00000000..643bf9da --- /dev/null +++ b/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/src/main/java/com/skyflow/enums/LogLevel.java b/src/main/java/com/skyflow/enums/LogLevel.java new file mode 100644 index 00000000..a605b520 --- /dev/null +++ b/src/main/java/com/skyflow/enums/LogLevel.java @@ -0,0 +1,9 @@ +package com.skyflow.enums; + +public enum LogLevel { + OFF, + ERROR, + WARN, + INFO, + DEBUG +} diff --git a/src/main/java/com/skyflow/enums/RedactionType.java b/src/main/java/com/skyflow/enums/RedactionType.java new file mode 100644 index 00000000..af86a560 --- /dev/null +++ b/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/src/main/java/com/skyflow/entities/RequestMethod.java b/src/main/java/com/skyflow/enums/RequestMethod.java similarity index 82% rename from src/main/java/com/skyflow/entities/RequestMethod.java rename to src/main/java/com/skyflow/enums/RequestMethod.java index 7e2cea75..ffa3d949 100644 --- a/src/main/java/com/skyflow/entities/RequestMethod.java +++ b/src/main/java/com/skyflow/enums/RequestMethod.java @@ -1,7 +1,4 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.entities; +package com.skyflow.enums; public enum RequestMethod { GET("GET"), diff --git a/src/main/java/com/skyflow/errors/ErrorCode.java b/src/main/java/com/skyflow/errors/ErrorCode.java index f996d828..943913c6 100644 --- a/src/main/java/com/skyflow/errors/ErrorCode.java +++ b/src/main/java/com/skyflow/errors/ErrorCode.java @@ -1,79 +1,18 @@ -/* - 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."), + INVALID_INPUT(400), + INVALID_INDEX(404), + SERVER_ERROR(500), + PARTIAL_SUCCESS(500); - BearerTokenExpired(400,"Bearer token is invalid or expired."); private final int code; - private final String description; - ErrorCode(int code, String description) { + ErrorCode(int code) { this.code = code; - this.description = description; } public int getCode() { return code; } - - public String getDescription() { - return description; - } } diff --git a/src/main/java/com/skyflow/errors/ErrorMessage.java b/src/main/java/com/skyflow/errors/ErrorMessage.java new file mode 100644 index 00000000..ac5fd0cf --- /dev/null +++ b/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -0,0 +1,137 @@ +package com.skyflow.errors; + +import com.skyflow.utils.Constants; + +public enum ErrorMessage { + // 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. Specify a valid credentials."), + + // 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 + 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("%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("%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("%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("%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("%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 + 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."), + EmptyQuery("%s0 Validation error. 'query' can't be empty. Specify a query"), + + // 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 + 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."), + 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 = message.replace("%s0", Constants.SDK_PREFIX); + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/com/skyflow/errors/SkyflowException.java b/src/main/java/com/skyflow/errors/SkyflowException.java index 129eb67d..6cff3cdd 100644 --- a/src/main/java/com/skyflow/errors/SkyflowException.java +++ b/src/main/java/com/skyflow/errors/SkyflowException.java @@ -1,54 +1,123 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ package com.skyflow.errors; -import org.json.simple.JSONObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; -public final class SkyflowException extends Exception { - private int code; - private JSONObject data; +import java.util.List; +import java.util.Map; +import java.util.Objects; - public SkyflowException(ErrorCode errorCode) { - super(errorCode.getDescription()); - this.setCode(errorCode.getCode()); +public class SkyflowException extends Exception { + private String requestId; + private Integer grpcCode; + private Integer httpCode; + private String message; + private String httpStatus; + private JsonArray details; + private JsonObject responseBody; + + public SkyflowException(String message) { + super(message); + this.message = 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.httpCode = code; + this.message = message; + } + + public SkyflowException(int httpCode, Throwable cause, Map> responseHeaders, String responseBody) { + this(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; + } } - public SkyflowException(ErrorCode errorCode, Throwable cause) { - super(errorCode.getDescription(), cause); - this.setCode(errorCode.getCode()); + private void setResponseBody(String responseBody) { + try { + if (responseBody != null) { + this.responseBody = JsonParser.parseString(responseBody).getAsJsonObject(); + setGrpcCode(); + setHttpStatus(); + setMessage(); + setDetails(); + } + } catch (JsonSyntaxException e) { + throw new RuntimeException(e); + } } - public SkyflowException(int code, String description) { - super(description); - this.setCode(code); + public String getRequestId() { + return requestId; } - public SkyflowException(int code, String description, Throwable cause) { - super(description, cause); - this.setCode(code); + private void setRequestId(Map> responseHeaders) { + if (responseHeaders != null) { + List ids = responseHeaders.get("x-request-id"); + this.requestId = ids.get(0); + } } - public SkyflowException(int code, String description, JSONObject data) { - super(description); - this.setCode(code); - setData(data); + private void setMessage() { + this.message = ((JsonObject) responseBody.get("error")).get("message").getAsString(); } - public int getCode() { - return code; + private void setGrpcCode() { + this.grpcCode = ((JsonObject) responseBody.get("error")).get("grpc_code").getAsInt(); } - void setCode(int code) { - this.code = code; + 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 getHttpCode() { + return httpCode; + } + + public JsonArray getDetails() { + return details; + } + + public Integer getGrpcCode() { + return grpcCode; + } + + public String getHttpStatus() { + return httpStatus; + } - public JSONObject getData() { - return data; + @Override + public String getMessage() { + return message; } - void setData(JSONObject data) { - this.data = data; + @Override + public String toString() { + return String.format( + "%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 + ); } } diff --git a/src/main/java/com/skyflow/generated/rest/ApiCallback.java b/src/main/java/com/skyflow/generated/rest/ApiCallback.java new file mode 100644 index 00000000..84a241d3 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/ApiClient.java b/src/main/java/com/skyflow/generated/rest/ApiClient.java new file mode 100644 index 00000000..bb0391a4 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/ApiException.java b/src/main/java/com/skyflow/generated/rest/ApiException.java new file mode 100644 index 00000000..d10c995e --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/ApiResponse.java b/src/main/java/com/skyflow/generated/rest/ApiResponse.java new file mode 100644 index 00000000..d3cdb698 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/Configuration.java b/src/main/java/com/skyflow/generated/rest/Configuration.java new file mode 100644 index 00000000..6b12e8bb --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java b/src/main/java/com/skyflow/generated/rest/GzipRequestInterceptor.java new file mode 100644 index 00000000..2b69f358 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/JSON.java b/src/main/java/com/skyflow/generated/rest/JSON.java new file mode 100644 index 00000000..8e6e8375 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/Pair.java b/src/main/java/com/skyflow/generated/rest/Pair.java new file mode 100644 index 00000000..0f182d02 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java b/src/main/java/com/skyflow/generated/rest/ProgressRequestBody.java new file mode 100644 index 00000000..38d16e94 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java b/src/main/java/com/skyflow/generated/rest/ProgressResponseBody.java new file mode 100644 index 00000000..6bd61b5a --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/ServerConfiguration.java b/src/main/java/com/skyflow/generated/rest/ServerConfiguration.java new file mode 100644 index 00000000..f91ef52d --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/ServerVariable.java b/src/main/java/com/skyflow/generated/rest/ServerVariable.java new file mode 100644 index 00000000..53b17180 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/StringUtil.java b/src/main/java/com/skyflow/generated/rest/StringUtil.java new file mode 100644 index 00000000..433e15d7 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/api/AuditApi.java b/src/main/java/com/skyflow/generated/rest/api/AuditApi.java new file mode 100644 index 00000000..6b441971 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java b/src/main/java/com/skyflow/generated/rest/api/AuthenticationApi.java new file mode 100644 index 00000000..e26da776 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java b/src/main/java/com/skyflow/generated/rest/api/BinLookupApi.java new file mode 100644 index 00000000..da1a862a --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/api/QueryApi.java b/src/main/java/com/skyflow/generated/rest/api/QueryApi.java new file mode 100644 index 00000000..fad624ce --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/api/RecordsApi.java b/src/main/java/com/skyflow/generated/rest/api/RecordsApi.java new file mode 100644 index 00000000..d8d8257b --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/api/TokensApi.java b/src/main/java/com/skyflow/generated/rest/api/TokensApi.java new file mode 100644 index 00000000..f2ec51a3 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java b/src/main/java/com/skyflow/generated/rest/auth/ApiKeyAuth.java new file mode 100644 index 00000000..79949c2b --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/auth/Authentication.java b/src/main/java/com/skyflow/generated/rest/auth/Authentication.java new file mode 100644 index 00000000..219caa17 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java b/src/main/java/com/skyflow/generated/rest/auth/HttpBasicAuth.java new file mode 100644 index 00000000..5bf3124a --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java b/src/main/java/com/skyflow/generated/rest/auth/HttpBearerAuth.java new file mode 100644 index 00000000..e8797964 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java b/src/main/java/com/skyflow/generated/rest/models/AbstractOpenApiSchema.java new file mode 100644 index 00000000..c506e085 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java b/src/main/java/com/skyflow/generated/rest/models/AuditEventAuditResourceType.java new file mode 100644 index 00000000..ee029542 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java b/src/main/java/com/skyflow/generated/rest/models/AuditEventContext.java new file mode 100644 index 00000000..5732e155 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/AuditEventData.java b/src/main/java/com/skyflow/generated/rest/models/AuditEventData.java new file mode 100644 index 00000000..4631467b --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java b/src/main/java/com/skyflow/generated/rest/models/AuditEventHTTPInfo.java new file mode 100644 index 00000000..8d35595f --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java b/src/main/java/com/skyflow/generated/rest/models/BatchRecordMethod.java new file mode 100644 index 00000000..4ef6d0f4 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java b/src/main/java/com/skyflow/generated/rest/models/ContextAccessType.java new file mode 100644 index 00000000..92075e20 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java b/src/main/java/com/skyflow/generated/rest/models/ContextAuthMode.java new file mode 100644 index 00000000..d0fc0afc --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java b/src/main/java/com/skyflow/generated/rest/models/DetokenizeRecordResponseValueType.java new file mode 100644 index 00000000..346833e6 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java b/src/main/java/com/skyflow/generated/rest/models/GooglerpcStatus.java new file mode 100644 index 00000000..44ca3e7f --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java b/src/main/java/com/skyflow/generated/rest/models/ProtobufAny.java new file mode 100644 index 00000000..658d341e --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java b/src/main/java/com/skyflow/generated/rest/models/QueryServiceExecuteQueryBody.java new file mode 100644 index 00000000..3a7790a0 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java b/src/main/java/com/skyflow/generated/rest/models/RecordServiceBatchOperationBody.java new file mode 100644 index 00000000..ec0c3f95 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java b/src/main/java/com/skyflow/generated/rest/models/RecordServiceBulkDeleteRecordBody.java new file mode 100644 index 00000000..b7358e49 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java b/src/main/java/com/skyflow/generated/rest/models/RecordServiceInsertRecordBody.java new file mode 100644 index 00000000..0ffe7ce8 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java b/src/main/java/com/skyflow/generated/rest/models/RecordServiceUpdateRecordBody.java new file mode 100644 index 00000000..27e8f48a --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java b/src/main/java/com/skyflow/generated/rest/models/RedactionEnumREDACTION.java new file mode 100644 index 00000000..e0c8ea98 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/RequestActionType.java b/src/main/java/com/skyflow/generated/rest/models/RequestActionType.java new file mode 100644 index 00000000..d5e979d8 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditAfterOptions.java new file mode 100644 index 00000000..faf2c5b3 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditEventResponse.java new file mode 100644 index 00000000..97134351 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditResponse.java new file mode 100644 index 00000000..1d0268b4 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEvent.java new file mode 100644 index 00000000..0e2070ae --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1AuditResponseEventRequest.java new file mode 100644 index 00000000..d4b69f55 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1BINListRequest.java new file mode 100644 index 00000000..292bd674 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1BINListResponse.java new file mode 100644 index 00000000..47f30610 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1BYOT.java b/src/main/java/com/skyflow/generated/rest/models/V1BYOT.java new file mode 100644 index 00000000..28bd87e9 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1BatchOperationResponse.java new file mode 100644 index 00000000..2d98e66e --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java b/src/main/java/com/skyflow/generated/rest/models/V1BatchRecord.java new file mode 100644 index 00000000..21ab2cf9 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1BulkDeleteRecordResponse.java new file mode 100644 index 00000000..6a89ed40 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1BulkGetRecordResponse.java new file mode 100644 index 00000000..2a935fe9 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1Card.java b/src/main/java/com/skyflow/generated/rest/models/V1Card.java new file mode 100644 index 00000000..5c8fb3cc --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1DeleteFileResponse.java new file mode 100644 index 00000000..9a3c2cb4 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1DeleteRecordResponse.java new file mode 100644 index 00000000..8ebf5c35 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java b/src/main/java/com/skyflow/generated/rest/models/V1DetokenizePayload.java new file mode 100644 index 00000000..fdc5c52e --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordRequest.java new file mode 100644 index 00000000..391fa2fc --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeRecordResponse.java new file mode 100644 index 00000000..5c223793 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1DetokenizeResponse.java new file mode 100644 index 00000000..ed996183 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java b/src/main/java/com/skyflow/generated/rest/models/V1FieldRecords.java new file mode 100644 index 00000000..9efada66 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java b/src/main/java/com/skyflow/generated/rest/models/V1FileAVScanStatus.java new file mode 100644 index 00000000..af3f490f --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenRequest.java new file mode 100644 index 00000000..c2d6bf1d --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1GetAuthTokenResponse.java new file mode 100644 index 00000000..d6c0f61f --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1GetFileScanStatusResponse.java new file mode 100644 index 00000000..4bce5d74 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1GetQueryResponse.java new file mode 100644 index 00000000..2ff57e57 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1InsertRecordResponse.java new file mode 100644 index 00000000..f4f432b3 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1MemberType.java b/src/main/java/com/skyflow/generated/rest/models/V1MemberType.java new file mode 100644 index 00000000..5cb1ce8b --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java b/src/main/java/com/skyflow/generated/rest/models/V1RecordMetaProperties.java new file mode 100644 index 00000000..e0aaf47e --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java b/src/main/java/com/skyflow/generated/rest/models/V1TokenizePayload.java new file mode 100644 index 00000000..74936451 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java b/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordRequest.java new file mode 100644 index 00000000..1de790c5 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1TokenizeRecordResponse.java new file mode 100644 index 00000000..290d7403 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1TokenizeResponse.java new file mode 100644 index 00000000..3885c9a5 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java b/src/main/java/com/skyflow/generated/rest/models/V1UpdateRecordResponse.java new file mode 100644 index 00000000..b731dd12 --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java b/src/main/java/com/skyflow/generated/rest/models/V1VaultFieldMapping.java new file mode 100644 index 00000000..582a53fd --- /dev/null +++ b/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/src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java b/src/main/java/com/skyflow/generated/rest/models/V1VaultSchemaConfig.java new file mode 100644 index 00000000..58ac97ef --- /dev/null +++ b/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); + } +} + diff --git a/src/main/java/com/skyflow/logs/DebugLogs.java b/src/main/java/com/skyflow/logs/DebugLogs.java deleted file mode 100644 index 82e636d4..00000000 --- a/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/src/main/java/com/skyflow/logs/ErrorLogs.java b/src/main/java/com/skyflow/logs/ErrorLogs.java index 2f7c78ff..ad32b886 100644 --- a/src/main/java/com/skyflow/logs/ErrorLogs.java +++ b/src/main/java/com/skyflow/logs/ErrorLogs.java @@ -1,62 +1,113 @@ -/* - 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"), + // 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."), - 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."); + // 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."), + 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."), + 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."), + + // 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/src/main/java/com/skyflow/logs/InfoLogs.java b/src/main/java/com/skyflow/logs/InfoLogs.java index 33728a3a..5beecfd3 100644 --- a/src/main/java/com/skyflow/logs/InfoLogs.java +++ b/src/main/java/com/skyflow/logs/InfoLogs.java @@ -1,39 +1,85 @@ -/* - 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"); + // 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 String getLog() { + public final String getLog() { return log; } } diff --git a/src/main/java/com/skyflow/logs/WarnLogs.java b/src/main/java/com/skyflow/logs/WarnLogs.java deleted file mode 100644 index 6a1a3d16..00000000 --- a/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/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java b/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java index a40ec2c2..da221458 100644 --- a/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java +++ b/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java @@ -1,40 +1,41 @@ -/* - 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.google.gson.JsonElement; +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; -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.URL; +import java.net.MalformedURLException; import java.security.PrivateKey; +import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; -import java.util.Map; 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 String[] roles; - + private final ArrayList roles; private final String credentialsType; private BearerToken(BearerTokenBuilder builder) { @@ -45,167 +46,110 @@ private BearerToken(BearerTokenBuilder builder) { 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 static BearerTokenBuilder builder() { + return new BearerTokenBuilder(); } - public synchronized String getBearerToken() throws SkyflowException { - // Make API call in generateBearerToken function to get the token - ResponseToken response; - String accessToken = null; - + private static V1GetAuthTokenResponse generateBearerTokenFromCredentials( + File credentialsFile, String context, ArrayList roles + ) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.GENERATE_BEARER_TOKEN_FROM_CREDENTIALS_TRIGGERED.getLog()); 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(); + if (credentialsFile == null || !credentialsFile.isFile()) { + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); } - } catch (SkyflowException e) { - e.printStackTrace(); + FileReader reader = new FileReader(String.valueOf(credentialsFile)); + JsonObject serviceAccountCredentials = JsonParser.parseReader(reader).getAsJsonObject(); + return getBearerTokenFromCredentials(serviceAccountCredentials, context, roles); + } catch (JsonSyntaxException e) { + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE_FORMAT.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( + 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.getPath())); } - 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; + 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 (credentialsPath == null || !credentialsPath.isFile()) { - LogUtil.printErrorLog(ErrorLogs.EmptyJSONString.getLog()); - throw new SkyflowException(ErrorCode.EmptyJSONString); + if (credentials == null || credentials.isEmpty()) { + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_STRING.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); } - - 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); + JsonObject serviceAccountCredentials = JsonParser.parseString(credentials).getAsJsonObject(); + return getBearerTokenFromCredentials(serviceAccountCredentials, context, roles); + } catch (JsonSyntaxException e) { + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_STRING_FORMAT.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.CredentialsStringInvalidJson.getMessage()); } - - 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; + private static V1GetAuthTokenResponse getBearerTokenFromCredentials( + JsonObject credentials, String context, ArrayList roles + ) throws SkyflowException { try { - if (credentials == null || credentials.isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.EmptyJSONString.getLog()); - throw new SkyflowException(ErrorCode.EmptyJSONString); + JsonElement privateKey = credentials.get("privateKey"); + if (privateKey == null) { + LogUtil.printErrorLog(ErrorLogs.PRIVATE_KEY_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingPrivateKey.getMessage()); } - 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"); + JsonElement clientID = credentials.get("clientID"); if (clientID == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidClientID.getLog()); - throw new SkyflowException(ErrorCode.InvalidClientID); + LogUtil.printErrorLog(ErrorLogs.CLIENT_ID_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingClientId.getMessage()); } - String keyID = (String) creds.get("keyID"); + + JsonElement keyID = credentials.get("keyID"); if (keyID == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidKeyID.getLog()); - throw new SkyflowException(ErrorCode.InvalidKeyID); + LogUtil.printErrorLog(ErrorLogs.KEY_ID_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingKeyId.getMessage()); } - String tokenURI = (String) creds.get("tokenURI"); + + JsonElement tokenURI = credentials.get("tokenURI"); if (tokenURI == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidTokenURI.getLog()); - throw new SkyflowException(ErrorCode.InvalidTokenURI); + LogUtil.printErrorLog(ErrorLogs.TOKEN_URI_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingTokenUri.getMessage()); } - PrivateKey pvtKey = Helpers.getPrivateKeyFromPem((String) creds.get("privateKey")); + PrivateKey pvtKey = Utils.getPrivateKeyFromPem(privateKey.getAsString()); + String signedUserJWT = getSignedToken( + clientID.getAsString(), keyID.getAsString(), tokenURI.getAsString(), pvtKey, context + ); - String signedUserJWT = getSignedToken(clientID, keyID, tokenURI, pvtKey, context); + String basePath = Utils.getBaseURL(tokenURI.getAsString()); + apiClient.setBasePath(basePath); - Map headers = new HashMap<>(); - headers.put(Constants.SDK_METRICS_HEADER_KEY, Helpers.getMetrics().toJSONString()); + V1GetAuthTokenRequest body = new V1GetAuthTokenRequest(); + body.setGrantType(Constants.GRANT_TYPE); + body.setAssertion(signedUserJWT); - 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); + body.setScope(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 authenticationApi.authenticationServiceGetAuthToken(body); + } catch (MalformedURLException e) { + LogUtil.printErrorLog(ErrorLogs.INVALID_TOKEN_URI.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidTokenUri.getMessage()); + } catch (ApiException e) { + LogUtil.printErrorLog(ErrorLogs.BEARER_TOKEN_REJECTED.getLog()); + throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); } - - return responseToken; } - private static String getSignedToken(String clientID, String keyID, String tokenURI, PrivateKey pvtKey, - String context) { + 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) @@ -217,7 +161,7 @@ private static String getSignedToken(String clientID, String keyID, String token .compact(); } - private static String getScopeUsingRoles(String[] roles) { + private static String getScopeUsingRoles(ArrayList roles) { StringBuilder scope = new StringBuilder(); if (roles != null) { for (String role : roles) { @@ -226,4 +170,61 @@ private static String getScopeUsingRoles(String[] roles) { } return scope.toString(); } + + public synchronized String getBearerToken() throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.GET_BEARER_TOKEN_TRIGGERED.getLog()); + V1GetAuthTokenResponse response; + String accessToken = null; + 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; + } + + // Builder class + public static class BearerTokenBuilder { + private File credentialsFile; + private String credentialsString; + private String ctx; + private ArrayList roles; + private String credentialsType; + + private BearerTokenBuilder() { + } + + 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/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java index ed05e541..e7e966bc 100644 --- a/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java +++ b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java @@ -1,20 +1,22 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ package com.skyflow.serviceaccount.util; +import com.skyflow.utils.Constants; + public class SignedDataTokenResponse { - String dataToken; - String signedDataToken; + 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 = signedDataToken; + this.signedDataToken = new StringBuilder(prefix).append(signedDataToken).toString(); } @Override public String toString() { - return "{" + "dataToken: " + dataToken + "," + "signedDataToken: " + signedDataToken + "}"; - + return "{" + + "\n\t\"dataToken\":\"" + this.dataToken + "\"," + + "\n\t\"signedDataToken\":\"" + this.signedDataToken + "\"," + + "\n}"; } } diff --git a/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java index d31c5b85..83fd0543 100644 --- a/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java +++ b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java @@ -1,23 +1,22 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ package com.skyflow.serviceaccount.util; -import com.skyflow.common.utils.Helpers; -import com.skyflow.common.utils.LogUtil; +import com.google.gson.JsonElement; +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 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.security.PrivateKey; import java.util.ArrayList; import java.util.Date; @@ -27,169 +26,105 @@ public class SignedDataTokens { private final File credentialsFile; private final String credentialsString; + private final String credentialsType; private final String ctx; - - private final String[] dataTokens; + private final ArrayList dataTokens; private final Integer timeToLive; - private final String credentialsType; - private SignedDataTokens(SignedDataTokensBuilder builder) { this.credentialsFile = builder.credentialsFile; this.credentialsString = builder.credentialsString; + this.credentialsType = builder.credentialsType; 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); - } + this.timeToLive = builder.timeToLive; } - 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 SignedDataTokensBuilder builder() { + return new SignedDataTokensBuilder(); } - private static List generateSignedTokens(File credentialsPath, String[] dataTokens, - Integer timeToLive, String context) throws SkyflowException { - LogUtil.printInfoLog(InfoLogs.GenerateBearerTokenFromCredsCalled.getLog()); - JSONParser parser = new JSONParser(); + private static List generateSignedTokenFromCredentialsFile( + File credentialsFile, ArrayList dataTokens, Integer timeToLive, String context + ) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.GENERATE_SIGNED_TOKENS_FROM_CREDENTIALS_FILE_TRIGGERED.getLog()); List responseToken; - try { - if (credentialsPath == null || !credentialsPath.isFile()) { - LogUtil.printErrorLog(ErrorLogs.EmptyJSONString.getLog()); - throw new SkyflowException(ErrorCode.EmptyJSONString); + if (credentialsFile == null || !credentialsFile.isFile()) { + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); } - - 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); + FileReader reader = new FileReader(String.valueOf(credentialsFile)); + JsonObject serviceAccountCredentials = JsonParser.parseReader(reader).getAsJsonObject(); + responseToken = generateSignedTokensFromCredentials(serviceAccountCredentials, dataTokens, timeToLive, context); + } catch (JsonSyntaxException e) { + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_FILE_FORMAT.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( + 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.getPath())); } - 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(); + private static List generateSignedTokensFromCredentialsString( + String credentials, ArrayList dataTokens, Integer timeToLive, String context + ) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.GENERATE_SIGNED_TOKENS_FROM_CREDENTIALS_STRING_TRIGGERED.getLog()); List responseToken; - LogUtil.printInfoLog(InfoLogs.GenerateBearerTokenFromCredsCalled.getLog()); - try { if (credentials == null || credentials.isEmpty()) { - LogUtil.printErrorLog(ErrorLogs.EmptyJSONString.getLog()); - throw new SkyflowException(ErrorCode.EmptyJSONString); + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_STRING.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidCredentials.getMessage()); } - - 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); + JsonObject serviceAccountCredentials = JsonParser.parseString(credentials).getAsJsonObject(); + responseToken = generateSignedTokensFromCredentials(serviceAccountCredentials, dataTokens, timeToLive, context); + } catch (JsonSyntaxException e) { + LogUtil.printErrorLog(ErrorLogs.INVALID_CREDENTIALS_STRING_FORMAT.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.CredentialsStringInvalidJson.getMessage()); } - return responseToken; } - private static List getSignedTokenFromCredsFile(JSONObject creds, String[] dataTokens, - Integer timeToLive, String context) throws SkyflowException { - List responseToken; - + private static List generateSignedTokensFromCredentials( + JsonObject credentials, ArrayList dataTokens, Integer timeToLive, String context + ) throws SkyflowException { + List signedDataTokens = null; try { - String clientID = (String) creds.get("clientID"); + JsonElement privateKey = credentials.get("privateKey"); + if (privateKey == null) { + 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) { - LogUtil.printErrorLog(ErrorLogs.InvalidClientID.getLog()); - throw new SkyflowException(ErrorCode.InvalidClientID); + LogUtil.printErrorLog(ErrorLogs.CLIENT_ID_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingClientId.getMessage()); } - String keyID = (String) creds.get("keyID"); + + JsonElement keyID = credentials.get("keyID"); if (keyID == null) { - LogUtil.printErrorLog(ErrorLogs.InvalidKeyID.getLog()); - throw new SkyflowException(ErrorCode.InvalidKeyID); + LogUtil.printErrorLog(ErrorLogs.KEY_ID_IS_REQUIRED.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingKeyId.getMessage()); } - - PrivateKey pvtKey = Helpers.getPrivateKeyFromPem((String) creds.get("privateKey")); - - responseToken = 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 new SkyflowException(ErrorCode.IncorrectCredentials, e); + LogUtil.printErrorLog(ErrorLogs.SIGNED_DATA_TOKENS_REJECTED.getLog()); + throw new SkyflowException(e); } - - return responseToken; + return signedDataTokens; } - private static List getSignedToken(String clientID, String keyID, PrivateKey pvtKey, - String[] dataTokens, Integer timeToLive, String context) { + private static List getSignedToken( + String clientID, String keyID, PrivateKey pvtKey, + ArrayList dataTokens, Integer timeToLive, String context + ) { final Date createdDate = new Date(); final Date expirationDate; @@ -200,12 +135,10 @@ private static List getSignedToken(String clientID, Str } 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("iat", (createdDate.getTime() / 1000)) .claim("key", keyID) .claim("sub", clientID) .claim("ctx", context) @@ -213,12 +146,68 @@ private static List getSignedToken(String clientID, Str .setExpiration(expirationDate) .signWith(SignatureAlgorithm.RS256, pvtKey) .compact(); - - SignedDataTokenResponse responseObject = new SignedDataTokenResponse(dataToken, - prefix + eachSignedDataToken); - + SignedDataTokenResponse responseObject = new SignedDataTokenResponse(dataToken, eachSignedDataToken); list.add(responseObject); } return list; } + + public synchronized List getSignedDataTokens() throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.GET_SIGNED_DATA_TOKENS_TRIGGERED.getLog()); + List signedToken = new ArrayList<>(); + 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; + } + + public static class SignedDataTokensBuilder { + private ArrayList dataTokens; + private Integer timeToLive; + private File credentialsFile; + private String credentialsString; + private String ctx; + private String credentialsType; + + private SignedDataTokensBuilder() { + } + + 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/src/main/java/com/skyflow/serviceaccount/util/Token.java b/src/main/java/com/skyflow/serviceaccount/util/Token.java index 42155e27..90da0cf4 100644 --- a/src/main/java/com/skyflow/serviceaccount/util/Token.java +++ b/src/main/java/com/skyflow/serviceaccount/util/Token.java @@ -1,231 +1,46 @@ -/* - 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.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.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 com.skyflow.utils.logger.LogUtil; +import org.apache.commons.codec.binary.Base64; -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.nio.charset.StandardCharsets; 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 class Token { public static boolean isExpired(String token) { - long expiryTime; long currentTime; try { - if (token == null || token.isEmpty()) { - LogUtil.printInfoLog(InfoLogs.EmptyBearerToken.getLog()); + if (token == null || token.trim().isEmpty()) { + LogUtil.printInfoLog(InfoLogs.EMPTY_BEARER_TOKEN.getLog()); return true; } currentTime = new Date().getTime() / 1000; - expiryTime = (long) TokenUtils.decoded(token).get("exp"); + expiryTime = decoded(token).get("exp").getAsLong(); - } catch (ParseException e) { - LogUtil.printInfoLog(ErrorLogs.InvalidBearerToken.getLog()); - return true; - } catch (SkyflowException e) { - LogUtil.printInfoLog(ErrorLogs.InvalidBearerToken.getLog()); + } catch (JsonSyntaxException | SkyflowException e) { + LogUtil.printErrorLog(ErrorLogs.INVALID_BEARER_TOKEN.getLog()); return true; } return currentTime > expiryTime; } -} + static JsonObject decoded(String encodedToken) throws JsonSyntaxException, SkyflowException { + String[] split = encodedToken.split("\\."); + if (split.length < 3) { + LogUtil.printErrorLog(ErrorLogs.INVALID_BEARER_TOKEN.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.JwtDecodeError.getMessage()); + } + byte[] decodedBytes = Base64.decodeBase64(split[1]); + return JsonParser.parseString(new String(decodedBytes, StandardCharsets.UTF_8)).getAsJsonObject(); + } +} diff --git a/src/main/java/com/skyflow/utils/Constants.java b/src/main/java/com/skyflow/utils/Constants.java new file mode 100644 index 00000000..f7c378f5 --- /dev/null +++ b/src/main/java/com/skyflow/utils/Constants.java @@ -0,0 +1,19 @@ +package com.skyflow.utils; + +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"; + 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_"; + 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/src/main/java/com/skyflow/utils/HttpUtility.java b/src/main/java/com/skyflow/utils/HttpUtility.java new file mode 100644 index 00000000..93cbdd31 --- /dev/null +++ b/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/src/main/java/com/skyflow/utils/Utils.java b/src/main/java/com/skyflow/utils/Utils.java new file mode 100644 index 00000000..66e50b5a --- /dev/null +++ b/src/main/java/com/skyflow/utils/Utils.java @@ -0,0 +1,153 @@ +package com.skyflow.utils; + +import com.skyflow.config.ConnectionConfig; +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 com.skyflow.vault.connection.InvokeConnectionRequest; +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; +import java.util.HashMap; +import java.util.Map; + +public final class Utils { + public static String getVaultURL(String clusterId, Env env) { + StringBuilder sb = new StringBuilder(Constants.SECURE_PROTOCOL); + sb.append(clusterId); + switch (env) { + case DEV: + sb.append(Constants.DEV_DOMAIN); + break; + case STAGE: + sb.append(Constants.STAGE_DOMAIN); + break; + case SANDBOX: + sb.append(Constants.SANDBOX_DOMAIN); + break; + case PROD: + default: + sb.append(Constants.PROD_DOMAIN); + break; + } + return sb.toString(); + } + + 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 { + LogUtil.printErrorLog(ErrorLogs.JWT_INVALID_FORMAT.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.JwtInvalidFormat.getMessage()); + } + return privateKey; + } + + public static String getBaseURL(String url) throws MalformedURLException { + URL parsedUrl = new URL(url); + String protocol = parsedUrl.getProtocol(); + String host = parsedUrl.getHost(); + 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; + 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()); + + 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/src/main/java/com/skyflow/common/utils/LogUtil.java b/src/main/java/com/skyflow/utils/logger/LogUtil.java similarity index 75% rename from src/main/java/com/skyflow/common/utils/LogUtil.java rename to src/main/java/com/skyflow/utils/logger/LogUtil.java index fa48cdb3..78cfa038 100644 --- a/src/main/java/com/skyflow/common/utils/LogUtil.java +++ b/src/main/java/com/skyflow/utils/logger/LogUtil.java @@ -1,19 +1,16 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.common.utils; +package com.skyflow.utils.logger; -import com.skyflow.entities.LogLevel; +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_OWNER = "[Skyflow] "; + 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(); @@ -24,8 +21,11 @@ synchronized public static void setupLogger(LogLevel logLevel) { // Override format method @Override public synchronized String format(LogRecord logRecord) { - return String.format(format, loggerLevelToLogLevelMap(logRecord.getLevel()), - logRecord.getMessage()); + return String.format( + format, + loggerLevelToLogLevelMap(logRecord.getLevel()), + logRecord.getMessage() + ); } }; ConsoleHandler consoleHandler = new ConsoleHandler(); @@ -34,31 +34,31 @@ public synchronized String format(LogRecord logRecord) { LOGGER.addHandler(consoleHandler); LOGGER.setLevel(logLevelToLoggerLevelMap(logLevel)); - printInfoLog(InfoLogs.LoggerSetup.getLog()); + printInfoLog(InfoLogs.LOGGER_SETUP_DONE.getLog()); } public static void printErrorLog(String message) { if (IS_LOGGER_SETUP_DONE) - LOGGER.severe(SDK_OWNER + message); + LOGGER.severe(SDK_LOG_PREFIX + message); else { setupLogger(LogLevel.ERROR); - LOGGER.severe(SDK_OWNER + message); + LOGGER.severe(SDK_LOG_PREFIX + message); } } public static void printDebugLog(String message) { if (IS_LOGGER_SETUP_DONE) - LOGGER.config(SDK_OWNER + message); + LOGGER.config(SDK_LOG_PREFIX + message); } public static void printWarningLog(String message) { if (IS_LOGGER_SETUP_DONE) - LOGGER.warning(SDK_OWNER + message); + LOGGER.warning(SDK_LOG_PREFIX + message); } public static void printInfoLog(String message) { if (IS_LOGGER_SETUP_DONE) - LOGGER.info(SDK_OWNER + message); + LOGGER.info(SDK_LOG_PREFIX + message); } @@ -91,12 +91,10 @@ private static LogLevel loggerLevelToLogLevelMap(Level loggerLevel) { logLevel = LogLevel.WARN; } else if (Level.INFO.equals(loggerLevel)) { logLevel = LogLevel.INFO; - } else if (Level.CONFIG.equals(loggerLevel)){ + } else if (Level.CONFIG.equals(loggerLevel)) { logLevel = LogLevel.DEBUG; - }else + } else logLevel = LogLevel.OFF; return logLevel; } - - } diff --git a/src/main/java/com/skyflow/utils/validations/Validations.java b/src/main/java/com/skyflow/utils/validations/Validations.java new file mode 100644 index 00000000..77f6b823 --- /dev/null +++ b/src/main/java/com/skyflow/utils/validations/Validations.java @@ -0,0 +1,746 @@ +package com.skyflow.utils.validations; + +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.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +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.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; +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; + +public class Validations { + + public static void validateVaultConfig(VaultConfig vaultConfig) throws SkyflowException { + String vaultId = vaultConfig.getVaultId(); + String clusterId = vaultConfig.getClusterId(); + Credentials credentials = vaultConfig.getCredentials(); + 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); + } + } + + public static void validateConnectionConfig(ConnectionConfig connectionConfig) throws SkyflowException { + String connectionId = connectionConfig.getConnectionId(); + String connectionUrl = connectionConfig.getConnectionUrl(); + + 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()); + } 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 { + 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()); + } + } + } + } + + 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()); + } + } + } + } + + 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()); + } + } + } + + public static void validateCredentials(Credentials credentials) throws SkyflowException { + int nonNullMembers = 0; + String path = credentials.getPath(); + 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) { + 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()) { + LogUtil.printErrorLog(ErrorLogs.EMPTY_CREDENTIALS_PATH.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyCredentialFilePath.getMessage()); + } else if (credentialsString != null && credentialsString.trim().isEmpty()) { + LogUtil.printErrorLog(ErrorLogs.EMPTY_CREDENTIALS_STRING.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyCredentialsString.getMessage()); + } else if (token != null && token.trim().isEmpty()) { + 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()) { + 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()); + } + } + } 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()); + } + } + } + } + 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(); + 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()) { + 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()); + } + } + } + } + + public static void validateInsertRequest(InsertRequest insertRequest) throws SkyflowException { + String table = insertRequest.getTable(); + ArrayList> values = insertRequest.getValues(); + ArrayList> tokens = insertRequest.getTokens(); + String upsert = insertRequest.getUpsert(); + Boolean homogeneous = insertRequest.getHomogeneous(); + Byot tokenStrict = insertRequest.getTokenStrict(); + + if (table == null) { + 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.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.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.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.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.printErrorLog(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()) { + 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.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_VALUE_IN_VALUES.getLog(), + InterfaceName.INSERT.getName(), key + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyValueInValues.getMessage()); + } + } + } + } + + switch (tokenStrict) { + case DISABLE: + if (tokens != null) { + 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()); + } + break; + case ENABLE: + if (tokens == null) { + LogUtil.printErrorLog(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, tokenStrict); + break; + case ENABLE_STRICT: + if (tokens == null) { + 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.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() + ); + } + validateTokensForInsertRequest(tokens, values, tokenStrict); + break; + } + } + + public static void validateGetRequest(GetRequest getRequest) throws SkyflowException { + String table = getRequest.getTable(); + ArrayList ids = getRequest.getIds(); + RedactionType redactionType = getRequest.getRedactionType(); + Boolean tokenization = getRequest.getReturnTokens(); + ArrayList fields = getRequest.getFields(); + String offset = getRequest.getOffset(); + String limit = getRequest.getLimit(); + String columnName = getRequest.getColumnName(); + ArrayList columnValues = getRequest.getColumnValues(); + String orderBy = getRequest.getOrderBy(); + + if (table == null) { + 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.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.printErrorLog(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()) { + LogUtil.printErrorLog(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()); + } + } + } + } + if (fields != null) { + if (fields.isEmpty()) { + LogUtil.printErrorLog(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()) { + LogUtil.printErrorLog(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()); + } + } + } + } + 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( + 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.printErrorLog(Utils.parameterizedString( + ErrorLogs.TOKENIZATION_SUPPORTED_ONLY_WITH_IDS.getLog(), InterfaceName.GET.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.TokensGetColumnNotSupported.getMessage() + ); + } + } + 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()); + } + 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.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.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.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.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.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.printErrorLog(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()) { + LogUtil.printErrorLog(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()); + } + } + } + } + } + + public static void validateUpdateRequest(UpdateRequest updateRequest) throws SkyflowException { + String table = updateRequest.getTable(); + HashMap data = updateRequest.getData(); + HashMap tokens = updateRequest.getTokens(); + Byot tokenStrict = updateRequest.getTokenStrict(); + + if (table == null) { + 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.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_TABLE_NAME.getLog(), InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); + } else if (data == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.DATA_IS_REQUIRED.getLog(), InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.DataKeyError.getMessage()); + } else if (data.isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_DATA.getLog(), InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyData.getMessage()); + } else if (!data.containsKey("skyflow_id")) { + 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 (!(data.get("skyflow_id") instanceof String)) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_SKYFLOW_ID_TYPE.getLog(), InterfaceName.UPDATE.getName() + )); + 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() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTokens.getMessage()); + } + + 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 = 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 + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.EmptyValueInValues.getMessage()); + } + } + } + + switch (tokenStrict) { + case DISABLE: + if (tokens != null) { + 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()); + } + break; + case ENABLE: + if (tokens == null) { + LogUtil.printErrorLog(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, 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() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( + ErrorMessage.NoTokensWithByot.getMessage(), Byot.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() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage()); + } + validateTokensMapWithTokenStrict(tokens, data); + break; + } + } + + public static void validateDeleteRequest(DeleteRequest deleteRequest) throws SkyflowException { + String table = deleteRequest.getTable(); + ArrayList ids = deleteRequest.getIds(); + if (table == null) { + 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.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.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.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_IDS.getLog(), InterfaceName.DELETE.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.trim().isEmpty()) { + LogUtil.printErrorLog(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()); + } + } + } + } + + public static void validateQueryRequest(QueryRequest queryRequest) throws SkyflowException { + String query = queryRequest.getQuery(); + if (query == null) { + 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.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_QUERY.getLog(), InterfaceName.QUERY.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyQuery.getMessage()); + } + } + + public static void validateTokenizeRequest(TokenizeRequest tokenizeRequest) throws SkyflowException { + List columnValues = tokenizeRequest.getColumnValues(); + + 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++) { + ColumnValue value = columnValues.get(index); + if (value.getValue() == null || value.getValue().isEmpty()) { + 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.printErrorLog(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()); + } + } + } + } + + 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, + Byot tokenStrict + ) throws SkyflowException { + if (tokens.isEmpty()) { + LogUtil.printErrorLog(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); + 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); + } + } + + private static void validateTokensMapWithTokenStrict( + HashMap tokensMap, HashMap valuesMap + ) 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() + )); + 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() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MismatchOfFieldsAndTokens.getMessage()); + } else { + Object value = tokensMap.get(key); + if (value == null || value.toString().trim().isEmpty()) { + LogUtil.printErrorLog(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/src/main/java/com/skyflow/vault/DeleteBySkyflowId.java b/src/main/java/com/skyflow/vault/DeleteBySkyflowId.java deleted file mode 100644 index 3d38787f..00000000 --- a/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/src/main/java/com/skyflow/vault/Detokenize.java b/src/main/java/com/skyflow/vault/Detokenize.java deleted file mode 100644 index da0baec4..00000000 --- a/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/src/main/java/com/skyflow/vault/Get.java b/src/main/java/com/skyflow/vault/Get.java deleted file mode 100644 index 5951c275..00000000 --- a/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/src/main/java/com/skyflow/vault/GetBySkyflowId.java b/src/main/java/com/skyflow/vault/GetBySkyflowId.java deleted file mode 100644 index 370d1f8f..00000000 --- a/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/src/main/java/com/skyflow/vault/Insert.java b/src/main/java/com/skyflow/vault/Insert.java deleted file mode 100644 index 94435ee9..00000000 --- a/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/src/main/java/com/skyflow/vault/Skyflow.java b/src/main/java/com/skyflow/vault/Skyflow.java deleted file mode 100644 index b444dc4d..00000000 --- a/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/src/main/java/com/skyflow/vault/UpdateBySkyflowId.java b/src/main/java/com/skyflow/vault/UpdateBySkyflowId.java deleted file mode 100644 index e26299a0..00000000 --- a/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/src/main/java/com/skyflow/vault/audit/ListEventRequest.java b/src/main/java/com/skyflow/vault/audit/ListEventRequest.java new file mode 100644 index 00000000..b6c26b6d --- /dev/null +++ b/src/main/java/com/skyflow/vault/audit/ListEventRequest.java @@ -0,0 +1,11 @@ +package com.skyflow.vault.audit; + +public class ListEventRequest { + // members + + // constructor + public ListEventRequest() { + } + + // getters ans setters +} diff --git a/src/main/java/com/skyflow/vault/audit/ListEventResponse.java b/src/main/java/com/skyflow/vault/audit/ListEventResponse.java new file mode 100644 index 00000000..2647e617 --- /dev/null +++ b/src/main/java/com/skyflow/vault/audit/ListEventResponse.java @@ -0,0 +1,10 @@ +package com.skyflow.vault.audit; + +public class ListEventResponse { + // members + + public ListEventResponse() { + } + + // getters ans setters +} diff --git a/src/main/java/com/skyflow/vault/bin/GetBinRequest.java b/src/main/java/com/skyflow/vault/bin/GetBinRequest.java new file mode 100644 index 00000000..d059245f --- /dev/null +++ b/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/src/main/java/com/skyflow/vault/bin/GetBinResponse.java b/src/main/java/com/skyflow/vault/bin/GetBinResponse.java new file mode 100644 index 00000000..86210031 --- /dev/null +++ b/src/main/java/com/skyflow/vault/bin/GetBinResponse.java @@ -0,0 +1,10 @@ +package com.skyflow.vault.bin; + +public class GetBinResponse { + // members + + public GetBinResponse() { + } + + // getters ans setters +} diff --git a/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java b/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java new file mode 100644 index 00000000..c64bedf4 --- /dev/null +++ b/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java @@ -0,0 +1,83 @@ +package com.skyflow.vault.connection; + +import com.skyflow.enums.RequestMethod; + +import java.util.HashMap; +import java.util.Map; + +public class InvokeConnectionRequest { + + private final InvokeConnectionRequestBuilder builder; + + private InvokeConnectionRequest(InvokeConnectionRequestBuilder builder) { + this.builder = builder; + } + + public static InvokeConnectionRequestBuilder builder() { + return new InvokeConnectionRequestBuilder(); + } + + public RequestMethod 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 RequestMethod methodName; + private Map pathParams; + private Map queryParams; + private Map requestHeaders; + private Object requestBody; + + private InvokeConnectionRequestBuilder() { + this.methodName = RequestMethod.POST; + this.requestBody = new Object(); + } + + public InvokeConnectionRequestBuilder methodName(RequestMethod methodName) { + this.methodName = methodName == null ? RequestMethod.POST : 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); + } + + } + +} diff --git a/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java b/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java new file mode 100644 index 00000000..d6c8fa17 --- /dev/null +++ b/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java @@ -0,0 +1,18 @@ +package com.skyflow.vault.connection; + +import com.google.gson.JsonObject; + +public class InvokeConnectionResponse { + private JsonObject response; + + public InvokeConnectionResponse(JsonObject response) { + this.response = response; + } + + @Override + public String toString() { + return "InvokeConnectionResponse{" + + "response=" + response + + '}'; + } +} diff --git a/src/main/java/com/skyflow/vault/controller/AuditController.java b/src/main/java/com/skyflow/vault/controller/AuditController.java new file mode 100644 index 00000000..9d605e6c --- /dev/null +++ b/src/main/java/com/skyflow/vault/controller/AuditController.java @@ -0,0 +1,20 @@ +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 + public ListEventResponse list(ListEventRequest listEventRequest) { + // return audit events + return null; + } +} diff --git a/src/main/java/com/skyflow/vault/controller/BinLookupController.java b/src/main/java/com/skyflow/vault/controller/BinLookupController.java new file mode 100644 index 00000000..e5d9cc62 --- /dev/null +++ b/src/main/java/com/skyflow/vault/controller/BinLookupController.java @@ -0,0 +1,19 @@ +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) { + // return bin lookup response (card metadata associated with BIN) + return null; + } +} diff --git a/src/main/java/com/skyflow/vault/controller/ConnectionController.java b/src/main/java/com/skyflow/vault/controller/ConnectionController.java new file mode 100644 index 00000000..890ef530 --- /dev/null +++ b/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -0,0 +1,86 @@ +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.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 java.io.IOException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class ConnectionController extends ConnectionClient { + public ConnectionController(ConnectionConfig connectionConfig, Credentials credentials) { + super(connectionConfig, credentials); + } + + 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(super.getConnectionConfig(), invokeConnectionRequest); + Map headers = new HashMap<>(); + + Map requestHeaders = invokeConnectionRequest.getRequestHeaders(); + if (requestHeaders != null && requestHeaders.containsKey("requestHeader")) { + headers = Utils.constructConnectionHeadersMap(invokeConnectionRequest.getRequestHeaders()); + } + if (!headers.containsKey("x-skyflow-authorization")) { + headers.put("x-skyflow-authorization", token == null ? apiKey : token); + } + + RequestMethod requestMethod = invokeConnectionRequest.getMethodName(); + JsonObject requestBody = null; + Object requestBodyObject = invokeConnectionRequest.getRequestBody(); + + if (requestBodyObject != null) { + try { + requestBody = convertObjectToJson(requestBodyObject); + } catch (Exception e) { + LogUtil.printErrorLog(ErrorLogs.INVALID_REQUEST_HEADERS.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); + } + } + + 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) { + LogUtil.printErrorLog(ErrorLogs.INVOKE_CONNECTION_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.getMessage(), e); + } + return connectionResponse; + } + + 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; + } + } +} diff --git a/src/main/java/com/skyflow/vault/controller/DetectController.java b/src/main/java/com/skyflow/vault/controller/DetectController.java new file mode 100644 index 00000000..5b507d89 --- /dev/null +++ b/src/main/java/com/skyflow/vault/controller/DetectController.java @@ -0,0 +1,26 @@ +package com.skyflow.vault.controller; + +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.vault.detect.DeIdentifyRequest; +import com.skyflow.vault.detect.DeIdentifyResponse; + +public class DetectController { + public DetectController(ApiClient apiClient) { + } + + // should return detect controller + public DetectController deIdentify() { + // return detect controller + return null; + } + + public DeIdentifyResponse text(DeIdentifyRequest deIdentifyRequest) { + // return detect response + return null; + } + + public DeIdentifyResponse file(DeIdentifyRequest deIdentifyRequest) { + // return detect response + return null; + } +} diff --git a/src/main/java/com/skyflow/vault/controller/VaultController.java b/src/main/java/com/skyflow/vault/controller/VaultController.java new file mode 100644 index 00000000..2c211687 --- /dev/null +++ b/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -0,0 +1,386 @@ +package com.skyflow.vault.controller; + +import com.google.gson.*; +import com.google.gson.internal.LinkedTreeMap; +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.models.*; +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.*; + +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; + 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) { + 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); + + /* + 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; + } + + 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)); + } + } + 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)); + } + } + 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 { + 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); + 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); + LogUtil.printInfoLog(InfoLogs.INSERT_REQUEST_RESOLVED.getLog()); + List records = bulkInsertResult.getRecords(); + if (records != null) { + for (V1RecordMetaProperties record : records) { + HashMap insertRecord = getFormattedBulkInsertRecord(record); + insertedFields.add(insertRecord); + } + } + } + } 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) { + DetokenizeRecordResponse recordResponse = new DetokenizeRecordResponse(record); + if (record.getError() != null) { + errorRecords.add(recordResponse); + } else { + detokenizedFields.add(recordResponse); + } + } + } + } catch (ApiException e) { + LogUtil.printErrorLog(ErrorLogs.DETOKENIZE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.getCode(), e, e.getResponseHeaders(), e.getResponseBody()); + } + + if (!errorRecords.isEmpty()) { + 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(); + 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() + ); + LogUtil.printInfoLog(InfoLogs.GET_REQUEST_RESOLVED.getLog()); + List records = result.getRecords(); + if (records != null) { + for (V1FieldRecords record : records) { + data.add(getFormattedGetRecord(record)); + } + } + } 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); + result = super.getRecordsApi().recordServiceUpdateRecord( + super.getVaultConfig().getVaultId(), + updateRequest.getTable(), + updateRequest.getData().get("skyflow_id").toString(), + 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(); + for (String id : deleteRequest.getIds()) { + deleteBody.addSkyflowIdsItem(id); + } + 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()); + } + + public Object uploadFile(Object uploadFileRequest) { + return null; + } + + 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()); + } + } + } + } catch (ApiException e) { + 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); + } + + 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/DeleteRequest.java b/src/main/java/com/skyflow/vault/data/DeleteRequest.java new file mode 100644 index 00000000..d61c996f --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/DeleteRequest.java @@ -0,0 +1,45 @@ +package com.skyflow.vault.data; + +import java.util.ArrayList; + +public class DeleteRequest { + private final DeleteRequestBuilder builder; + + private DeleteRequest(DeleteRequestBuilder builder) { + this.builder = builder; + } + + public static DeleteRequestBuilder builder() { + return new DeleteRequestBuilder(); + } + + public String getTable() { + return this.builder.table; + } + + public ArrayList getIds() { + return this.builder.ids; + } + + public static final 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/src/main/java/com/skyflow/vault/data/DeleteResponse.java b/src/main/java/com/skyflow/vault/data/DeleteResponse.java new file mode 100644 index 00000000..21adc788 --- /dev/null +++ b/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 final ArrayList deletedIds; + + public DeleteResponse(ArrayList deletedIds) { + this.deletedIds = deletedIds; + } + + public ArrayList getDeletedIds() { + return deletedIds; + } + + @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"); + } +} diff --git a/src/main/java/com/skyflow/vault/data/GetRequest.java b/src/main/java/com/skyflow/vault/data/GetRequest.java new file mode 100644 index 00000000..04626e35 --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/GetRequest.java @@ -0,0 +1,140 @@ +package com.skyflow.vault.data; + +import com.skyflow.enums.RedactionType; +import com.skyflow.utils.Constants; + +import java.util.ArrayList; + +public class GetRequest { + private final GetRequestBuilder builder; + + private GetRequest(GetRequestBuilder builder) { + this.builder = builder; + } + + public static GetRequestBuilder builder() { + return new GetRequestBuilder(); + } + + public String getTable() { + return this.builder.table; + } + + public ArrayList getIds() { + return this.builder.ids; + } + + public RedactionType getRedactionType() { + return this.builder.redactionType; + } + + public Boolean getReturnTokens() { + return this.builder.returnTokens; + } + + public ArrayList getFields() { + return this.builder.fields; + } + + public String getOffset() { + return this.builder.offset; + } + + public String getLimit() { + return this.builder.limit; + } + + public Boolean getDownloadURL() { + return this.builder.downloadURL; + } + + public String getColumnName() { + return this.builder.columnName; + } + + public ArrayList getColumnValues() { + return this.builder.columnValues; + } + + public String getOrderBy() { + return this.builder.orderBy; + } + + public static final class GetRequestBuilder { + private String table; + private ArrayList ids; + private RedactionType redactionType; + private Boolean returnTokens; + private ArrayList fields; + private String offset; + private String limit; + private Boolean downloadURL; + private String columnName; + private ArrayList columnValues; + private String orderBy; + + private GetRequestBuilder() { + this.downloadURL = true; + this.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 returnTokens(Boolean returnTokens) { + this.returnTokens = returnTokens; + return this; + } + + public GetRequestBuilder fields(ArrayList 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 == null || 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 == null ? Constants.ORDER_ASCENDING : orderBy; + return this; + } + + public GetRequest build() { + return new GetRequest(this); + } + } +} diff --git a/src/main/java/com/skyflow/vault/data/GetResponse.java b/src/main/java/com/skyflow/vault/data/GetResponse.java new file mode 100644 index 00000000..bd882138 --- /dev/null +++ b/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"); + } +} diff --git a/src/main/java/com/skyflow/vault/data/InsertRequest.java b/src/main/java/com/skyflow/vault/data/InsertRequest.java new file mode 100644 index 00000000..b2a49f1b --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/InsertRequest.java @@ -0,0 +1,122 @@ +package com.skyflow.vault.data; + +import com.skyflow.enums.Byot; + +import java.util.ArrayList; +import java.util.HashMap; + +public class InsertRequest { + private final InsertRequestBuilder builder; + + private InsertRequest(InsertRequestBuilder builder) { + this.builder = builder; + } + + public static InsertRequestBuilder builder() { + return new InsertRequestBuilder(); + } + + public String getTable() { + return this.builder.table; + } + + public ArrayList> getValues() { + return this.builder.values; + } + + public ArrayList> getTokens() { + return this.builder.tokens; + } + + public Boolean getReturnTokens() { + return this.builder.returnTokens; + } + + public String getUpsert() { + return this.builder.upsert; + } + + 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 static final class InsertRequestBuilder { + private String table; + private ArrayList> values; + private ArrayList> tokens; + private Boolean returnTokens; + private String upsert; + private Boolean homogeneous; + private Boolean tokenMode; + private Boolean continueOnError; + private Byot tokenStrict; + + private InsertRequestBuilder() { + this.returnTokens = true; + this.tokenMode = false; + this.continueOnError = false; + this.tokenStrict = Byot.DISABLE; + } + + public InsertRequestBuilder table(String table) { + this.table = table; + return this; + } + + public InsertRequestBuilder values(ArrayList> values) { + this.values = values; + return this; + } + + public InsertRequestBuilder tokens(ArrayList> tokens) { + this.tokens = tokens; + return this; + } + + public InsertRequestBuilder returnTokens(Boolean returnTokens) { + this.returnTokens = returnTokens == null || 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 != 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; + return this; + } + + public InsertRequest build() { + return new InsertRequest(this); + } + } +} diff --git a/src/main/java/com/skyflow/vault/data/InsertResponse.java b/src/main/java/com/skyflow/vault/data/InsertResponse.java new file mode 100644 index 00000000..240c6940 --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/InsertResponse.java @@ -0,0 +1,51 @@ +package com.skyflow.vault.data; + +import java.util.ArrayList; +import java.util.HashMap; + +public class InsertResponse { + private final ArrayList> insertedFields; + private final ArrayList> errorFields; + + public InsertResponse(ArrayList> insertedFields, ArrayList> errorFields) { + this.insertedFields = insertedFields; + this.errorFields = errorFields; + } + + public ArrayList> getInsertedFields() { + return insertedFields; + } + + public ArrayList> getErrorFields() { + return errorFields; + } + + @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/src/main/java/com/skyflow/vault/data/QueryRequest.java b/src/main/java/com/skyflow/vault/data/QueryRequest.java new file mode 100644 index 00000000..2aaa200d --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/QueryRequest.java @@ -0,0 +1,33 @@ +package com.skyflow.vault.data; + +public class QueryRequest { + private final QueryRequestBuilder builder; + + private QueryRequest(QueryRequestBuilder builder) { + this.builder = builder; + } + + public static QueryRequestBuilder builder() { + return new QueryRequestBuilder(); + } + + public String getQuery() { + return this.builder.query; + } + + public static final 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/src/main/java/com/skyflow/vault/data/QueryResponse.java b/src/main/java/com/skyflow/vault/data/QueryResponse.java new file mode 100644 index 00000000..e8103506 --- /dev/null +++ b/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 final 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"); + } + +} diff --git a/src/main/java/com/skyflow/vault/data/UpdateRequest.java b/src/main/java/com/skyflow/vault/data/UpdateRequest.java new file mode 100644 index 00000000..58e075ac --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/UpdateRequest.java @@ -0,0 +1,79 @@ +package com.skyflow.vault.data; + +import com.skyflow.enums.Byot; + +import java.util.HashMap; + +public class UpdateRequest { + private final UpdateRequestBuilder builder; + + private UpdateRequest(UpdateRequestBuilder builder) { + this.builder = builder; + } + + public static UpdateRequestBuilder builder() { + return new UpdateRequestBuilder(); + } + + public String getTable() { + return this.builder.table; + } + + public Boolean getReturnTokens() { + return this.builder.returnTokens; + } + + public HashMap getData() { + return this.builder.data; + } + + public HashMap getTokens() { + return this.builder.tokens; + } + + public Byot getTokenStrict() { + return this.builder.tokenStrict; + } + + public static final class UpdateRequestBuilder { + private String table; + private Boolean returnTokens; + private HashMap data; + 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 returnTokens(Boolean returnTokens) { + this.returnTokens = returnTokens == null || returnTokens; + return this; + } + + public UpdateRequestBuilder data(HashMap data) { + this.data = data; + return this; + } + + public UpdateRequestBuilder tokens(HashMap tokens) { + this.tokens = tokens; + return this; + } + + public UpdateRequestBuilder tokenStrict(Byot tokenStrict) { + this.tokenStrict = tokenStrict == null ? Byot.DISABLE : tokenStrict; + return this; + } + + public UpdateRequest build() { + return new UpdateRequest(this); + } + } +} diff --git a/src/main/java/com/skyflow/vault/data/UpdateResponse.java b/src/main/java/com/skyflow/vault/data/UpdateResponse.java new file mode 100644 index 00000000..4567e2e1 --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/UpdateResponse.java @@ -0,0 +1,40 @@ +package com.skyflow.vault.data; + +import java.util.HashMap; + +public class UpdateResponse { + private final String skyflowId; + private final 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).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("\","); + } + return sb.toString(); + } +} diff --git a/src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java b/src/main/java/com/skyflow/vault/detect/DeIdentifyRequest.java new file mode 100644 index 00000000..92be4962 --- /dev/null +++ b/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/src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java b/src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java new file mode 100644 index 00000000..05fe9a6e --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/DeIdentifyResponse.java @@ -0,0 +1,10 @@ +package com.skyflow.vault.detect; + +public class DeIdentifyResponse { + // members + + public DeIdentifyResponse() { + } + + // getters ans setters +} diff --git a/src/main/java/com/skyflow/vault/tokens/ColumnValue.java b/src/main/java/com/skyflow/vault/tokens/ColumnValue.java new file mode 100644 index 00000000..3fa08b2e --- /dev/null +++ b/src/main/java/com/skyflow/vault/tokens/ColumnValue.java @@ -0,0 +1,45 @@ +package com.skyflow.vault.tokens; + +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; + + private ColumnValueBuilder() { + } + + 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/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java new file mode 100644 index 00000000..2fb1d42f --- /dev/null +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java @@ -0,0 +1,47 @@ +package com.skyflow.vault.tokens; + +import com.skyflow.generated.rest.models.V1DetokenizeRecordResponse; + +public class DetokenizeRecordResponse { + private final String token; + private final String value; + private final String type; + private final String error; + + public DetokenizeRecordResponse(V1DetokenizeRecordResponse record) { + this.token = record.getToken(); + this.value = record.getValue(); + this.type = record.getValueType().getValue(); + this.error = record.getError(); + } + + public String getError() { + return error; + } + + public String getToken() { + return token; + } + + public String getValue() { + return value; + } + + 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/DetokenizeRequest.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java new file mode 100644 index 00000000..205ecef7 --- /dev/null +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java @@ -0,0 +1,59 @@ +package com.skyflow.vault.tokens; + +import com.skyflow.enums.RedactionType; + +import java.util.ArrayList; + +public class DetokenizeRequest { + 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; + } + + public static final class DetokenizeRequestBuilder { + private ArrayList tokens; + private RedactionType redactionType; + private Boolean continueOnError; + + private DetokenizeRequestBuilder() { + 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 == null ? RedactionType.PLAIN_TEXT : redactionType; + return this; + } + + public DetokenizeRequestBuilder continueOnError(Boolean continueOnError) { + this.continueOnError = continueOnError == null || continueOnError; + return this; + } + + public DetokenizeRequest build() { + return new DetokenizeRequest(this); + } + } +} diff --git a/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java new file mode 100644 index 00000000..0c136e1a --- /dev/null +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java @@ -0,0 +1,34 @@ +package com.skyflow.vault.tokens; + +import java.util.ArrayList; + +public class DetokenizeResponse { + private final ArrayList detokenizedFields; + private final ArrayList errorRecords; + + public DetokenizeResponse(ArrayList detokenizedFields, ArrayList errorRecords) { + this.detokenizedFields = detokenizedFields; + this.errorRecords = errorRecords; + } + + public ArrayList getDetokenizedFields() { + return detokenizedFields; + } + + public ArrayList getErrors() { + return errorRecords; + } + + @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"); + } +} diff --git a/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java b/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java new file mode 100644 index 00000000..a1a5ca33 --- /dev/null +++ b/src/main/java/com/skyflow/vault/tokens/TokenizeRequest.java @@ -0,0 +1,35 @@ +package com.skyflow.vault.tokens; + +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; + + private TokenizeRequestBuilder() { + } + + public TokenizeRequestBuilder values(List columnValues) { + this.columnValues = columnValues; + return this; + } + + public TokenizeRequest build() { + return new TokenizeRequest(this); + } + } +} diff --git a/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java b/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java new file mode 100644 index 00000000..a82d081a --- /dev/null +++ b/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java @@ -0,0 +1,22 @@ +package com.skyflow.vault.tokens; + +import java.util.List; + +public class TokenizeResponse { + 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/SkyflowTests.java b/src/test/java/com/skyflow/SkyflowTests.java new file mode 100644 index 00000000..041969a7 --- /dev/null +++ b/src/test/java/com/skyflow/SkyflowTests.java @@ -0,0 +1,411 @@ +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 newConnectionURL = 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"; + newConnectionURL = "https://new.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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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); + } + } + + @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.getHttpCode()); + 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.getHttpCode()); + 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 (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyConnectionId.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 (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + 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.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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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); + } + } + + @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.getHttpCode()); + Assert.assertEquals(ErrorMessage.NoTokenGenerationMeansPassed.getMessage(), e.getMessage()); + } + } + + @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().addVaultConfig(vaultConfig).addConnectionConfig(connectionConfig).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) { + 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/src/test/java/com/skyflow/common/utils/HelpersTest.java b/src/test/java/com/skyflow/common/utils/HelpersTest.java deleted file mode 100644 index fea055d2..00000000 --- a/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/src/test/java/com/skyflow/common/utils/TokenUtilsTest.java b/src/test/java/com/skyflow/common/utils/TokenUtilsTest.java deleted file mode 100644 index 1e242cfb..00000000 --- a/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/src/test/java/com/skyflow/common/utils/TokenUtilsValidTokenTest.java b/src/test/java/com/skyflow/common/utils/TokenUtilsValidTokenTest.java deleted file mode 100644 index 75623fb7..00000000 --- a/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/src/test/java/com/skyflow/common/utils/ValidatorsTest.java b/src/test/java/com/skyflow/common/utils/ValidatorsTest.java deleted file mode 100644 index 52abcc15..00000000 --- a/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/src/test/java/com/skyflow/config/ConnectionConfigTests.java b/src/test/java/com/skyflow/config/ConnectionConfigTests.java new file mode 100644 index 00000000..5ff32ca5 --- /dev/null +++ b/src/test/java/com/skyflow/config/ConnectionConfigTests.java @@ -0,0 +1,142 @@ +package com.skyflow.config; + +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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.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 new file mode 100644 index 00000000..cfc61de6 --- /dev/null +++ b/src/test/java/com/skyflow/config/CredentialsTests.java @@ -0,0 +1,266 @@ +package com.skyflow.config; + +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"; + 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"; + } + + @Before + public void setupTest() { + roles.clear(); + } + + @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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + Assert.assertEquals(ErrorMessage.NoTokenGenerationMeansPassed.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyRolesInCredentials() { + try { + 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.getHttpCode()); + 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.getHttpCode()); + 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.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 new file mode 100644 index 00000000..1a5ca703 --- /dev/null +++ b/src/test/java/com/skyflow/config/VaultConfigTests.java @@ -0,0 +1,172 @@ +package com.skyflow.config; + +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 testValidVaultConfigWithCredentialsInValidations() { + 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 testValidVaultConfigWithoutCredentialsInValidations() { + 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 testDefaultEnvInVaultConfigWithCredentialsInValidations() { + 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 testDefaultEnvInVaultConfigWithoutCredentialsInValidations() { + 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 testNoVaultIdInVaultConfigInValidations() { + 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.getHttpCode()); + Assert.assertEquals(ErrorMessage.InvalidVaultId.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyVaultIdInVaultConfigInValidations() { + 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.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyVaultId.getMessage(), e.getMessage()); + } + } + + @Test + public void testNoClusterIdInVaultConfigInValidations() { + 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.getHttpCode()); + Assert.assertEquals(ErrorMessage.InvalidClusterId.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyClusterIdInVaultConfigInValidations() { + 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.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyClusterId.getMessage(), e.getMessage()); + } + } +} diff --git a/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTest.java b/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTest.java deleted file mode 100644 index e78501e0..00000000 --- a/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/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java b/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java new file mode 100644 index 00000000..52272933 --- /dev/null +++ b/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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + Assert.assertEquals(ErrorMessage.InvalidTokenUri.getMessage(), e.getMessage()); + } + } +} diff --git a/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokenResponseTest.java b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokenResponseTest.java deleted file mode 100644 index b75cb031..00000000 --- a/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/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTest.java b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTest.java deleted file mode 100644 index 00e74383..00000000 --- a/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/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java new file mode 100644 index 00000000..50b97e11 --- /dev/null +++ b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java @@ -0,0 +1,222 @@ +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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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/serviceaccount/util/TokenTest.java b/src/test/java/com/skyflow/serviceaccount/util/TokenTest.java deleted file mode 100644 index 19eee9e1..00000000 --- a/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/src/test/java/com/skyflow/serviceaccount/util/TokenTests.java b/src/test/java/com/skyflow/serviceaccount/util/TokenTests.java new file mode 100644 index 00000000..ed5c72b2 --- /dev/null +++ b/src/test/java/com/skyflow/serviceaccount/util/TokenTests.java @@ -0,0 +1,55 @@ +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 { + 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 { + 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/src/test/java/com/skyflow/common/utils/HttpUtilityTest.java b/src/test/java/com/skyflow/utils/HttpUtilityTests.java similarity index 72% rename from src/test/java/com/skyflow/common/utils/HttpUtilityTest.java rename to src/test/java/com/skyflow/utils/HttpUtilityTests.java index e473ee1f..816f1504 100644 --- a/src/test/java/com/skyflow/common/utils/HttpUtilityTest.java +++ b/src/test/java/com/skyflow/utils/HttpUtilityTests.java @@ -1,10 +1,7 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.skyflow.common.utils; +package com.skyflow.utils; +import com.google.gson.JsonObject; import com.skyflow.errors.SkyflowException; -import org.json.simple.JSONObject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -22,28 +19,26 @@ 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 HttpUtilityTest { +@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; - private static String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; @Before public void setup() throws IOException { @@ -65,86 +60,60 @@ protected URLConnection openConnection(final URL arg0) throws IOException { } @Test - @PrepareForTest({ URL.class, HttpURLConnection.class }) + @PrepareForTest({URL.class, HttpURLConnection.class}) public void testSendRequest() { try { given(mockConnection.getRequestProperty("content-type")).willReturn("application/json"); - - JSONObject headers = new JSONObject(); + Map headers = new HashMap<>(); headers.put("content-type", "application/json"); - - JSONObject params = new JSONObject(); - params.put("key", "value"); - + JsonObject params = new JsonObject(); + params.addProperty("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 }) + @PrepareForTest({URL.class, HttpURLConnection.class}) public void testSendRequestFormData() { try { given(mockConnection.getRequestProperty("content-type")).willReturn("multipart/form-data"); - - JSONObject headers = new JSONObject(); + Map headers = new HashMap<>(); headers.put("content-type", "multipart/form-data"); - - JSONObject params = new JSONObject(); - params.put("key", "value"); - + JsonObject params = new JsonObject(); + params.addProperty("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 }) + @PrepareForTest({URL.class, HttpURLConnection.class}) public void testSendRequestFormURLEncoded() { try { given(mockConnection.getRequestProperty("content-type")).willReturn("application/x-www-form-urlencoded"); - - JSONObject headers = new JSONObject(); + Map headers = new HashMap<>(); headers.put("content-type", "application/x-www-form-urlencoded"); - - JSONObject params = new JSONObject(); - params.put("key", "value"); - + JsonObject params = new JsonObject(); + params.addProperty("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 }) + @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) { diff --git a/src/test/java/com/skyflow/utils/UtilsTests.java b/src/test/java/com/skyflow/utils/UtilsTests.java new file mode 100644 index 00000000..79817bc5 --- /dev/null +++ b/src/test/java/com/skyflow/utils/UtilsTests.java @@ -0,0 +1,184 @@ +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"; + 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; + 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() { + 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); + connectionId = "test_connection_id"; + connectionUrl = "https://test.connection.url"; + pathParams = new HashMap<>(); + queryParams = new HashMap<>(); + requestHeaders = new HashMap<>(); + } + + @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.getHttpCode()); + 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.getHttpCode()); + 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); + } + } + + @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/src/test/java/com/skyflow/vault/DeleteMethodTest.java b/src/test/java/com/skyflow/vault/DeleteMethodTest.java deleted file mode 100644 index 9ad439e8..00000000 --- a/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/src/test/java/com/skyflow/vault/GetMethodTest.java b/src/test/java/com/skyflow/vault/GetMethodTest.java deleted file mode 100644 index 2477cbbf..00000000 --- a/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/src/test/java/com/skyflow/vault/InvokeConnectionTest.java b/src/test/java/com/skyflow/vault/InvokeConnectionTest.java deleted file mode 100644 index 70319cc3..00000000 --- a/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/src/test/java/com/skyflow/vault/SkyflowTest.java b/src/test/java/com/skyflow/vault/SkyflowTest.java deleted file mode 100644 index 70dd193f..00000000 --- a/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/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java new file mode 100644 index 00000000..8d950279 --- /dev/null +++ b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java @@ -0,0 +1,409 @@ +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; +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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java b/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java new file mode 100644 index 00000000..102eb9d7 --- /dev/null +++ b/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java @@ -0,0 +1,52 @@ +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; + +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"; + 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 { + 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.EmptyRequestBody.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 new file mode 100644 index 00000000..ca2e85d9 --- /dev/null +++ b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java @@ -0,0 +1,196 @@ +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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.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()); + } + } + + @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 new file mode 100644 index 00000000..8cb43880 --- /dev/null +++ b/src/test/java/com/skyflow/vault/data/DeleteTests.java @@ -0,0 +1,174 @@ +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.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"; + 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"; + } + + @Before + public void setupTest() { + ids.clear(); + } + + @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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyTable.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @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()); + Assert.assertEquals(responseString, response.toString()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} diff --git a/src/test/java/com/skyflow/vault/data/GetTests.java b/src/test/java/com/skyflow/vault/data/GetTests.java new file mode 100644 index 00000000..f9fa98d9 --- /dev/null +++ b/src/test/java/com/skyflow/vault/data/GetTests.java @@ -0,0 +1,500 @@ +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.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"; + 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"; + } + + @Before + public void setupTest() { + ids.clear(); + fields.clear(); + columnValues.clear(); + } + + @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); + fields.add(field); + 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.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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyTableInGetRequestValidations() { + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyTable.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyIdsInGetRequestValidations() { + 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.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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyIdInIds.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyFieldsInGetRequestValidations() { + ids.add(skyflowID); + 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.EmptyFields.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyFieldInFieldsInGetRequestValidations() { + ids.add(skyflowID); + fields.add(field); + fields.add(""); + 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 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.UniqueColumnOrIdsKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testBothIdsAndColumnNameInGetRequestValidations() { + ids.add(skyflowID); + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.BothIdsAndColumnDetailsSpecified.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testBothIdsAndColumnValuesInGetRequestValidations() { + ids.add(skyflowID); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyColumnName.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyColumnValuesInGetRequestValidations() { + 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.getHttpCode()); + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyValueInColumnValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @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/src/test/java/com/skyflow/vault/data/InsertTests.java b/src/test/java/com/skyflow/vault/data/InsertTests.java new file mode 100644 index 00000000..87057d7c --- /dev/null +++ b/src/test/java/com/skyflow/vault/data/InsertTests.java @@ -0,0 +1,413 @@ +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.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"; + 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<>(); + 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.clear(); + tokenMap.put("test_column_1", "test_token_1"); + } + + @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.assertTrue(request.getReturnTokens()); + Assert.assertTrue(request.getTokenMode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.ValuesKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyValuesInInsertRequestValidations() { + 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.getHttpCode()); + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyKeyInValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyValueInValuesInInsertRequestValidations() { + valueMap.put("test_column_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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyValueInValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyUpsertInInsertRequestValidations() { + values.add(valueMap); + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyUpsert.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testUpsertWithHomogenousInInsertRequestValidations() { + values.add(valueMap); + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.HomogenousNotSupportedWithUpsert.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testTokensWithTokenStrictDisableInInsertRequestValidations() { + values.add(valueMap); + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TokensPassedForByotDisable.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoTokensWithTokenStrictEnableInInsertRequestValidations() { + values.add(valueMap); + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE.toString()), + e.getMessage() + ); + } + } + + @Test + public void testNoTokensWithTokenStrictEnableStrictInInsertRequestValidations() { + values.add(valueMap); + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString()), + e.getMessage() + ); + } + } + + @Test + public void testEmptyTokensWithTokenStrictEnableInInsertRequestValidations() { + values.add(valueMap); + 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.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testInsufficientTokensWithTokenStrictEnableStrictInInsertRequestValidations1() { + values.add(valueMap); + tokens.add(tokenMap); + 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.getHttpCode()); + Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage(), e.getMessage()); + } + } + + @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(); + 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()); + } + } + + @Test + public void testTokenValueMismatchInInsertRequestValidations() { + values.add(valueMap); + 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) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.MismatchOfFieldsAndTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyKeyInTokensInInsertRequestValidations() { + 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(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyKeyInTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyValueInTokensInInsertRequestValidations() { + 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(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyValueInTokens.getMessage(), e.getMessage()); + } + } + + @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/src/test/java/com/skyflow/vault/data/QueryTests.java b/src/test/java/com/skyflow/vault/data/QueryTests.java new file mode 100644 index 00000000..82b8499a --- /dev/null +++ b/src/test/java/com/skyflow/vault/data/QueryTests.java @@ -0,0 +1,121 @@ +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; +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"; + private static String vaultID = null; + 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 { + 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"; + 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 + 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.getHttpCode()); + 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.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyQuery.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + 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(2, response.getFields().size()); + Assert.assertEquals(responseString, response.toString()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} diff --git a/src/test/java/com/skyflow/vault/data/UpdateTests.java b/src/test/java/com/skyflow/vault/data/UpdateTests.java new file mode 100644 index 00000000..d323dcee --- /dev/null +++ b/src/test/java/com/skyflow/vault/data/UpdateTests.java @@ -0,0 +1,410 @@ +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.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"; + private static String vaultID = null; + private static String clusterID = null; + private static String skyflowID = null; + private static String table = null; + private static HashMap dataMap = 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); + + skyflowID = "test_update_id_1"; + table = "test_table"; + dataMap = new HashMap<>(); + tokenMap = new HashMap<>(); + } + + @Before + public void setupTest() { + dataMap.clear(); + tokenMap.clear(); + } + + @Test + public void testValidInputInUpdateRequestValidations() { + try { + 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() + .table(table) + .data(dataMap) + .tokens(tokenMap) + .returnTokens(true) + .tokenStrict(Byot.ENABLE) + .build(); + Validations.validateUpdateRequest(request); + Assert.assertEquals(table, request.getTable()); + Assert.assertEquals(3, request.getData().size()); + Assert.assertEquals(1, request.getTokens().size()); + Assert.assertTrue(request.getReturnTokens()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoSkyflowIdInUpdateRequestValidations() { + 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); + } 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 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() { + dataMap.put("skyflow_id", ""); + 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.EmptySkyflowId.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoTableInUpdateRequestValidations() { + UpdateRequest request = UpdateRequest.builder().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.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyTableInUpdateRequestValidations() { + UpdateRequest request = UpdateRequest.builder().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.EmptyTable.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoValuesInUpdateRequestValidations() { + 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.DataKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyValuesInUpdateRequestValidations() { + 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.EmptyData.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyKeyInValuesInUpdateRequestValidations() { + 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); + } 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 testEmptyValueInValuesInUpdateRequestValidations() { + 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); + } 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 testTokensWithTokenStrictDisableInUpdateRequestValidations() { + 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() + .table(table).data(dataMap).tokens(tokenMap).tokenStrict(Byot.DISABLE) + .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.TokensPassedForByotDisable.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoTokensWithTokenStrictEnableInUpdateRequestValidations() { + 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).tokenStrict(Byot.ENABLE) + .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.NoTokensWithByot.getMessage(), Byot.ENABLE.toString()), + e.getMessage() + ); + } + } + + @Test + public void testNoTokensWithTokenStrictEnableStrictInUpdateRequestValidations() { + 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).tokenStrict(Byot.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( + Utils.parameterizedString(ErrorMessage.NoTokensWithByot.getMessage(), Byot.ENABLE_STRICT.toString()), + e.getMessage() + ); + } + } + + @Test + public void testEmptyTokensWithTokenStrictEnableInUpdateRequestValidations() { + 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).tokens(tokenMap).tokenStrict(Byot.ENABLE) + .build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testInsufficientTokensWithTokenStrictEnableStrictInUpdateRequestValidations() { + 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() + .table(table).data(dataMap).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.getHttpCode()); + Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForByotEnableStrict.getMessage(), e.getMessage()); + } + } + + @Test + public void testTokenValueMismatchInUpdateRequestValidations() { + 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() + .table(table).data(dataMap).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.getHttpCode()); + Assert.assertEquals(ErrorMessage.MismatchOfFieldsAndTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyKeyInTokensInUpdateRequestValidations() { + 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() + .table(table).data(dataMap).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.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyKeyInTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyValueInTokensInUpdateRequestValidations() { + 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() + .table(table).data(dataMap).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.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyValueInTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testUpdateResponse() { + try { + 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\"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()); + } 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 new file mode 100644 index 00000000..6c49bc8c --- /dev/null +++ b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -0,0 +1,157 @@ +package com.skyflow.vault.tokens; + +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.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; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.ArrayList; + +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; + + @BeforeClass + public static void setup() throws SkyflowException, NoSuchMethodException { + tokens = new ArrayList<>(); + token = "test_token_1"; + } + + @Before + public void setupTest() { + tokens.clear(); + } + + @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.getHttpCode()); + 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() { + 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.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.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); + 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 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 new file mode 100644 index 00000000..18edf253 --- /dev/null +++ b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java @@ -0,0 +1,139 @@ +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; +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() { + 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"; + + tokens = new ArrayList<>(); + } + + @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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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.getHttpCode()); + 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); + } + } +} diff --git a/src/test/resources/invalidPrivateKeyCredentials.json b/src/test/resources/invalidPrivateKeyCredentials.json new file mode 100644 index 00000000..3615e623 --- /dev/null +++ b/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/src/test/resources/invalidTokenURICredentials.json b/src/test/resources/invalidTokenURICredentials.json new file mode 100644 index 00000000..ac9346aa --- /dev/null +++ b/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/src/test/resources/noClientIDCredentials.json b/src/test/resources/noClientIDCredentials.json new file mode 100644 index 00000000..6e7edd20 --- /dev/null +++ b/src/test/resources/noClientIDCredentials.json @@ -0,0 +1 @@ +{"privateKey":"private_key_value"} \ No newline at end of file diff --git a/src/test/resources/noKeyIDCredentials.json b/src/test/resources/noKeyIDCredentials.json new file mode 100644 index 00000000..64ff438e --- /dev/null +++ b/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/src/test/resources/invalidCredentials.json b/src/test/resources/noPrivateKeyCredentials.json similarity index 100% rename from src/test/resources/invalidCredentials.json rename to src/test/resources/noPrivateKeyCredentials.json diff --git a/src/test/resources/noTokenURICredentials.json b/src/test/resources/noTokenURICredentials.json new file mode 100644 index 00000000..f88b0792 --- /dev/null +++ b/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/src/test/resources/notJson.txt b/src/test/resources/notJson.txt index e69de29b..bdf08de0 100644 --- a/src/test/resources/notJson.txt +++ b/src/test/resources/notJson.txt @@ -0,0 +1 @@ +test file \ No newline at end of file