diff --git a/.github/workflows/beta-release.yml b/.github/workflows/beta-release.yml new file mode 100644 index 00000000..13fcf623 --- /dev/null +++ b/.github/workflows/beta-release.yml @@ -0,0 +1,20 @@ +name: Public beta release +on: + push: + tags: '*.*.*-beta.*' +jobs: + build-and-deploy: + uses: ./.github/workflows/shared-build-and-deploy.yml + with: + ref: ${{ github.ref_name }} + server-id: central + profile: maven-central + tag: 'beta' + secrets: + server-username: ${{ secrets.CENTRAL_PUBLISHER_PORTAL_USERNAME }} + server-password: ${{ secrets.CENTRAL_PUBLISHER_PORTAL_PASSWORD }} + gpg-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} + gpg-passphrase: ${{ secrets.MAVEN_GPG_PASSPHRASE }} + skyflow-credentials: ${{ secrets.SKYFLOW_CREDENTIALS }} >> .env + test-expired-token: ${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + test-reusable-token: ${{ secrets.TEST_REUSABLE_TOKEN }} >> .env diff --git a/.github/workflows/endorlabsScan.yml b/.github/workflows/endorlabsScan.yml index a8642878..3c316417 100644 --- a/.github/workflows/endorlabsScan.yml +++ b/.github/workflows/endorlabsScan.yml @@ -37,7 +37,7 @@ jobs: json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - name: Compile Package - run: mvn -B package -DTEST_VAULT_ID=${{ secrets.TEST_VAULT_ID }} -DTEST_VAULT_URL=${{ secrets.TEST_VAULT_URL }} -DTEST_SKYFLOW_ID=${{ secrets.TEST_SKYFLOW_ID }} -DTEST_TOKEN=${{ secrets.TEST_TOKEN }} -DTEST_CREDENTIALS=${{ secrets.TEST_CREDENTIALS_FILE_STRING }} -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -DTEST_REUSABLE_TOKEN=${{ secrets.TEST_REUSABLE_TOKEN }} -DSKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} -f pom.xml + run: mvn -B package -f pom.xml -Dmaven.javadoc.skip=true - name: Endor Labs SCA Scan uses: endorlabs/github-action@main @@ -47,4 +47,4 @@ jobs: pr: false enable_github_action_token: true scan_dependencies: true - additional_args: "--as-default-branch --call-graph-languages=java" + additional_args: "--as-default-branch --call-graph-languages=java" \ No newline at end of file diff --git a/.github/workflows/internal-release.yml b/.github/workflows/internal-release.yml index 1e26a801..e8b8ee61 100644 --- a/.github/workflows/internal-release.yml +++ b/.github/workflows/internal-release.yml @@ -1,9 +1,9 @@ name: Publish package to the JFROG Artifactory on: push: - tags: '*.*.*' + tags-ignore: + - '*.*' paths-ignore: - - "pom.xml" - "*.md" branches: - release/* @@ -13,11 +13,14 @@ jobs: uses: ./.github/workflows/shared-build-and-deploy.yml with: ref: ${{ github.ref_name }} - is-internal: true server-id: central profile: jfrog + tag: 'internal' secrets: server-username: ${{ secrets.ARTIFACTORY_USERNAME }} server-password: ${{ secrets.ARTIFACTORY_PASSWORD }} gpg-key: ${{ secrets.JFROG_GPG_KEY }} - gpg-passphrase: ${{ secrets.JFROG_GPG_PASSPHRASE }} \ No newline at end of file + gpg-passphrase: ${{ secrets.JFROG_GPG_PASSPHRASE }} + skyflow-credentials: ${{ secrets.SKYFLOW_CREDENTIALS }} >> .env + test-expired-token: ${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + test-reusable-token: ${{ secrets.TEST_REUSABLE_TOKEN }} >> .env diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index efdecf24..db7c9850 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -13,7 +13,7 @@ jobs: - uses: actions/checkout@v1 - uses: actions/setup-java@v1 with: - java-version: '1.8' + java-version: '11' - name: create-json id: create-json @@ -23,7 +23,7 @@ jobs: json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - name: Build & Run tests with Maven - run: mvn -B package -DTEST_VAULT_ID=${{ secrets.TEST_VAULT_ID }} -DTEST_VAULT_URL=${{ secrets.TEST_VAULT_URL }} -DTEST_SKYFLOW_ID=${{ secrets.TEST_SKYFLOW_ID }} -DTEST_TOKEN=${{ secrets.TEST_TOKEN }} -DTEST_CREDENTIALS=${{ secrets.TEST_CREDENTIALS_FILE_STRING }} -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -f pom.xml + run: mvn -B package -f pom.xml -Dmaven.javadoc.skip=true - name: Codecov uses: codecov/codecov-action@v2.1.0 diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 7ce64698..2b2945f0 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]*)|(\[AUTOMATED\])|(Merge)|(Release).+$' - flags: 'gm' - excludeDescription: 'true' - checkAllCommitMessages: 'true' + flags: "gm" + excludeDescription: "true" + checkAllCommitMessages: "true" accessToken: ${{ secrets.PAT_ACTIONS }} - error: 'One of your your commit messages is not matching the format with JIRA ID Ex: ( SDK-123 commit message )' + error: "One of your your commit messages is not matching the format with JIRA ID Ex: ( SDK-123 commit message )" Test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions/setup-java@v1 with: - java-version: '1.8' + java-version: "11" - name: create-json id: create-json @@ -31,8 +31,16 @@ 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 + echo TEST_REUSABLE_TOKEN=${{ secrets.TEST_REUSABLE_TOKEN }} >> .env + - name: Build & Run tests with Maven - run: mvn -B package -DTEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} -DTEST_DATA_CREDENTIALS_FILE=${{ secrets.TEST_DATA_CREDENTIALS_FILE }} -f pom.xml + run: mvn -B package -f pom.xml -Dmaven.javadoc.skip=true - name: Codecov uses: codecov/codecov-action@v2.1.0 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f978c067..720e16d8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,17 +1,20 @@ -name: Publish package to the Maven Central Repository +name: Public release on: push: - tags: '*.*.*' + tags: '[0-9]+.[0-9]+.[0-9]+' jobs: build-and-deploy: uses: ./.github/workflows/shared-build-and-deploy.yml with: ref: ${{ github.ref_name }} - is-internal: false - server-id: ossrh + server-id: central profile: maven-central + tag: 'public' secrets: - server-username: ${{ secrets.OSSRH_USERNAME }} - server-password: ${{ secrets.OSSRH_PASSWORD }} + server-username: ${{ secrets.CENTRAL_PUBLISHER_PORTAL_USERNAME }} + server-password: ${{ secrets.CENTRAL_PUBLISHER_PORTAL_PASSWORD }} gpg-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} - gpg-passphrase: ${{ secrets.MAVEN_GPG_PASSPHRASE }} \ No newline at end of file + gpg-passphrase: ${{ secrets.MAVEN_GPG_PASSPHRASE }} + skyflow-credentials: ${{ secrets.SKYFLOW_CREDENTIALS }} >> .env + test-expired-token: ${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + test-reusable-token: ${{ secrets.TEST_REUSABLE_TOKEN }} >> .env diff --git a/.github/workflows/shared-build-and-deploy.yml b/.github/workflows/shared-build-and-deploy.yml index 43a54dec..13fd1b5b 100644 --- a/.github/workflows/shared-build-and-deploy.yml +++ b/.github/workflows/shared-build-and-deploy.yml @@ -3,22 +3,22 @@ on: workflow_call: inputs: ref: - description: 'Git reference to use (e.g., main or branch name)' + description: "Git reference to use (e.g., main or branch name)" required: true type: string - is-internal: - description: 'Flag for internal release' - required: true - type: boolean - server-id: - description: 'Id of the repository' + description: "Id of the repository" required: true type: string - + profile: - description: 'Profile to pick from pom.xml' + description: "Profile to pick from pom.xml" + required: true + type: string + + tag: + description: 'Release Tag' required: true type: string secrets: @@ -34,25 +34,46 @@ on: gpg-passphrase: required: true + skyflow-credentials: + required: true + + test-expired-token: + required: true + + test-reusable-token: + required: true + jobs: publish: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: - ref: ${{ inputs.ref }} fetch-depth: 0 - name: Set up maven or jfrog repository - uses: actions/setup-java@v1 + uses: actions/setup-java@v4 with: - java-version: '1.8' - distribution: 'adopt' + java-version: "11" + distribution: "adopt" server-id: ${{ inputs.server-id }} server-username: SERVER_USERNAME server-password: SERVER_PASSWORD gpg-private-key: ${{ secrets.gpg-key }} # Value of the GPG private key to import gpg-passphrase: GPG_PASSPHRASE # env variable for GPG private key passphrase + + - name: Resolve Branch for the Tagged Commit + id: resolve-branch + if: ${{ inputs.tag == 'beta' || inputs.tag == 'public' }} + run: | + TAG_COMMIT=$(git rev-list -n 1 ${{ github.ref_name }}) + BRANCH_NAME=$(git branch -r --contains $TAG_COMMIT | grep -o 'origin/.*' | sed 's|origin/||' | head -n 1) + if [ -z "$BRANCH_NAME" ]; then + echo "Error: Could not resolve branch for the tag." + exit 1 + fi + echo "Resolved Branch Name: $BRANCH_NAME" + echo "branch_name=$BRANCH_NAME" >> $GITHUB_ENV - name: Get Previous tag id: previoustag @@ -63,7 +84,7 @@ jobs: - name: Bump Version run: | chmod +x ./scripts/bump_version.sh - if ${{ inputs.is-internal }}; then + if ${{ inputs.tag == 'internal' }}; then ./scripts/bump_version.sh "${{ steps.previoustag.outputs.tag }}" "$(git rev-parse --short "$GITHUB_SHA")" else ./scripts/bump_version.sh "${{ steps.previoustag.outputs.tag }}" @@ -73,22 +94,28 @@ jobs: run: | git config user.name ${{ github.actor }} git config user.email ${{ github.actor }}@users.noreply.github.com + + if [[ "${{ inputs.tag }}" == "beta" || "${{ inputs.tag }}" == "public" ]]; then + git checkout ${{ env.branch_name }} + fi + git add pom.xml - if ${{ inputs.is-internal }}; then + if [[ "${{ inputs.tag }}" == "internal" ]]; then git commit -m "[AUTOMATED] Private Release ${{ steps.previoustag.outputs.tag }}-dev-$(git rev-parse --short $GITHUB_SHA)" git push origin ${{ github.ref_name }} -f - else + fi + if [[ "${{ inputs.tag }}" == "beta" || "${{ inputs.tag }}" == "public" ]]; then git commit -m "[AUTOMATED] Public Release - ${{ steps.previoustag.outputs.tag }}" - git push origin + git push origin ${{ env.branch_name }} fi - name: Create env - if: ${{ inputs.is-internal }} id: create-env run: | touch .env - echo SKYFLOW_CREDENTIALS=${{ secrets.SKYFLOW_CREDENTIALS }} >> .env - echo TEST_EXPIRED_TOKEN=${{ secrets.TEST_EXPIRED_TOKEN }} >> .env + echo SKYFLOW_CREDENTIALS=${{ secrets.skyflow-credentials }} >> .env + echo TEST_EXPIRED_TOKEN=${{ secrets.test-expired-token }} >> .env + echo TEST_REUSABLE_TOKEN=${{ secrets.test-reusable-token }} >> .env - name: Create credentials json id: create-json @@ -98,8 +125,9 @@ jobs: json: ${{ secrets.TEST_CREDENTIALS_FILE_STRING }} - name: Publish package - run: mvn clean deploy -P ${{ inputs.profile }} + run: mvn --batch-mode deploy -P ${{ inputs.profile }} + env: SERVER_USERNAME: ${{ secrets.server-username }} SERVER_PASSWORD: ${{ secrets.server-password }} - GPG_PASSPHRASE: ${{ secrets.gpg-passphrase }} \ No newline at end of file + GPG_PASSPHRASE: ${{ secrets.gpg-passphrase }} diff --git a/README.md b/README.md index 647e8fe5..ed471ba4 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # Skyflow Java + The Skyflow Java SDK is designed to help with integrating Skyflow into a Java backend. [![CI](https://img.shields.io/static/v1?label=CI&message=passing&color=green?style=plastic&logo=github)](https://github.com/skyflowapi/skyflow-java/actions) @@ -7,349 +8,214 @@ The Skyflow Java SDK is designed to help with integrating Skyflow into a Java ba # Table of Contents -- [Skyflow Java](#skyflow-java) - [Table of Contents](#table-of-contents) - - [Features](#features) - - [Installation](#installation) - - [Requirements](#requirements) - - [Configuration](#configuration) - - [Gradle users](#gradle-users) - - [Maven users](#maven-users) - - [Service Account Bearer Token Generation](#service-account-bearer-token-generation) - - [Service Account Bearer Token with Context Generation](#service-account-bearer-token-with-context-generation) - - [Service Account Scoped Bearer Token Generation](#service-account-scoped-bearer-token-generation) - - [Signed Data Tokens Generation](#signed-data-tokens-generation) - - [Vault APIs](#vault-apis) - - [Insert](#insert) - - [InsertBulk](#insertbulk) - - [Detokenize](#detokenize) - - [Get](#get) - - [Use Skyflow IDs](#use-skyflow-ids) - - [Use column name and values](#use-column-name-and-values) - - [Redaction types](#redaction-types) - - [Examples](#examples) - - [GetById](#getbyid) - - [Update](#update) - - [Delete](#delete) - - [Invoke Connection](#invoke-connection) - - [Query](#query) - - [Logging](#logging) - - [Reporting a Vulnerability](#reporting-a-vulnerability) - -## Features - -- Authenticate with a Skyflow service account and generate a bearer token. -- Insert, retrieve and tokenize sensitive data. -- Invoke connections to call downstream third party APIs without directly handling sensitive data. - -## Installation - -### Requirements -- Java 1.8 and above - -### Configuration ---- -#### Gradle users - -Add this dependency to your project's build file: -``` -implementation 'com.skyflow:skyflow-java:1.15.0' -``` - -#### Maven users -Add this dependency to your project's POM: +- [Overview](#overview) +- [Install](#install) + - [Requirements](#requirements) + - [Configuration](#configuration) + - [Gradle users](#gradle-users) + - [Maven users](#maven-users) +- [Migration from v1 to v2](#migration-from-v1-to-v2) + - [Authentication options](#authentication-options) + - [Initializing the client](#initializing-the-client) + - [Request & response structure](#request--response-structure) + - [Request options](#request-options) + - [Error structure](#error-structure) +- [Quickstart](#quickstart) + - [Authenticate](#authenticate) + - [Initialize the client](#initialize-the-client) + - [Insert data into the vault](#insert-data-into-the-vault) +- [Vault](#vault) + - [Insert data into the vault](#insert-data-into-the-vault-1) + - [Detokenize](#detokenize) + - [Tokenize](#tokenize) + - [Get](#get) + - [Get by skyflow IDS](#get-by-skyflow-ids) + - [Get tokens](#get-tokens) + - [Get by column name and column values](#get-by-column-name-and-column-values) + - [Redaction types](#redaction-types) + - [Update](#update) + - [Delete](#delete) + - [Query](#query) + - [Upload File](#upload-file) +- [Detect](#detect) + - [Deidentify Text](#deidentify-text) + - [Reidentify Text](#reidentify-text) + - [Deidentify File](#deidentify-file) + - [Get Run](#get-run) +- [Connections](#connections) + - [Invoke a connection](#invoke-a-connection) +- [Authenticate with bearer tokens](#authenticate-with-bearer-tokens) + - [Generate a bearer token](#generate-a-bearer-token) + - [Generate bearer tokens with context](#generate-bearer-tokens-with-context) + - [Generate scoped bearer tokens](#generate-scoped-bearer-tokens) + - [Generate signed data tokens](#generate-signed-data-tokens) + - [Bearer token expiry edge case](#bearer-token-expiry-edge-case) +- [Logging](#logging) +- [Reporting a Vulnerability](#reporting-a-vulnerability) + +# Overview + +- Authenticate using a Skyflow service account and generate bearer tokens for secure access. +- Perform Vault API operations such as inserting, retrieving, and tokenizing sensitive data with ease. +- Invoke connections to third-party APIs without directly handling sensitive data, ensuring compliance and data protection. + +# Install + +## Requirements + +- Java 8 and above (tested with Java 8) + +## Configuration -```xml - - com.skyflow - skyflow-java - 1.15.0 - -``` --- -## Service Account Bearer Token Generation -The [Service Account](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/serviceaccount) java module is used to generate service account tokens from service account credentials file which is downloaded upon creation of service account. The token generated from this module is valid for 60 minutes and can be used to make API calls to vault services as well as management API(s) based on the permissions of the service account. +### Gradle users -The `generateBearerToken(filepath)` function takes the credentials file path for token generation, alternatively, you can also send the entire credentials as string, by using `generateBearerTokenFromCreds(credentials)` +Add this dependency to your project's `build.gradle` file: -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/TokenGenerationExample.java -): - -```java - -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.entities.ResponseToken; - -public class TokenGenerationUtil { +``` +implementation 'com.skyflow:skyflow-java:2.0.0' +``` - private static String bearerToken = null; +### Maven users - public static String getSkyflowBearerToken() { - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - ResponseToken response = Token.generateBearerToken(filePath); - // or Token.generateBearerTokenFromCreds(credentialsString) - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } +Add this dependency to your project's `pom.xml` file: - return bearerToken; - } -} +```xml + + com.skyflow + skyflow-java + 2.0.0 + ``` -## Service Account Bearer Token with Context Generation +--- -Context-Aware Authorization enables you to embed context values into a Bearer token when you generate it, and reference those values in your policies for more dynamic access control of data in the vault or validating signed data tokens during detokenization. It can be used to track end user identity when making API calls using service accounts. +# Migrate from v1 to v2 -The service account generated with `context_id` identifier enabled can be used to generate bearer tokens with `context`, which is a `jwt` claim for a skyflow generated bearer token. The token generated from this service account will have a `context_identifier` claim and is valid for 60 minutes and can be used to make API calls to vault services as well as management API(s) based on the permissions of the service account. +Below are the steps to migrate the java sdk from v1 to v2. -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/BearerTokenWithContextGenerationExample.java): +### Authentication options -``` java -import com.skyflow.entities.ResponseToken; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import java.io.File; +In V2, we have introduced multiple authentication options. You can now provide credentials in the following ways: -public class BearerTokenWithContextGeneration { - public static void main(String args[]) { - String bearerToken = null; - // Generate a bearer token using a service account key file with a context value of "abc". - try { - String filePath = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(filePath)) - .setContext("abc") - .build(); +- Passing credentials in ENV. (`SKYFLOW_CREDENTIALS`) _(Recommended)_ +- API Key +- Path to your credentials JSON file +- Stringified JSON of your credentials +- Bearer token - bearerToken = token.getBearerToken(); - System.out.println(bearerToken); - } catch (Exception e) { - e.printStackTrace(); - } - // Generate a bearer token using a service account key string with a context value of "abc". - try { - String fileContents = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(fileContents) - .setContext("abc") - .build(); +These options allow you to choose the authentication method that best suits your use case. - bearerToken = token.getBearerToken(); - System.out.println(bearerToken); +**V1 (Old)** +```java +static class DemoTokenProvider implements TokenProvider { + @Override + public String getBearerToken() throws Exception { + ResponseToken res = null; + try { + String filePath = ""; + res = Token.generateBearerToken(filePath); } catch (SkyflowException e) { e.printStackTrace(); } + return res.getAccessToken(); } } ``` -Note: -- You can pass either a service account key credentials file path or a service account key credentials as string to the `setCredentials` method of the BearerTokenBuilder class. -- If you pass both a file path and string to the `setCredentials` method, the last method used takes precedence. -- To generate multiple bearer tokens using a thread, see this [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/BearerTokenGenerationUsingThreadsExample.java) - -## Service Account Scoped Bearer Token Generation +**V2 (New): Passing one of the following:** -A service account that has multiple roles can generate bearer tokens with access restricted to a specific role by providing the appropriate `roleID`. Generated bearer tokens are valid for 60 minutes and can only perform operations with the permissions associated with the specified role. +```java +// Option 1: API Key (Recommended) +Credentials skyflowCredentials = new Credentials(); +skyflowCredentials.setApiKey(""); // Replace with your actual API key -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/ScopedTokenGenerationExample.java): +// Option 2: Environment Variables (Recommended) +// Set SKYFLOW_CREDENTIALS in your environment -```java -import java.io.File; +// Option 3: Credentials File +skyflowCredentials.setPath(""); // Replace with the path to credentials file -public class ScopedTokenGeneration { - public static void main(String args[]) { - String scopedToken = null; - // Generate a bearer token using a service account file path scoped to a specific role. - try { - String filePath = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(filePath)) - .setRoles(new String[] { - "roleID" - }) - .build(); +// Option 4: Stringified JSON +skyflowCredentials.setCredentialsString(""); // Replace with the credentials string - scopedToken = token.getBearerToken(); - System.out.println(scopedToken); - } catch (Exception e) { - e.printStackTrace(); - } - } -} +// Option 5: Bearer Token +skyflowCredentials.setToken(""); // Replace with your actual authentication token. ``` -Note: -- You can pass either a service account key credentials file path or a service account key credentials as string to the `setCredentials` method of the BearerTokenBuilder class. -- If you pass both a file path and string to the `setCredentials` method, the last method used takes precedence. -## Signed Data Tokens Generation -Skyflow generates data tokens when sensitive data is inserted into the vault. These data tokens can be digitally signed with the private key of the service account credentials, which adds an additional layer of protection. Signed tokens can be detokenized by passing the signed data token and a bearer token generated from service account credentials. The service account must have appropriate permissions and context to detokenize the signed data tokens. +Notes: +- Use only ONE authentication method. +- API Key or environment variables are recommended for production use. +- Secure storage of credentials is essential. +- For overriding behavior and priority order of credentials, please refer to [Initialize the client](#initialize-the-client) section in [Quickstart](#quickstart). -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/SignedTokenGenerationExample.java): +--- -``` java -import com.skyflow.errors.SkyflowException; -import java.io.File; -import java.util.List; +### Initializing the client -public class SignedTokenGeneration { - public static void main(String args[]) { - List < SignedDataTokenResponse > signedTokenValue; - // Generate signed data tokens using a service account file path, context information, and a time to live. - try { - String filePath = ""; - String context = "abc"; - SignedDataTokens signedToken = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(new File(filePath)) - .setContext(context) - .setTimeToLive(30.0) // Time to live set in seconds. - .setDataTokens(new String[] { - "dataToken1" - }).build(); - - signedTokenValue = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValue); - } catch (Exception e) { - e.printStackTrace(); - } - // Generate signed data tokens using a service account key string, context information, and a time to live. - try { - String fileContents = ""; - String context = "abc"; - SignedDataTokens signedToken = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(fileContents) - .setContext(context) - .setTimeToLive(30.0) // Time to live set in seconds. - .setDataTokens(new String[] { - "dataToken1" - }).build(); +In V2, we have introduced a builder design pattern for client initialization and added support for multi-vault. This allows you to configure multiple vaults during client initialization. In V2, the log level is tied to each individual client instance. During client initialization, you can pass the following parameters: - signedTokenValue = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValue); +- `vaultId` and `clusterId`: These values are derived from the vault ID & vault URL. +- `env`: Specify the environment (e.g., SANDBOX or PROD). +- `credentials`: The necessary authentication credentials. - } catch (SkyflowException e) { - e.printStackTrace(); - } - } -} -``` -Response: +**V1 (Old)** -``` java -[ - { - "token":"5530-4316-0674-5748", - "signedToken":"signed_token_eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJzLCpZjA" - } -] +```java +// DemoTokenProvider class is an implementation of the TokenProvider interface +DemoTokenProvider demoTokenProvider = new DemoTokenProvider(); +SkyflowConfiguration skyflowConfig = new SkyflowConfiguration("","", demoTokenProvider); +Skyflow skyflowClient = Skyflow.init(skyflowConfig); ``` -Note: -- You can pass either a service account key credentials file path or a service account key credentials as string to the `setCredentials` method of the SignedDataTokensBuilder class. -- If you pass both a file path and string to the `setCredentials` method, the last method used takes precedence. -- Time to live value expects time as seconds. -- The default time to live value is 60 seconds. -## Vault APIs -The [Vault](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault) module is used to perform operations on the vault such as inserting records, detokenizing tokens, retrieving tokens for a skyflow_id and to invoke a connection. +**V2 (New)** -To use this module, the skyflow client must first be initialized as follows. ```java -import com.skyflow.vault.Skyflow; -import com.skyflow.entities.SkyflowConfiguration; +Credentials credentials = new Credentials(); +credentials.setPath(""); // Replace with the path to the credentials file + +// Configure the first vault (Blitz) +VaultConfig config = new VaultConfig(); +config.setVaultId(""); // Replace with the ID of the first vault +config.setClusterId(""); // Replace with the cluster ID of the first vault +config.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) +config.setCredentials(credentials); // Associate the credentials with the vault + +// Set up credentials for the Skyflow client +Credentials skyflowCredentials = new Credentials(); +skyflowCredentials.setPath(""); // Replace with the path to another credentials file + +// Create a Skyflow client and add vault configurations +Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs + .addVaultConfig(config) // Add the first vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials + .build(); +``` -// DemoTokenProvider class is an implementation of the TokenProvider interface -DemoTokenProvider demoTokenProvider = new DemoTokenProvider(); +**Key Changes:** -SkyflowConfiguration skyflowConfig = new SkyflowConfiguration(,,demoTokenProvider); +- `vaultUrl` replaced with `clusterId`. +- Added environment specification (`env`). +- Instance-specific log levels. -Skyflow skyflowClient = Skyflow.init(skyflowConfig); -``` -Example implementation of DemoTokenProvider using credentials file path is as follows -```java -import com.skyflow.entities.TokenProvider; +--- -static class DemoTokenProvider implements TokenProvider { - - @Override - public String getBearerToken() throws Exception { - ResponseToken res = null; - try { - String filePath = ""; - res = Token.generateBearerToken(filePath); - } catch (SkyflowException e) { - e.printStackTrace(); - } - return res.getAccessToken(); - } - } -``` +### Request & response structure -Example implementation of DemoTokenProvider using credentials file content is as follows -```java -import com.skyflow.entities.TokenProvider; +In V2, we have removed the use of JSON objects from a third-party package. Instead, we have transitioned to accepting native ArrayList and HashMap data structures and adopted the builder pattern for request creation. This request needs: -static class DemoTokenProvider implements TokenProvider { - @Override - public String getBearerToken() throws Exception { - ResponseToken res = null; - try { - String filePath = ""; - res = Token.generateBearerTokenFromCreds(filePath); - } catch (SkyflowException e) { - e.printStackTrace(); - } - return res.getAccessToken(); - } - return res.getAccessToken(); -} -``` +- `table`: The name of the table. +- `values`: An array list of objects containing the data to be inserted. -All Vault APIs must be invoked using a client instance. +The response will be of type `InsertResponse` class, which contains `insertedFields` and `errors`. -## Insert +**V1 (Old):** Request building -To insert data into your vault, use the **insert(JSONObject insertInput, InsertOptions options)** method. The first parameter `insertInput` is a JSON object that must have a `records` key and takes an array of records to insert into the vault as a value. The second parameter, `options` is an `InsertOptions` object that provides further options for your insert call, including **upsert** operations as shown below: -```java -import com.skyflow.entities.InsertOptions; -import com.skyflow.entities.UpsertOption; -// initialize Skyflow - -// construct insert input -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject record = new JSONObject(); -record.put("table", ""); - -JSONObject fields = new JSONObject(); -fields.put("", ""); -record.put("fields", fields); -recordsArray.add(record); -records.put("records", recordsArray); - -// Create an upsert option and insert it into the UpsertOption array. -UpsertOption[] upsertOptions = new UpsertOption[1]; -upsertOptions[0] = new UpsertOption( - '', // Table name. - '' // Unique column in the table. - ); -// Indicates whether or not tokens should be returned for the inserted data. Defaults to 'True' -InsertOptions insertOptions = new InsertOptions( - true, - upsertOptions - ); - -``` -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/InsertWithUpsertExample.java) of insert call with upsert support ```java JSONObject recordsJson = new JSONObject(); JSONArray recordsArrayJson = new JSONArray(); @@ -359,450 +225,464 @@ recordJson.put("table", "cards"); JSONObject fieldsJson = new JSONObject(); fields.put("cardNumber", "41111111111"); -fields.put("cvv","123"); +fields.put("cvv", "123"); recordJson.put("fields", fieldsJson); recordsArrayJson.add(record); recordsJson.put("records", recordsArrayJson); - -// Create an Uupsert option and insert it into the UpsertOptions array. -UpsertOption[] upsertOptions = new UpsertOption[1]; -upsertOptions[0] = new UpsertOption("cards", "cardNumber"); - -// Pass Upsert options in the insert method options. -InsertOptions insertOptions = new InsertOptions(true, upsertOptions); - try { - JSONObject insertResponse = skyflowClient.insert(records,insertOptions); + JSONObject insertResponse = skyflowClient.insert(records); System.out.println(insertResponse); } catch (SkyflowException exception) { System.out.println(exception); } ``` -Sample insert Response -```js -{ - "records": [ - { - "table": "cards", - "fields": { - "skyflow_id": "16419435-aa63-4823-aae7-19c6a2d6a19f", - "cardNumber": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", - "cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5", - }, - } - ] -} -``` -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/InsertWithContinueOnErrorExample.java) of Insert call with `continueOnError` support: +**V2 (New):** Request building + ```java -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject invalidRecord = new JSONObject(); -invalidRecord.put("table", "cards"); -JSONObject invalidRecordFields = new JSONObject(); -invalidRecordFields.put("namee", "john doe"); -invalidRecordFields.put("card_number", "4111111111111111"); -invalidRecordFields.put("cvv", "1125"); -invalidRecord.put("fields", invalidRecordFields); - -JSONObject validRecord = new JSONObject(); -validRecord.put("table", "cards"); -JSONObject validRecordFields = new JSONObject(); -validRecordFields.put("name", "jane doe"); -validRecordFields.put("card_number", "4111111111111111"); -validRecordFields.put("cvv", "1125"); -validRecord.put("fields", validRecordFields); - -recordsArray.add(invalidRecord); -recordsArray.add(validRecord); -records.put("records", recordsArray); +ArrayList> values = new ArrayList<>(); +HashMap value = new HashMap<>(); +value.put("", ""); // Replace with column name and value +value.put("", ""); // Replace with another column name and value +values.add(values); + +ArrayList> tokens = new ArrayList<>(); +HashMap token = new HashMap<>(); +token.put("", ""); // Replace with the token for COLUMN_NAME_2 +tokens.add(token); + +InsertRequest insertRequest = InsertRequest.builder() + .table("") // Replace with the table name + .continueOnError(true) // Continue inserting even if some records fail + .tokenMode(TokenMode.ENABLE) // Enable BYOT for token validation + .values(values) // Data to insert + .tokens(tokens) // Provide tokens for BYOT columns + .returnTokens(true) // Return tokens along with the response + .build(); +``` -try { - InsertOptions insertOptions = new InsertOptions(true, true); - JSONObject insertResponse = skyflowClient.insert(records, insertOptions); - System.out.println(insertResponse); -} catch (SkyflowException e) { - System.out.println(e); - e.printStackTrace(); +**V1 (Old):** Response structure + +```json +{ + "records": [ + { + "table": "cards", + "fields": { + "skyflow_id": "16419435-aa63-4823-aae7-19c6a2d6a19f", + "cardNumber": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", + "cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5" + } + } + ] } ``` -Sample Response: -```js +**V2 (New):** Response structure + +```json { - "records": [ - { - "table": "cards", - "fields": { - "skyflow_id": "16419435-aa63-4823-aae7-19c6a2d6a19f", - "cardNumber": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", - "cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5", - "name": "245d3a0f-a2d3-443b-8a20-8c17de86e186", - }, - "request_index": 1, - } - ], - "errors": [ - { - "error": { - "code":400, - "description":"Invalid field present in JSON namee - requestId: 87fb2e32-6287-4e61-8304-9268df12bfe8", - "request_index": 0, - } - } - ] + "insertedFields": [ + { + "card_number": "5484-7829-1702-9110", + "request_index": "0", + "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", + "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b" + } + ], + "errors": [] } ``` -## InsertBulk +--- + +### Request options + +In V2, with the introduction of the builder design pattern has made handling optional fields in Java more efficient and straightforward. -To insert data into your vault using Bulk operation, use the **insertBulk(JSONObject insertInput, InsertBulkOptions options)** method. The first parameter `insertInput` is a JSON object that must have a `records` key and takes an array of records to insert into the vault as a value. The second parameter, `options` is an `InsertOptions` object that provides further options for your insert call, including **upsert** operations as shown below: +**V1 (Old)** ```java -import com.skyflow.entities.InsertOptions; -import com.skyflow.entities.UpsertOption; -// initialize Skyflow - -// construct insert input -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject record = new JSONObject(); -record.put("table", ""); - -JSONObject fields = new JSONObject(); -fields.put("", ""); -record.put("fields", fields); -recordsArray.add(record); -records.put("records", recordsArray); - -// Create an upsert option and insert it into the UpsertOption array. -UpsertOption[] upsertOptions = new UpsertOption[1]; -upsertOptions[0] = new UpsertOption( - '', // Table name. - '' // Unique column in the table. - ); -// Indicates whether or not tokens should be returned for the inserted data. Defaults to 'True' -InsertBulkOptions insertOptions = new InsertBulkOptions( - true, - upsertOptions - ); -``` -An [example]() of insert call with upsert support: +InsertOptions insertOptions = new InsertOptions(true); +``` + +**V2 (New)** ```java -JSONObject recordsJson = new JSONObject(); -JSONArray recordsArrayJson = new JSONArray(); +InsertRequest upsertRequest = InsertRequest.builder() + .table("") // Replace with the table name + .continueOnError(false) // Stop inserting if any record fails + .tokenMode(TokenMode.DISABLE) // Disable BYOT + .values(values) // Data to insert + .returnTokens(false) // Do not return tokens + .upsert("") // Replace with the column name used for upsert logic + .build(); +``` -JSONObject recordJson = new JSONObject(); -recordJson.put("table", "cards"); +--- -JSONObject fieldsJson = new JSONObject(); -fields.put("cardNumber", "41111111111"); -fields.put("cvv","123"); +### Error structure -recordJson.put("fields", fieldsJson); -recordsArrayJson.add(record); -recordsJson.put("records", recordsArrayJson); +In V2, we have enriched the error details to provide better debugging capabilities. +The error response now includes: -// Create an Uupsert option and insert it into the UpsertOptions array. -UpsertOption[] upsertOptions = new UpsertOption[1]; -upsertOptions[0] = new UpsertOption("cards", "cardNumber"); +- `httpStatus`: The HTTP status code. +- `grpcCode`: The gRPC code associated with the error. +- `details` & `message`: A detailed description of the error. +- `requestId`: A unique request identifier for easier debugging. -// Pass Upsert options in the insert method options. -InsertBulkOptions insertOptions = new InsertBulkOptions(true, upsertOptions); +**V1 (Old):** Error structure -try { - JSONObject insertResponse = skyflowClient.insertBulk(records,insertOptions); - System.out.println(insertResponse); -} catch (SkyflowException exception) { - System.out.println(exception); -} -``` -Sample insert Response -```js +```json { - "records": [ - { - "table": "cards", - "fields": { - "skyflow_id": "16419435-aa63-4823-aae7-19c6a2d6a19f", - "cardNumber": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", - "cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5", - }, - } - ] + "code": "", + "description": "" } ``` -An [example]() of Insert using bulk call: -```java -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject invalidRecord = new JSONObject(); -invalidRecord.put("table", "cards"); -JSONObject invalidRecordFields = new JSONObject(); -invalidRecordFields.put("namee", "john doe"); -invalidRecordFields.put("card_number", "4111111111111111"); -invalidRecordFields.put("cvv", "1125"); -invalidRecord.put("fields", invalidRecordFields); - -JSONObject validRecord = new JSONObject(); -validRecord.put("table", "cards"); -JSONObject validRecordFields = new JSONObject(); -validRecordFields.put("name", "jane doe"); -validRecordFields.put("card_number", "4111111111111111"); -validRecordFields.put("cvv", "1125"); -validRecord.put("fields", validRecordFields); - -recordsArray.add(invalidRecord); -recordsArray.add(validRecord); -records.put("records", recordsArray); - -try { - InsertBulkOptions insertOptions = new InsertBulkOptions(true); - JSONObject insertResponse = skyflowClient.insertBulk(records, insertOptions); - System.out.println(insertResponse); -} catch (SkyflowException e) { - System.out.println(e); - e.printStackTrace(); -} -``` +**V2 (New):** Error structure -Sample Response: ```js { - "records": [ - { - "table": "cards", - "fields": { - "skyflow_id": "16419435-aa63-4823-aae7-19c6a2d6a19f", - "cardNumber": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", - "cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5", - "name": "245d3a0f-a2d3-443b-8a20-8c17de86e186", - }, - "request_index": 1, - } - ], - "errors": [ - { - "error": { - "code":400, - "description":"Invalid field present in JSON namee - requestId: 87fb2e32-6287-4e61-8304-9268df12bfe8", - "request_index": 0, - } - } - ] + "httpStatus": "", + "grpcCode": , + "httpCode": , + "message": "", + "requestId": "", + "details": ["
"] } ``` -## Detokenize +# Quickstart + +Get started quickly with the essential steps: authenticate, initialize the client, and perform a basic vault operation. This section provides a minimal setup to help you integrate the SDK efficiently. -To retrieve record data using tokens, use the **detokenize(JSONObject records)** method. TheJSONObject must have a `records` key that takes an JSON array of record objects to fetch: +### Authenticate + +You can use an API key to authenticate and authorize requests to an API. For authenticating via bearer tokens and different supported bearer token types, refer to the [Authenticate with bearer tokens](#authenticate-with-bearer-tokens) section. ```java -JSONObject recordsJson = new JSONObject(); +// create a new credentials object +Credentials credentials = new Credentials(); +credentials.setApiKey(""); // add your API key in credentials +``` -JSONObject recordJson = new JSONObject(); -recordJson.put("token", ""); -recordJson.put("redaction", ); // Optional. Redaction to apply for retrieved data. E.g. RedactionType.DEFAULT.toString() +### Initialize the client -JSONArray recordsArrayJson = new JSONArray(); -recordsArrayJson.put(recordJson); +To get started, you must first initialize the skyflow client. While initializing the skyflow client, you can specify different types of credentials. -recordsJson.put("records", recordsArrayJson); -``` +1. **API keys** + A unique identifier used to authenticate and authorize requests to an API. -Note: `redaction` defaults to [`RedactionType.PLAIN_TEXT`](#redaction-types). +2. **Bearer tokens** + A temporary access token used to authenticate API requests, typically included in the Authorization header. -The following [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/DetokenizeExample.java) code makes a detokenize call to reveal the masked value of a token: +3. **Service account credentials file path** + The file path pointing to a JSON file containing credentials for a service account, used for secure API access. -```java -JSONObject recordsJson = new JSONObject(); +4. **Service account credentials string (JSON formatted)** + A JSON-formatted string containing service account credentials, often used as an alternative to a file for programmatic authentication. -JSONObject validRecordJson = new JSONObject(); -validRecordJson.put("token", "45012507-f72b-4f5c-9bf9-86b133bae719"); -validRecordJson.put("redaction", RedactionType.MASKED.toString()); +Note: Only one type of credential can be used at a time. If multiple credentials are provided, the last one added will take precedence. -JSONObject invalidRecordJson = new JSONObject(); -invalidRecordJson.put("token","invalid-token"); +```java +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; -JSONArray recordsArrayJson = new JSONArray(); -recordsArrayJson.put(validRecordJson); -recordsArrayJson.put(invalidRecordJson); +/** + * Example program to initialize the Skyflow client with various configurations. + * The Skyflow client facilitates secure interactions with the Skyflow vault, + * such as securely managing sensitive data. + */ +public class InitSkyflowClient { + public static void main(String[] args) throws SkyflowException { + // Step 1: Define the primary credentials for authentication. + // Note: Only one type of credential can be used at a time. You can choose between: + // - API key + // - Bearer token + // - A credentials string (JSON-formatted) + // - A file path to a credentials file. + + // Initialize primary credentials using a Bearer token for authentication. + Credentials primaryCredentials = new Credentials(); + primaryCredentials.setToken(""); // Replace with your actual authentication token. + + // Step 2: Configure the primary vault details. + // VaultConfig stores all necessary details to connect to a specific Skyflow vault. + VaultConfig primaryConfig = new VaultConfig(); + primaryConfig.setVaultId(""); // Replace with your primary vault's ID. + primaryConfig.setClusterId(""); // Replace with the cluster ID (part of the vault URL, e.g., https://{clusterId}.vault.skyflowapis.com). + primaryConfig.setEnv(Env.PROD); // Set the environment (PROD, SANDBOX, STAGE, DEV). + primaryConfig.setCredentials(primaryCredentials); // Attach the primary credentials to this vault configuration. + + // Step 3: Create credentials as a JSON object (if a Bearer Token is not provided). + // Demonstrates an alternate approach to authenticate with Skyflow using a credentials object. + JsonObject credentialsObject = new JsonObject(); + credentialsObject.addProperty("clientID", ""); // Replace with your Client ID. + credentialsObject.addProperty("clientName", ""); // Replace with your Client Name. + credentialsObject.addProperty("TokenURI", ""); // Replace with the Token URI. + credentialsObject.addProperty("keyID", ""); // Replace with your Key ID. + credentialsObject.addProperty("privateKey", ""); // Replace with your Private Key. + + // Step 4: Convert the JSON object to a string and use it as credentials. + // This approach allows the use of dynamically generated or pre-configured credentials. + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(credentialsObject.toString()); // Converts JSON object to string for use as credentials. + + // Step 5: Define secondary credentials (API key-based authentication as an example). + // Demonstrates a different type of authentication mechanism for Skyflow vaults. + Credentials secondaryCredentials = new Credentials(); + secondaryCredentials.setApiKey(""); // Replace with your API Key for authentication. + + // Step 6: Configure the secondary vault details. + // A secondary vault configuration can be used for operations involving multiple vaults. + VaultConfig secondaryConfig = new VaultConfig(); + secondaryConfig.setVaultId(""); // Replace with your secondary vault's ID. + secondaryConfig.setClusterId(""); // Replace with the corresponding cluster ID. + secondaryConfig.setEnv(Env.SANDBOX); // Set the environment for this vault. + secondaryConfig.setCredentials(secondaryCredentials); // Attach the secondary credentials to this configuration. + + // Step 7: Define tertiary credentials using a path to a credentials JSON file. + // This method demonstrates an alternative authentication method. + Credentials tertiaryCredentials = new Credentials(); + tertiaryCredentials.setPath(""); // Replace with the path to your credentials file. + + // Step 8: Configure the tertiary vault details. + VaultConfig tertiaryConfig = new VaultConfig(); + tertiaryConfig.setVaultId(""); // Replace with the tertiary vault ID. + tertiaryConfig.setClusterId(""); // Replace with the corresponding cluster ID. + tertiaryConfig.setEnv(Env.STAGE); // Set the environment for this vault. + tertiaryConfig.setCredentials(tertiaryCredentials); // Attach the tertiary credentials. + + // Step 9: Build and initialize the Skyflow client. + // Skyflow client is configured with multiple vaults and credentials. + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.INFO) // Set log level for debugging or monitoring purposes. + .addVaultConfig(primaryConfig) // Add the primary vault configuration. + .addVaultConfig(secondaryConfig) // Add the secondary vault configuration. + .addVaultConfig(tertiaryConfig) // Add the tertiary vault configuration. + .addSkyflowCredentials(skyflowCredentials) // Add JSON-formatted credentials if applicable. + .build(); -recordsJson.put("records", recordsArrayJson); -try { - JSONObject detokenizeResponse = skyflowClient.detokenize(recordsJson); - System.out.println(detokenizeResponse); -} catch (SkyflowExeception exception) { - if (exception.getData() != null) - System.out.println(exception.getData()); - else - System.out.println(exception); -} -``` -The sample response: -```js -{ - "records": [ - { - "token": "45012507-f72b-4f5c-9bf9-86b133bae719", - "value": "j***oe" - } - ], - "errors": [ - { - "token": "invalid-token", - "error": { - "code": 404, - "description": "Tokens not found for invalid-token" - } - } - ] + // The Skyflow client is now fully initialized. + // Use the `skyflowClient` object to perform secure operations such as: + // - Inserting data + // - Retrieving data + // - Deleting data + // within the configured Skyflow vaults. + } } ``` -## Get -In order to retrieve data from your vault using Skyflow IDs or by Unique Column Values, use the **get(JSONObject records, GetOptions options)** method. The `records` parameter takes a JSONObject that should contain -1. Either an array of Skyflow IDs to fetch -2. Or a column name and array of column values - -The second parameter, options, is a GetOptions object that retrieves tokens of Skyflow IDs. +Notes: -Note: -- GetOptions parameter applicable only for retrieving tokens using Skyflow ID. -- You can't pass GetOptions along with the redaction type. -- `tokens` defaults to false. +- If both Skyflow common credentials and individual credentials at the configuration level are specified, the individual credentials at the configuration level will take precedence. +- If neither Skyflow common credentials nor individual configuration-level credentials are provided, the SDK attempts to retrieve credentials from the `SKYFLOW_CREDENTIALS` environment variable. +- All Vault operations require a client instance. +### Insert data into the vault -### Use Skyflow IDs - -1. Retrieve data using Redaction type: +To insert data into your vault, use the `insert` method. The `InsertRequest` class creates an insert request, which includes the values to be inserted as a list of records. Below is a simple example to get started. For advanced options, check out [Insert data into the vault](#insert-data-into-the-vault-1) section. ```java -import com.skyflow.entities.RedactionType; - -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); -JSONObject record = new JSONObject(); -JSONArray ids = new JSONArray(); -ids.add(""); - -record.put("ids", ids); -record.put("table", ""); -record.put("redaction", RedactionType); - -recordsArray.add(record); -records.put("records", recordsArray); -try { - JSONObject getResponse = skyflowClient.get(records); - System.out.println(getResponse); -} catch(SkyflowException exception) { - if (exception.getData() != null) { - System.out.println(exception.getData()); - } else { - System.out.println(exception); +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; + +/** + * This example demonstrates how to insert sensitive data (e.g., card information) into a Skyflow vault using the Skyflow client. + * + * 1. Initializes the Skyflow client. + * 2. Prepares a record with sensitive data (e.g., card number and cardholder name). + * 3. Creates an insert request for inserting the data into the Skyflow vault. + * 4. Prints the response of the insert operation. + */ +public class InsertExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Initialize data to be inserted into the Skyflow vault + ArrayList> insertData = new ArrayList<>(); + + // Create a HashMap for a single record with card number and cardholder name as fields + HashMap insertRecord = new HashMap<>(); + insertRecord.put("card_number", "4111111111111111"); // Replace with actual card number (sensitive data) + insertRecord.put("cardholder_name", "john doe"); // Replace with actual cardholder name (sensitive data) + + // Add the created record to the list of data to be inserted + insertData.add(insertRecord); + + // Step 2: Build the InsertRequest object with the table name and data to insert + InsertRequest insertRequest = InsertRequest.builder() + .table("table1") // Specify the table in the vault where the data will be inserted + .values(insertData) // Attach the data (records) to be inserted + .returnTokens(true) // Specify if tokens should be returned upon successful insertion + .build(); // Build the insert request object + + // Step 3: Perform the insert operation using the Skyflow client + InsertResponse insertResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").insert(insertRequest); + // Replace the vault ID "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + // Step 4: Print the response from the insert operation + System.out.println(insertResponse); + } catch (SkyflowException e) { + // Step 5: Handle any exceptions that may occur during the insert operation + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the stack trace for debugging purposes } -} -``` -2. Retrieve tokens using GetOptions: -```java -import com.skyflow.entities.*; - -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject record = new JSONObject(); -JSONArray ids = new JSONArray(); -ids.add(""); - -record.put("ids", ids); -record.put("table", ""); -record.put("redaction", RedactionType); -recordsArray.add(record); -records.put("records", recordsArray); - -try { - GetOptions options = new GetOptions(true); - JSONObject getResponse = skyflowClient.get(records, options); - System.out.println(getResponse); -} catch(SkyflowException exception) { - if (exception.getData() != null) { - System.out.println(exception.getData()); - } else { - System.out.println(exception); - } + } } ``` -### Use column name and values +Skyflow returns tokens for the record that was just inserted. -```java -import com.skyflow.entities.RedactionType; +```json +{ + "insertedFields": [ + { + "card_number": "5484-7829-1702-9110", + "request_index": "0", + "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", + "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b" + } + ], + "errors": [] +} +``` -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); +# Vault -JSONObject record = new JSONObject(); -JSONArray values = new JSONArray(); -values.add(""); +The [Vault](https://github.com/skyflowapi/skyflow-java/tree/main/samples/src/main/java/com/example/vault) module performs operations on the vault, including inserting records, detokenizing tokens, and retrieving tokens associated with a `skyflow_id`. -record.put("table", ""); -record.put("column_name", ""); -record.put("column_values", ""); -record.put("redaction", RedactionType); -recordsArray.add(record); -records.put("records", recordsArray); -``` +## Insert data into the vault -### Redaction types -There are four accepted values for RedactionType: -* `PLAIN_TEXT` -* `MASKED` -* `REDACTED` -* `DEFAULT` +Apart from using the `insert` method to insert data into your vault covered in [Quickstart](#quickstart), you can also specify options in `InsertRequest`, such as returning tokenized data, upserting records, or continuing the operation in case of errors. -### Examples -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/GetExample.java) call using Skyflow IDs with RedactionType. +### Construct an insert request ```java -import com.skyflow.entities.RedactionType; +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; + +/** + * Example program to demonstrate inserting data into a Skyflow vault, along with corresponding InsertRequest schema. + * + */ +public class InsertSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Prepare the data to be inserted into the Skyflow vault + ArrayList> insertData = new ArrayList<>(); + + // Create the first record with field names and their respective values + HashMap insertRecord1 = new HashMap<>(); + insertRecord1.put("", ""); // Replace with actual field name and value + insertRecord1.put("", ""); // Replace with actual field name and value + + // Create the second record with field names and their respective values + HashMap insertRecord2 = new HashMap<>(); + insertRecord2.put("", ""); // Replace with actual field name and value + insertRecord2.put("", ""); // Replace with actual field name and value + + // Add the records to the list of data to be inserted + insertData.add(insertRecord1); + insertData.add(insertRecord2); + + // Step 2: Build an InsertRequest object with the table name and the data to insert + InsertRequest insertRequest = InsertRequest.builder() + .table("") // Replace with the actual table name in your Skyflow vault + .values(insertData) // Attach the data to be inserted + .build(); + + // Step 3: Use the Skyflow client to perform the insert operation + InsertResponse insertResponse = skyflowClient.vault("").insert(insertRequest); + // Replace with your actual vault ID + + // Print the response from the insert operation + System.out.println("Insert Response: " + insertResponse); + } catch (SkyflowException e) { + // Step 4: Handle any exceptions that occur during the insert operation + System.out.println("Error occurred while inserting data: "); + e.printStackTrace(); // Print the stack trace for debugging + } + } +} +``` -JSONObject recordsJson = new JSONObject(); -JSONArray recordsArrayJson = new JSONArray(); +### Insert call [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/InsertExample.java) with `continueOnError` option -JSONObject validRecord = new JSONObject(); -JSONArray idsJson = new JSONArray(); -idsJson.add("f8d8a622-b557-4c6b-a12c-c5ebe0b0bfd9"); -idsJson.add("da26de53-95d5-4bdb-99db-8d8c66a35ff9"); -validRecord.put("ids", idsJson); -validRecord.put("table", "cards"); -validRecord.put("redaction", Redaction.PLAIN_TEXT.toString()); - -JSONObject invalidRecord = new JSONObject(); -JSONArray invalidIdsJson = new JSONArray(); -invalidIdsJson.add("Invalid Skyflow ID"); - -invalidRecord.put("ids", invalidIdsJson); -invalidRecord.put("table", "cards"); -invalidRecord.put("redaction", Redaction.PLAIN_TEXT.toString()); -recordsArrayJson.add(validRecord); -recordsArrayJson.add(invalidRecord); -recordsJson.put("records", recordsArray); +The `continueOnError` flag is a boolean that determines whether insert operation should proceed despite encountering partial errors. Set to `true` to allow the process to continue even if some errors occur. -try { - JSONObject getResponse = skyflowClient.get(recordsJson); - System.out.println(getResponse); -} catch(SkyflowException exception) { - if (exception.getData() != null) { - System.out.println(exception.getData()); - } else { - System.out.println(exception); +```java +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; + +/** + * This example demonstrates how to insert multiple records into a Skyflow vault using the Skyflow client. + * + * 1. Initializes the Skyflow client. + * 2. Prepares multiple records with sensitive data (e.g., card number and cardholder name). + * 3. Creates an insert request with the records to insert into the Skyflow vault. + * 4. Specifies options to continue on error and return tokens. + * 5. Prints the response of the insert operation. + */ +public class InsertExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Initialize a list to hold the data records to be inserted into the vault + ArrayList> insertData = new ArrayList<>(); + + // Step 2: Create the first record with card number and cardholder name + HashMap insertRecord1 = new HashMap<>(); + insertRecord1.put("card_number", "4111111111111111"); // Replace with actual card number (sensitive data) + insertRecord1.put("cardholder_name", "john doe"); // Replace with actual cardholder name (sensitive data) + + // Step 3: Create the second record with card number and cardholder name + HashMap insertRecord2 = new HashMap<>(); + insertRecord2.put("card_number", "4111111111111111"); // Ensure field name matches ("card_number") + insertRecord2.put("cardholder_name", "jane doe"); // Replace with actual cardholder name (sensitive data) + + // Step 4: Add the records to the insertData list + insertData.add(insertRecord1); + insertData.add(insertRecord2); + + // Step 5: Build the InsertRequest object with the data records to insert + InsertRequest insertRequest = InsertRequest.builder() + .table("table1") // Specify the table in the vault where data will be inserted + .values(insertData) // Attach the data records to be inserted + .returnTokens(true) // Specify if tokens should be returned upon successful insertion + .continueOnError(true) // Specify to continue inserting records even if an error occurs for some records + .build(); // Build the insert request object + + // Step 6: Perform the insert operation using the Skyflow client + InsertResponse insertResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").insert(insertRequest); + // Replace the vault ID "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + // Step 7: Print the response from the insert operation + System.out.println(insertResponse); + } catch (SkyflowException e) { + // Step 8: Handle any exceptions that may occur during the insert operation + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the stack trace for debugging purposes + } } } ``` @@ -811,149 +691,197 @@ Sample response: ```json { - "records": [ - { - "fields": { - "card_number": "4111111111111111", - "cvv": "127", - "expiry_date": "11/35", - "fullname": "myname", - "id": "f8d8a622-b557-4c6b-a12c-c5ebe0b0bfd9" - }, - "table": "cards" - }, + "insertedFields": [ { - "fields": { - "card_number": "4111111111111111", - "cvv": "317", - "expiry_date": "10/23", - "fullname": "sam", - "id": "da26de53-95d5-4bdb-99db-8d8c66a35ff9" - }, - "table": "cards" + "card_number": "5484-7829-1702-9110", + "request_index": "0", + "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", + "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b" } ], "errors": [ { - "error": { - "code": "404", - "description": "No Records Found - requestId: fc531b8d-412e-9775-b945-4feacc9b8616" - }, - "ids": ["Invalid Skyflow ID"] + "request_index": "1", + "error": "Insert failed. Column card_numbe is invalid. Specify a valid column." } ] } ``` -An example call using Skyflow IDs with GetOptions: - -```java -import com.skyflow.entities.*; +### Insert call example with `upsert` option -JSONObject recordsJson = new JSONObject(); -JSONArray recordsArrayJson = new JSONArray(); +An upsert operation checks for a record based on a unique column's value. If a match exists, the record is updated; otherwise, a new record is inserted. + +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.InsertResponse; + +import java.util.ArrayList; +import java.util.HashMap; + +/** + * This example demonstrates how to insert or upsert a record into a Skyflow vault using the Skyflow client, with the option to return tokens. + * + * 1. Initializes the Skyflow client. + * 2. Prepares a record to insert or upsert (e.g., cardholder name). + * 3. Creates an insert request with the data to be inserted or upserted into the Skyflow vault. + * 4. Specifies the field (cardholder_name) for upsert operations. + * 5. Prints the response of the insert or upsert operation. + */ +public class UpsertExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Initialize a list to hold the data records for the insert/upsert operation + ArrayList> upsertData = new ArrayList<>(); + + // Step 2: Create a record with the field 'cardholder_name' to insert or upsert + HashMap upsertRecord = new HashMap<>(); + upsertRecord.put("cardholder_name", "jane doe"); // Replace with the actual cardholder name + + // Step 3: Add the record to the upsertData list + upsertData.add(upsertRecord); + + // Step 4: Build the InsertRequest object with the upsertData + InsertRequest insertRequest = InsertRequest.builder() + .table("table1") // Specify the table in the vault where data will be inserted/upserted + .values(upsertData) // Attach the data records to be inserted/upserted + .returnTokens(true) // Specify if tokens should be returned upon successful operation + .upsert("cardholder_name") // Specify the field to be used for upsert operations (e.g., cardholder_name) + .build(); // Build the insert request object + + // Step 5: Perform the insert/upsert operation using the Skyflow client + InsertResponse insertResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").insert(insertRequest); + // Replace the vault ID "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + // Step 6: Print the response from the insert/upsert operation + System.out.println(insertResponse); + } catch (SkyflowException e) { + // Step 7: Handle any exceptions that may occur during the insert/upsert operation + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the stack trace for debugging purposes + } + } +} +``` + +Skyflow returns tokens, with `upsert` support, for the record you just inserted. -JSONObject validRecord = new JSONObject(); -JSONArray idsJson = new JSONArray(); -idsJson.add("f8d8a622-b557-4c6b-a12c-c5ebe0b0bfd9"); -idsJson.add("da26de53-95d5-4bdb-99db-8d8c66a35ff9"); -validRecord.put("ids", idsJson); -validRecord.put("table", "cards"); - -JSONObject invalidRecord = new JSONObject(); -JSONArray invalidIdsJson = new JSONArray(); -invalidIdsJson.add("Invalid Skyflow ID"); - -invalidRecord.put("ids", invalidIdsJson); -invalidRecord.put("table", "cards"); -recordsArrayJson.add(validRecord); -recordsArrayJson.add(invalidRecord); -recordsJson.put("records", recordsArray); -GetOptions options = new GetOptions(true); -try { - JSONObject getResponse = skyflowClient.get(recordsJson, options); - System.out.println(getResponse); -} catch(SkyflowException exception) { - if (exception.getData() != null) { - System.out.println(exception.getData()); - } else { - System.out.println(exception); - } -} -``` -Sample response: ```json { - "records": [ - { - "fields": { - "card_number": "4555-5176-5936-1930", - "expiry_date": "23396425-93c9-419b-834b-7750b76a34b0", - "fullname": "d6bb7fe5-6b77-4842-b898-221c51c3cc20", - "id": "f8d8a622-b557-4c6b-a12c-c5ebe0b0bfd9" - }, - "table": "cards" - }, + "insertedFields": [ { - "fields": { - "card_number": "8882-7418-2776-6660", - "expiry_date": "284fb1f6-3c29-449f-8899-83a7839821bc", - "fullname": "45a69af3-e22a-4668-9016-08bb2ef2259d", - "id": "da26de53-95d5-4bdb-99db-8d8c66a35ff9" - }, - "table": "cards" + "skyflowId": "9fac9201-7b8a-4446-93f8-5244e1213bd1", + "cardholder_name": "73ce45ce-20fd-490e-9310-c1d4f603ee83" } ], - "errors": [ - { - "error": { - "code": "404", - "description": "No Records Found - requestId: fc531b8d-412e-9775-b945-4feacc9b8616" - }, - "ids": ["Invalid Skyflow ID"] - } - ] + "errors": [] } ``` -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/GetExample.java) call using column names and values. -```java -import com.skyflow.entities.RedactionType; +## Detokenize -JSONObject recordsJson = new JSONObject(); -JSONArray recordsArrayJson = new JSONArray(); +To retrieve tokens from your vault, use the `detokenize` method. The `DetokenizeRequest` class requires a list of detokenization data as input. Additionally, you can provide optional parameters, such as the redaction type and the option to continue on error. + +### Construct a detokenize request + +```java +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.DetokenizeResponse; -JSONObject validRecord = new JSONObject(); -JSONArray valuesJson = new JSONArray(); -valuesJson.add("123455432112345"); -valuesJson.add("123455432112346"); +import java.util.ArrayList; -validRecord.put("table", "account_details"); -validRecord.put("column_name", "bank_account_number"); -validRecord.put("column_values", valuesJson); -validRecord.put("redaction", Redaction.PLAIN_TEXT.toString()); +/** + * This example demonstrates how to detokenize sensitive data from tokens stored in a Skyflow vault, along with corresponding DetokenizeRequest schema. + * + */ +public class DetokenizeSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Initialize a list of tokens to be detokenized (replace with actual tokens) + ArrayList detokenizeData1 = new ArrayList<>(); + DetokenizeData detokenizeDataRecord1 = new DetokenizeData("", RedactionType.PLAIN_TEXT); // Replace with a token to detokenize with PLAIN_TEXT redaction + DetokenizeData detokenizeDataRecord2 = new DetokenizeData("", RedactionType.PLAIN_TEXT); // Replace with another token to detokenize with PLAIN_TEXT redaction + detokenizeData1.add(detokenizeDataRecord1); + detokenizeData1.add(detokenizeDataRecord2); + + // Step 2: Create the DetokenizeRequest object with the tokens and redaction type + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .detokenizeData(detokenizeData1) // Specify detokenize data with specified redaction types + .continueOnError(true) // Continue even if one token cannot be detokenized + .build(); // Build the detokenization request + + // Step 3: Call the Skyflow vault to detokenize the provided tokens + DetokenizeResponse detokenizeResponse = skyflowClient.vault("").detokenize(detokenizeRequest); + // Replace with your actual Skyflow vault ID + + // Step 4: Print the detokenization response, which contains the detokenized data + System.out.println(detokenizeResponse); + } catch (SkyflowException e) { + // Step 5: Handle any errors that occur during the detokenization process + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception for debugging purposes + } + } +} +``` -JSONObject invalidRecord = new JSONObject(); -JSONArray invalidValuesJson = new JSONArray(); -invalidValuesJson.add("Invalid Skyflow column value"); +Notes: -invalidRecord.put("table", "account_details"); -invalidRecord.put("column_name", "bank_account_number"); -invalidRecord.put("column_values", valuesJson); -invalidRecord.put("redaction", Redaction.PLAIN_TEXT.toString()); +- `redactionType` defaults to [`RedactionType.PLAIN_TEXT`](#redaction-types). +- `continueOnError` defaults to `true`. -recordsArrayJson.add(validRecord); -recordsArrayJson.add(invalidRecord); -recordsJson.put("records", recordsArray); +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/DetokenizeExample.java) of a detokenize call: -try { - JSONObject getResponse = skyflowClient.get(recordsJson); - System.out.println(getResponse); -} catch(SkyflowException exception) { - if (exception.getData() != null) { - System.out.println(exception.getData()); - } else { - System.out.println(exception); +```java +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; + +/** + * This example demonstrates how to detokenize sensitive data from tokens stored in a Skyflow vault. + * + * 1. Initializes the Skyflow client. + * 2. Creates a list of tokens (e.g., credit card tokens) that represent the sensitive data. + * 3. Builds a detokenization request using the provided tokens and specifies how the redacted data should be returned. + * 4. Calls the Skyflow vault to detokenize the tokens and retrieves the detokenized data. + * 5. Prints the detokenization response, which contains the detokenized values or errors. + */ +public class DetokenizeExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Initialize a list of tokens to be detokenized (replace with actual token values) + ArrayList detokenizeData1 = new ArrayList<>(); + DetokenizeData detokenizeDataRecord1 = new DetokenizeData("9738-1683-0486-1480", RedactionType.PLAIN_TEXT); // Replace with a token to detokenize with PLAIN_TEXT redaction + DetokenizeData detokenizeDataRecord2 = new DetokenizeData("6184-6357-8409-6668", RedactionType.PLAIN_TEXT); // Replace with another token to detokenize with PLAIN_TEXT redaction + detokenizeData1.add(detokenizeDataRecord1); + detokenizeData1.add(detokenizeDataRecord2); + + // Step 2: Create the DetokenizeRequest object with the tokens and redaction type + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .detokenizeData(detokenizeData1) // Specify detokenize data with specified redaction types + .continueOnError(true) // Continue even if one token cannot be detokenized + .build(); // Build the detokenization request + + // Step 3: Call the Skyflow vault to detokenize the provided tokens + DetokenizeResponse detokenizeResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").detokenize(detokenizeRequest); + // Replace "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + // Step 4: Print the detokenization response, which contains the detokenized data + System.out.println(detokenizeResponse); + } catch (SkyflowException e) { + // Step 5: Handle any errors that occur during the detokenization process + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception for debugging purposes + } } } ``` @@ -962,419 +890,2268 @@ Sample response: ```json { - "records": [ - { - "fields": { - "bank_account_number": "123455432112345", - "pin_code": "123123", - "name": "john doe", - "id": "492c21a1-107f-4d10-ba2c-3482a411827d" - }, - "table": "account_details" - }, - { - "fields": { - "bank_account_number": "123455432112346", - "pin_code": "103113", - "name": "jane doe", - "id": "ac6c6221-bcd1-4265-8fc7-ae7a8fb6dfd5" - }, - "table": "account_details" - } - ], - "errors": [ - { - "columnName": ["bank_account_number"], - "error": { - "code": 404, - "description": "No Records Found - requestId: fc531b8d-412e-9775-b945-4feacc9b8616" - } + "detokenizedFields": [{ + "token": "9738-1683-0486-1480", + "value": "4111111111111115", + "type": "STRING", + }, { + "token": "6184-6357-8409-6668", + "value": "4111111111111119", + "type": "STRING", + }], + "errors": [] +} + +``` + +### An example of a detokenize call with `continueOnError` option: + +```java +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; + +/** + * This example demonstrates how to detokenize sensitive data (e.g., credit card numbers) from tokens in a Skyflow vault. + * + * 1. Initializes the Skyflow client. + * 2. Creates a list of tokens (e.g., credit card tokens) to be detokenized. + * 3. Builds a detokenization request with the tokens and specifies the redaction type for the detokenized data. + * 4. Calls the Skyflow vault to detokenize the tokens and retrieves the detokenized data. + * 5. Prints the detokenization response, which includes the detokenized values or errors. + */ +public class DetokenizeExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Initialize a list of tokens to be detokenized (replace with actual token values) + // Step 1: Initialize a list of tokens to be detokenized (replace with actual token values) + ArrayList detokenizeData1 = new ArrayList<>(); + DetokenizeData detokenizeDataRecord1 = new DetokenizeData("9738-1683-0486-1480", RedactionType.PLAIN_TEXT); // Replace with a token to detokenize with PLAIN_TEXT redaction + DetokenizeData detokenizeDataRecord2 = new DetokenizeData("6184-6357-8409-6668", RedactionType.PLAIN_TEXT); // Replace with another token to detokenize with PLAIN_TEXT redaction + DetokenizeData detokenizeDataRecord2 = new DetokenizeData("4914-9088-2814-384", RedactionType.PLAIN_TEXT); // Replace with another token to detokenize with PLAIN_TEXT redaction + + detokenizeData1.add(detokenizeDataRecord1); + detokenizeData1.add(detokenizeDataRecord2); + + // Step 2: Create the DetokenizeRequest object with the tokens and redaction type + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .detokenizeData(detokenizeData1) // Specify detokenize data with specified redaction types + .continueOnError(true) // Continue even if one token cannot be detokenized + .build(); // Build the detokenization request + + // Step 3: Call the Skyflow vault to detokenize the provided tokens + DetokenizeResponse detokenizeResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").detokenize(detokenizeRequest); + // Replace "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + // Step 4: Print the detokenization response, which contains the detokenized data or errors + System.out.println(detokenizeResponse); + } catch (SkyflowException e) { + // Step 5: Handle any errors that occur during the detokenization process + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception for debugging purposes + } } - ] } ``` -`Note:` -While using detokenize and get methods, there is a possibility that some or all of the tokens might be invalid. In such cases, the data from the response consists of both errors and detokenized records. In the SDK, this will raise a SkyflowException and you can retrieve the data from the Exception object, as shown above. +Sample response: + +```json +{ + "detokenizedFields": [{ + "token": "9738-1683-0486-1480", + "value": "4111111111111115", + "type": "STRING", + }, { + "token": "6184-6357-8409-6668", + "value": "4111111111111119", + "type": "STRING", + }], + "errors": [{ + "token": "4914-9088-2814-384", + "error": "Token Not Found", + }] +} +``` + +## Tokenize + +Tokenization replaces sensitive data with unique identifier tokens. This approach protects sensitive information by securely storing the original data while allowing the use of tokens within your application. -## GetById +To tokenize data, use the `tokenize` method. The `TokenizeRequest` class creates a tokenize request. In this request, you specify the `values` parameter, which is a list of `ColumnValue` objects. Each `ColumnValue` contains two properties: `value` and `columnGroup`. + +### Construct a tokenize request -In order to retrieve data from your vault using SkyflowIDs, use the **getById(JSONObject records)** method. The `records` parameter takes a JSONObject that should contain an array of SkyflowIDs to be fetched, as shown below: ```java -import com.skyflow.entities.RedactionType; +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; + +/** + * This example demonstrates how to tokenize sensitive data (e.g., credit card information) using the Skyflow client, along with corresponding TokenizeRequest schema. + * + */ +public class TokenizeSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Initialize a list of column values to be tokenized (replace with actual sensitive data) + ArrayList columnValues = new ArrayList<>(); + + // Step 2: Create column values for each sensitive data field (e.g., card number and cardholder name) + ColumnValue columnValue1 = ColumnValue.builder().value("").columnGroup("").build(); // Replace and with actual data + ColumnValue columnValue2 = ColumnValue.builder().value("").columnGroup("").build(); // Replace and with actual data -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); + // Add the created column values to the list + columnValues.add(columnValue1); + columnValues.add(columnValue2); -JSONObject record = new JSONObject(); -JSONArray ids = new JSONArray(); -ids.add(""); + // Step 3: Build the TokenizeRequest with the column values + TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); -record.put("ids", ids); -record.put("table", ""); -record.put("redaction", RedactionType); -recordsArray.add(record); -records.put("records", recordsArray); + // Step 4: Call the Skyflow vault to tokenize the sensitive data + TokenizeResponse tokenizeResponse = skyflowClient.vault("").tokenize(tokenizeRequest); + // Replace with your actual Skyflow vault ID + + // Step 5: Print the tokenization response, which contains the generated tokens or errors + System.out.println(tokenizeResponse); + } catch (SkyflowException e) { + // Step 6: Handle any errors that occur during the tokenization process + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception for debugging purposes + } + } +} ``` -There are 4 accepted values in RedactionType: -- `PLAIN_TEXT` -- `MASKED` -- `REDACTED` -- `DEFAULT` -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/GetByIdExample.java) getById call +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/TokenizeExample.java) of Tokenize call: + ```java -import com.skyflow.entities.RedactionType; +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; + +/** + * This example demonstrates how to tokenize sensitive data (e.g., credit card information) using the Skyflow client. + * + * 1. Initializes the Skyflow client. + * 2. Creates a column value for sensitive data (e.g., credit card number). + * 3. Builds a tokenize request with the column value to be tokenized. + * 4. Sends the request to the Skyflow vault for tokenization. + * 5. Prints the tokenization response, which includes the token or errors. + */ +public class TokenizeExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Initialize a list of column values to be tokenized (replace with actual sensitive data) + ArrayList columnValues = new ArrayList<>(); -JSONObject recordsJson = new JSONObject(); -JSONArray recordsArrayJson = new JSONArray(); + // Step 2: Create a column value for the sensitive data (e.g., card number with its column group) + ColumnValue columnValue = ColumnValue.builder() + .value("4111111111111111") // Replace with the actual sensitive data (e.g., card number) + .columnGroup("card_number_cg") // Replace with the actual column group name + .build(); -JSONObject validRecord = new JSONObject(); -JSONArray idsJson = new JSONArray(); -idsJson.add("f8d8a622-b557-4c6b-a12c-c5ebe0b0bfd9"); -idsJson.add("da26de53-95d5-4bdb-99db-8d8c66a35ff9"); -validRecord.put("ids",idsJson); -validRecord.put("table","cards"); -validRecord.put("redaction",Redaction.PLAIN_TEXT.toString()); - -JSONObject invalidRecord = new JSONObject(); -JSONArray invalidIdsJson = new JSONArray(); -invalidIdsJson.add("invalid skyflow ID"); - -invalidRecord.put("ids",invalidIdsJson); -invalidRecord.put("table","cards"); -invalidRecord.put("redaction",Redaction.PLAIN_TEXT.toString()); -recordsArrayJson.add(validRecord); -recordsArrayJson.add(invalidRecord); -recordsJson.put("records", recordsArrayJson); + // Add the created column value to the list + columnValues.add(columnValue); + + // Step 3: Build the TokenizeRequest with the column value + TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); -try{ - JSONObject getByIdResponse = skyflowClient.getById(recordsJson); - System.out.println(getByIdResponse); -}catch(SkyflowException exception){ - if(exception.getData() != null) - System.out.println(exception.getData()); - else - System.out.println(exception); + // Step 4: Call the Skyflow vault to tokenize the sensitive data + TokenizeResponse tokenizeResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").tokenize(tokenizeRequest); + // Replace "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID + + // Step 5: Print the tokenization response, which contains the generated token or any errors + System.out.println(tokenizeResponse); + } catch (SkyflowException e) { + // Step 6: Handle any errors that occur during the tokenization process + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception for debugging purposes + } + } } ``` -Sample getById response -```js + +Sample response: + +```json { - "records": [ - { - "fields": { - "card_number": "4111111111111111", - "cvv": "127", - "expiry_date": "11/35", - "fullname": "myname", - "id": "f8d8a622-b557-4c6b-a12c-c5ebe0b0bfd9" - }, - "table": "cards" - }, - { - "fields": { - "card_number": "4111111111111111", - "cvv": "317", - "expiry_date": "10/23", - "fullname": "sam", - "id": "da26de53-95d5-4bdb-99db-8d8c66a35ff9" - }, - "table": "cards" - } - ], - "errors": [ - { - "error": { - "code": "404", - "description": "No Records Found" - }, - "ids": ["invalid skyflow id"] - } - ] + "tokens": [5479-4229-4622-1393] } ``` -`Note:` While using detokenize and getByID methods, there is a possibility that some or all of the tokens might be invalid. In such cases, the data from response consists of both errors and detokenized records. In the SDK, this will raise a SkyflowException and you can retrieve the data from this Exception object as shown above. -## Update +## Get + +To retrieve data using Skyflow IDs or unique column values, use the `get` method. The `GetRequest` class creates a get request, where you specify parameters such as the table name, redaction type, Skyflow IDs, column names, column values, and whether to return tokens. If you specify Skyflow IDs, you can't use column names and column values, and the inverse is true—if you specify column names and column values, you can't use Skyflow IDs. + +### Construct a get request -In order to update the records in your vault by **skyflow_id**, use the **update(records, options)** method. The first parameter, `records`, is a JSONObject that must have a records key and takes an array of records to update as a value in the vault. The options parameter takes an object of update options and includes an option to return tokens for the updated fields as shown below: ```java -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.GetRequest; +import com.skyflow.vault.data.GetResponse; -JSONObject record = new JSONObject(); -record.put("table", ""); -record.put("id",""); +import java.util.ArrayList; -JSONObject fields = new JSONObject(); -fields.put("", ""); -record.put("fields", fields); -recordsArray.add(record); -records.put("records", recordsArray); -UpdateOptions updateOptions = new UpdateOptions(true); +/** + * This example demonstrates how to retrieve data from the Skyflow vault using different methods, along with corresponding GetRequest schema. + * + */ +public class GetSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Initialize a list of Skyflow IDs to retrieve records (replace with actual Skyflow IDs) + ArrayList ids = new ArrayList<>(); + ids.add(""); // Replace with actual Skyflow ID + ids.add(""); // Replace with actual Skyflow ID + + // Step 2: Create a GetRequest to retrieve records by Skyflow ID without returning tokens + GetRequest getByIdRequest = GetRequest.builder() + .ids(ids) + .table("") // Replace with the actual table name + .returnTokens(false) // Set to false to avoid returning tokens + .redactionType(RedactionType.PLAIN_TEXT) // Redact data as plain text + .build(); + + // Send the request to the Skyflow vault and retrieve the records + GetResponse getByIdResponse = skyflowClient.vault("").get(getByIdRequest); // Replace with actual Vault ID + System.out.println(getByIdResponse); + + // Step 3: Create another GetRequest to retrieve records by Skyflow ID with tokenized values + GetRequest getTokensRequest = GetRequest.builder() + .ids(ids) + .table("") // Replace with the actual table name + .returnTokens(true) // Set to true to return tokenized values + .build(); + + // Send the request to the Skyflow vault and retrieve the tokenized records + GetResponse getTokensResponse = skyflowClient.vault("").get(getTokensRequest); // Replace with actual Vault ID + System.out.println(getTokensResponse); + + // Step 4: Create a GetRequest to retrieve records based on specific column values + ArrayList columnValues = new ArrayList<>(); + columnValues.add(""); // Replace with the actual column value + columnValues.add(""); // Replace with the actual column value + + GetRequest getByColumnRequest = GetRequest.builder() + .table("") // Replace with the actual table name + .columnName("") // Replace with the column name + .columnValues(columnValues) // Add the list of column values to filter by + .redactionType(RedactionType.PLAIN_TEXT) // Redact data as plain text + .build(); + + // Send the request to the Skyflow vault and retrieve the records filtered by column values + GetResponse getByColumnResponse = skyflowClient.vault("").get(getByColumnRequest); // Replace with actual Vault ID + System.out.println(getByColumnResponse); + } catch (SkyflowException e) { + // Step 5: Handle any errors that occur during the retrieval process + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception for debugging purposes + } + } +} ``` -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/UpdateExample.java) of update call: +### Get by skyflow IDs + +Retrieve specific records using `skyflow_ids`. Ideal for fetching exact records when IDs are known. + +#### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/GetExample.java) of a get call to retrieve data using Redaction type: + ```java -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); - -JSONObject record = new JSONObject(); -record.put("table", "cards"); -record.put("id","29ebda8d-5272-4063-af58-15cc674e332b"); - -JSONObject fields = new JSONObject(); -fields.put("card_number", "5105105105105100"); -fields.put("cardholder_name", "Thomas"); -fields.put("expiration_date", "07/2032"); -record.put("fields", fields); -recordsArray.add(record); -records.put("records", recordsArray); -UpdateOptions updateOptions = new UpdateOptions(true); +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; + +/** + * This example demonstrates how to retrieve data from the Skyflow vault using a list of Skyflow IDs. + * + * 1. Initializes the Skyflow client with a given vault ID. + * 2. Creates a request to retrieve records based on Skyflow IDs. + * 3. Specifies that the response should not return tokens. + * 4. Uses plain text redaction type for the retrieved records. + * 5. Prints the response to display the retrieved records. + */ +public class GetExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Initialize a list of Skyflow IDs (replace with actual Skyflow IDs) + ArrayList ids = new ArrayList<>(); + ids.add("a581d205-1969-4350-acbe-a2a13eb871a6"); // Replace with actual Skyflow ID + ids.add("5ff887c3-b334-4294-9acc-70e78ae5164a"); // Replace with actual Skyflow ID + + // Step 2: Create a GetRequest to retrieve records based on Skyflow IDs + // The request specifies: + // - `ids`: The list of Skyflow IDs to retrieve + // - `table`: The table from which the records will be retrieved + // - `returnTokens`: Set to false, meaning tokens will not be returned in the response + // - `redactionType`: Set to PLAIN_TEXT, meaning the retrieved records will have data redacted as plain text + GetRequest getByIdRequest = GetRequest.builder() + .ids(ids) + .table("table1") // Replace with the actual table name + .returnTokens(false) // Set to false to avoid returning tokens + .redactionType(RedactionType.PLAIN_TEXT) // Redact data as plain text + .build(); + + // Step 3: Send the request to the Skyflow vault and retrieve the records + GetResponse getByIdResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").get(getByIdRequest); // Replace with actual Vault ID + System.out.println(getByIdResponse); // Print the response to the console -try { - JSONObject response = skyflowClient.update(records, updateOptions); -} -catch (SkyflowException e) { - e.printStackTrace(); + } catch (SkyflowException e) { + // Step 4: Handle any errors that occur during the data retrieval process + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception for debugging purposes + } + } } ``` -Response: -```java + +Sample response: + +```json { - "records": [ - { - "id": "29ebda8d-5272-4063-af58-15cc674e332b", - "fields": { - "card_number": "93f28226-51b0-4f24-8151-78b5a61f028b", - "cardholder_name": "0838fd08-9b51-4db2-893c-48542f3b121e", - "expiration_date": "91d7ee77-262f-4d5d-8286-062b694c81fd", - }, - "table": "cards" - } - ] + "data": [ + { + "card_number": "4555555555555553", + "email": "john.doe@gmail.com", + "name": "john doe", + "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6" + }, + { + "card_number": "4555555555555559", + "email": "jane.doe@gmail.com", + "name": "jane doe", + "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a" + } + ], + "errors": [] } ``` -## Delete -To delete data from the vault, use the `delete(records, options?)` method of the Skyflow client. The `records` parameter takes an array of records to delete in the following format. The `options` parameter is optional and takes an object of deletion parameters. Currently, there are no supported deletion parameters. +### Get tokens -Call schema: +Return tokens for records. Ideal for securely processing sensitive data while maintaining data privacy. + +#### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/getExample.java) of get call to retrieve tokens using Skyflow IDs: ```java -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); +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; + +/** + * This example demonstrates how to retrieve data from the Skyflow vault and return tokens along with the records. + * + * 1. Initializes the Skyflow client with a given vault ID. + * 2. Creates a request to retrieve records based on Skyflow IDs and ensures tokens are returned. + * 3. Prints the response to display the retrieved records along with the tokens. + */ +public class GetExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Initialize a list of Skyflow IDs (replace with actual Skyflow IDs) + ArrayList ids = new ArrayList<>(); + ids.add("a581d205-1969-4350-acbe-a2a13eb871a6"); // Replace with actual Skyflow ID + ids.add("5ff887c3-b334-4294-9acc-70e78ae5164a"); // Replace with actual Skyflow ID + + // Step 2: Create a GetRequest to retrieve records based on Skyflow IDs + // The request specifies: + // - `ids`: The list of Skyflow IDs to retrieve + // - `table`: The table from which the records will be retrieved + // - `returnTokens`: Set to true, meaning tokens will be included in the response + GetRequest getTokensRequest = GetRequest.builder() + .ids(ids) + .table("table1") // Replace with the actual table name + .returnTokens(true) // Set to true to include tokens in the response + .build(); + + // Step 3: Send the request to the Skyflow vault and retrieve the records with tokens + GetResponse getTokensResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").get(getTokensRequest); // Replace with actual Vault ID + System.out.println(getTokensResponse); // Print the response to the console -JSONObject record = new JSONObject(); + } catch (SkyflowException e) { + // Step 4: Handle any errors that occur during the data retrieval process + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception for debugging purposes + } + } +} +``` -record.put("id", ""); -record.put("table", ""); -recordsArray.add(record); -records.put("records", recordsArray); +Sample response: -skyflowClient.delete(records); +```json +{ + "data": [ + { + "card_number": "3998-2139-0328-0697", + "email": "c9a6c9555060@82c092e7.bd52", + "name": "82c092e7-74c0-4e60-bd52-c9a6c9555060", + "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6" + }, + { + "card_number": "3562-0140-8820-7499", + "email": "6174366e2bc6@59f82e89.93fc", + "name": "59f82e89-138e-4f9b-93fc-6174366e2bc6", + "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a" + } + ], + "errors": [] +} ``` -An example of delete call: -```java -JSONObject records = new JSONObject(); -JSONArray recordsArray = new JSONArray(); +### Get By column name and column values -JSONObject record = new JSONObject(); -record.put("id", "71be4592-b9af-4dec-8669-5b9c926afb4c"); -record.put("table", "cards"); -recordsArray.add(record); - -JSONObject record2 = new JSONObject(); -record2.put("id", "2adf32e7-9a04-408e-b8bb-5b0a852422e0"); -record2.put("table", "cards"); -recordsArray.add(record2); +Retrieve records by unique column values. Ideal for querying data without knowing Skyflow IDs, using alternate unique identifiers. -records.put("records", recordsArray); +#### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/GetExample.java) of get call to retrieve data using column name and column values: -try { - JSONObject response = skyflowClient.delete(records); -} catch (SkyflowException e) { - e.printStackTrace(); - System.out.println("error"+ e.getData()); +```java +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; + +/** + * This example demonstrates how to retrieve data from the Skyflow vault based on column values. + * + * 1. Initializes the Skyflow client with a given vault ID. + * 2. Creates a request to retrieve records based on specific column values (e.g., email addresses). + * 3. Prints the response to display the retrieved records after redacting sensitive data based on the specified redaction type. + */ +public class GetExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Initialize a list of column values (email addresses in this case) + ArrayList columnValues = new ArrayList<>(); + columnValues.add("john.doe@gmail.com"); // Example email address + columnValues.add("jane.doe@gmail.com"); // Example email address + + // Step 2: Create a GetRequest to retrieve records based on column values + // The request specifies: + // - `table`: The table from which the records will be retrieved + // - `columnName`: The column to filter the records by (e.g., "email") + // - `columnValues`: The list of values to match in the specified column + // - `redactionType`: Defines how sensitive data should be redacted (set to PLAIN_TEXT here) + GetRequest getByColumnRequest = GetRequest.builder() + .table("table1") // Replace with the actual table name + .columnName("email") // The column name to filter by (e.g., "email") + .columnValues(columnValues) // The list of column values to match + .redactionType(RedactionType.PLAIN_TEXT) // Set the redaction type (e.g., PLAIN_TEXT) + .build(); + + // Step 3: Send the request to the Skyflow vault and retrieve the records + GetResponse getByColumnResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").get(getByColumnRequest); // Replace with actual Vault ID + System.out.println(getByColumnResponse); // Print the response to the console + + } catch (SkyflowException e) { + // Step 4: Handle any errors that occur during the data retrieval process + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception for debugging purposes + } + } } ``` -Response: + +Sample response: + ```json { - "records": [ + "data": [ { - "skyflow_id": "71be4592-b9af-4dec-8669-5b9c926afb4c", - "deleted": true, + "card_number": "4555555555555553", + "email": "john.doe@gmail.com", + "name": "john doe", + "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6" }, { - "skyflow_id": "2adf32e7-9a04-408e-b8bb-5b0a852422e0", - "deleted": true, + "card_number": "4555555555555559", + "email": "jane.doe@gmail.com", + "name": "jane doe", + "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a" } - ] + ], + "errors": [] } ``` -## Invoke Connection +### Redaction types -Using the InvokeConnection method, you can integrate their server-side application with third party APIs and services without directly handling sensitive data. Prior to invoking the `InvokeConnection` method, you must have created a connection and have a connectionURL already generated. Once you have the connectionURL, you can invoke a connection by using the **invokeConnection(JSONObject config)** method. The JSONObject config parameter must include a `connectionURL` and `methodName`. The other fields are optional. -```java -JSONObject invokeConfig = new JSONObject(); -// connection url received when creating a skyflow connection integration -invokeConfig.put("connectionURL", ""); -invokeConfig.put("methodName", RequestMethod); +Redaction types determine how sensitive data is displayed when retrieved from the vault. -JSONObject pathParamsJson = new JSONObject(); -pathParamsJson.put("", ""); -invokeConfig.put("pathParams", pathParamsJson); +#### **Available Redaction Types** -JSONObject queryParamsJson = new JSONObject(); -queryParamsJson.put("", ""); -invokeConfig.put("queryParams", queryParamsJson); +- `DEFAULT`: Applies the vault-configured default redaction setting. +- `REDACTED`: Completely removes sensitive data from view. +- `MASKED`: Partially obscures sensitive information. +- `PLAIN_TEXT`: Displays the full, unmasked data. -JSONObject requestHeadersJson = new JSONObject(); -requestHeadersJson.put("", ""); -invokeConfig.put("requestHeader", requestHeadersJson); +#### **Choosing the Right Redaction Type** -JSONObject requestBodyJson = new JSONObject(); -requestBodyJson.put("", ""); -invokeConfig.put("requestBody", requestBodyJson); -``` +- Use `REDACTED` for scenarios requiring maximum data protection to prevent exposure of sensitive information. +- Use `MASKED` to provide partial visibility of sensitive data for less critical use cases. +- Use `PLAIN_TEXT` for internal, authorized access where full data visibility is necessary. -`methodName` supports the following methods: -- GET -- POST -- PUT -- PATCH -- DELETE +## Update +To update data in your vault, use the `update` method. The `UpdateRequest` class is used to create an update request, +where you specify parameters such as the table name, data (as a map of key value pairs), tokens, returnTokens, and +tokenStrict. If `returnTokens` is set to `true`, Skyflow returns tokens for the updated records. If `returnTokens` is +set to `false`, Skyflow returns IDs for the updated records. -**pathParams, queryParams, requestHeader, requestBody** are the JSON objects that will be sent through the connection integration url. +### Construct an update request -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/InvokeConnectionExample.java) of invokeConnection: ```java -JSONObject invokeConfig = new JSONObject(); -invokeConfig.put("connectionURL", ""); -invokeConfig.put("methodName", RequestMethod.POST); +import com.skyflow.enums.TokenMode; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.UpdateRequest; +import com.skyflow.vault.data.UpdateResponse; -JSONObject requestHeaderJson = new JSONObject(); -requestHeaderJson.put("Content-Type","application/json"); -requestHeaderJson.put("Authorization",""); +import java.util.HashMap; -invokeConfig.put("requestHeader",requestHeaderJson); +/** + * This example demonstrates how to update records in the Skyflow vault by providing new data and/or tokenized values, along with corresponding UpdateRequest schema. + * + */ +public class UpdateSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Prepare the data to update in the vault + // Use a HashMap to store the data that will be updated in the specified table + HashMap data = new HashMap<>(); + data.put("skyflow_id", ""); // Skyflow ID for identifying the record to update + data.put("", ""); // Example of a column name and its value to update + data.put("", ""); // Another example of a column name and its value to update + + // Step 2: Prepare the tokens (if necessary) for certain columns that require tokenization + // Use a HashMap to specify columns that need tokens in the update request + HashMap tokens = new HashMap<>(); + tokens.put("", ""); // Example of a column name that should be tokenized + + // Step 3: Create an UpdateRequest to specify the update operation + // The request includes the table name, token mode, data, tokens, and the returnTokens flag + UpdateRequest updateRequest = UpdateRequest.builder() + .table("") // Replace with the actual table name to update + .tokenMode(TokenMode.ENABLE) // Specifies the tokenization mode (ENABLE means tokenization is applied) + .data(data) // The data to update in the record + .tokens(tokens) // The tokens associated with specific columns + .returnTokens(true) // Specify whether to return tokens in the response + .build(); + + // Step 4: Send the request to the Skyflow vault and update the record + UpdateResponse updateResponse = skyflowClient.vault("").update(updateRequest); // Replace with actual Vault ID + System.out.println(updateResponse); // Print the response to confirm the update result -JSONObject requestBodyJson = new JSONObject(); -requestBodyJson.put("expirationDate","12/2026"); -invokeConfig.put("requestBody",requestBodyJson); + } catch (SkyflowException e) { + // Step 5: Handle any errors that occur during the update operation + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception for debugging purposes + } + } +} +``` -JSONObject pathParamsJson = new JSONObject(); -pathParamsJson.put("card_number","1852-344-234-34251"); -invokeConfig.put("pathParams",pathParamsJson); +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/UpdateExample.java) of update call -try{ - JSONObject invokeConnectionResponse = skyflow.invokeConnection(invokeConfig); - System.out.println(invokeResponse) -}catch(SkyflowException exception){ - System.out.println(exception); +```java +import com.skyflow.enums.TokenMode; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.UpdateRequest; +import com.skyflow.vault.data.UpdateResponse; + +import java.util.HashMap; + +/** + * This example demonstrates how to update a record in the Skyflow vault with specified data and tokens. + * + * 1. Initializes the Skyflow client with a given vault ID. + * 2. Constructs an update request with data to modify and tokens to include. + * 3. Sends the request to update the record in the vault. + * 4. Prints the response to confirm the success or failure of the update operation. + */ +public class UpdateExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Prepare the data to update in the vault + // A HashMap is used to store the data that will be updated in the specified table + HashMap data = new HashMap<>(); + data.put("skyflow_id", "5b699e2c-4301-4f9f-bcff-0a8fd3057413"); // Skyflow ID identifies the record to update + data.put("name", "john doe"); // Updating the "name" column with a new value + data.put("card_number", "4111111111111115"); // Updating the "card_number" column with a new value + + // Step 2: Prepare the tokens to include in the update request + // Tokens can be included to update sensitive data with tokenized values + HashMap tokens = new HashMap<>(); + tokens.put("name", "72b8ffe3-c8d3-4b4f-8052-38b2a7405b5a"); // Tokenized value for the "name" column + + // Step 3: Create an UpdateRequest to define the update operation + // The request specifies the table name, token mode, data, and tokens for the update + UpdateRequest updateRequest = UpdateRequest.builder() + .table("table1") // Replace with the actual table name to update + .tokenMode(TokenMode.ENABLE) // Token mode enabled to allow tokenization of sensitive data + .data(data) // The data to update in the record + .tokens(tokens) // The tokenized values for sensitive columns + .build(); + + // Step 4: Send the update request to the Skyflow vault + UpdateResponse updateResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").update(updateRequest); // Replace with your actual Vault ID + System.out.println(updateResponse); // Print the response to confirm the update result + + } catch (SkyflowException e) { + // Step 5: Handle any exceptions that occur during the update operation + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception stack trace for debugging purposes + } + } } +``` + +Sample response: + +- When `returnTokens` is set to `true` +```json +{ + "skyflowId": "5b699e2c-4301-4f9f-bcff-0a8fd3057413", + "name": "72b8ffe3-c8d3-4b4f-8052-38b2a7405b5a", + "card_number": "4315-7650-1359-9681" +} ``` -Sample invokeConnection Response -```js + +- When `returnTokens` is set to `false` + +```json { - "receivedTimestamp": "2021-11-05 13:43:12.534", - "processingTimeinMs": 12, - "resource": { - "cvv2": "558" - } + "skyflowId": "5b699e2c-4301-4f9f-bcff-0a8fd3057413" } ``` -### Query +## Delete + +To delete records using Skyflow IDs, use the `delete` method. The `DeleteRequest` class accepts a list of Skyflow IDs +that you want to delete, as shown below: -To retrieve data with SQL queries, use the `query(queryInput, options)` method. `queryInput` is an object that takes the `query` parameter as follows: +### Construct a delete request ```java -JSONObject queryInput = new JSONObject(); -queryInput.put("query", ""); -skyflowClient.query(queryInput); +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.DeleteRequest; +import com.skyflow.vault.data.DeleteResponse; + +import java.util.ArrayList; + +/** + * This example demonstrates how to delete records from a Skyflow vault using specified Skyflow IDs, along with corresponding DeleteRequest schema. + * + */ +public class DeleteSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Prepare a list of Skyflow IDs for the records to delete + // The list stores the Skyflow IDs of the records that need to be deleted from the vault + ArrayList ids = new ArrayList<>(); + ids.add(""); // Replace with actual Skyflow ID 1 + ids.add(""); // Replace with actual Skyflow ID 2 + ids.add(""); // Replace with actual Skyflow ID 3 + + // Step 2: Create a DeleteRequest to define the delete operation + // The request specifies the table from which to delete the records and the IDs of the records to delete + DeleteRequest deleteRequest = DeleteRequest.builder() + .ids(ids) // List of Skyflow IDs to delete + .table("") // Replace with the actual table name from which to delete + .build(); + + // Step 3: Send the delete request to the Skyflow vault + DeleteResponse deleteResponse = skyflowClient.vault("").delete(deleteRequest); // Replace with your actual Vault ID + System.out.println(deleteResponse); // Print the response to confirm the delete result + + } catch (SkyflowException e) { + // Step 4: Handle any exceptions that occur during the delete operation + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception stack trace for debugging purposes + } + } +} ``` -See [Query your data](https://docs.skyflow.com/query-data/) and [Execute Query](https://docs.skyflow.com/record/#QueryService_ExecuteQuery) for guidelines and restrictions on supported SQL statements, operators, and keywords. -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/QueryExample.java) of query call: +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/DeleteExample.java) of delete call: + ```java -JSONObject queryInput = new JSONObject(); -queryInput.put("query", "SELECT * FROM cards WHERE skyflow_id='3ea3861-x107-40w8-la98-106sp08ea83f'"); +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.DeleteRequest; +import com.skyflow.vault.data.DeleteResponse; + +import java.util.ArrayList; + +/** + * This example demonstrates how to delete records from a Skyflow vault using specified Skyflow IDs. + * + * 1. Initializes the Skyflow client with a given Vault ID. + * 2. Constructs a delete request by specifying the IDs of the records to delete. + * 3. Sends the delete request to the Skyflow vault to delete the specified records. + * 4. Prints the response to confirm the success or failure of the delete operation. + */ +public class DeleteExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Prepare a list of Skyflow IDs for the records to delete + // The list stores the Skyflow IDs of the records that need to be deleted from the vault + ArrayList ids = new ArrayList<>(); + ids.add("9cbf66df-6357-48f3-b77b-0f1acbb69280"); // Replace with actual Skyflow ID 1 + ids.add("ea74bef4-f27e-46fe-b6a0-a28e91b4477b"); // Replace with actual Skyflow ID 2 + ids.add("47700796-6d3b-4b54-9153-3973e281cafb"); // Replace with actual Skyflow ID 3 + + // Step 2: Create a DeleteRequest to define the delete operation + // The request specifies the table from which to delete the records and the IDs of the records to delete + DeleteRequest deleteRequest = DeleteRequest.builder() + .ids(ids) // List of Skyflow IDs to delete + .table("table1") // Replace with the actual table name from which to delete + .build(); + + // Step 3: Send the delete request to the Skyflow vault + DeleteResponse deleteResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").delete(deleteRequest); // Replace with your actual Vault ID + System.out.println(deleteResponse); // Print the response to confirm the delete result -try { - JSONObject res = skyflowClient.query(queryInput); -} catch (SkyflowException e) { - System.out.println(e.getData()); - e.printStackTrace(); + } catch (SkyflowException e) { + // Step 4: Handle any exceptions that occur during the delete operation + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception stack trace for debugging purposes + } + } } ``` -Sample Response -```java +Sample response: + +```json { - "records": [ - { - "fields": { - "card_number": "XXXXXXXXXXXX1111", - "card_pin": "*REDACTED*", - "cvv": "", - "expiration_date": "*REDACTED*", - "expiration_month": "*REDACTED*", - "expiration_year": "*REDACTED*", - "name": "a***te", - "skyflow_id": "3ea3861-x107-40w8-la98-106sp08ea83f", - "ssn": "XXX-XX-6789", - "zip_code": null - }, - "tokens": null - } + "deletedIds": [ + "9cbf66df-6357-48f3-b77b-0f1acbb69280", + "ea74bef4-f27e-46fe-b6a0-a28e91b4477b", + "47700796-6d3b-4b54-9153-3973e281cafb" ] } ``` -## Logging -The skyflow-java SDK provides useful logging using java inbuilt `java.util.logging`. By default the logging level of the SDK is set to `LogLevel.ERROR`. This can be changed by using `setLogLevel(LogLevel)` as shown below: +## Query + +To retrieve data with SQL queries, use the `query` method. The `QueryRequest` class accepts a `query` parameter, as shown below. + +### Construct a query request + +Refer to [Query your data](https://docs.skyflow.com/query-data/) and [Execute Query](https://docs.skyflow.com/record/#QueryService_ExecuteQuery) for guidelines and restrictions on supported SQL statements, operators, and keywords. ```java -import com.skyflow.entities.LogLevel; -import com.skyflow.Configuration; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.QueryRequest; +import com.skyflow.vault.data.QueryResponse; + +/** + * This example demonstrates how to execute a custom SQL query on a Skyflow vault, along with QueryRequest schema. + * + */ +public class QuerySchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Define the SQL query to execute on the Skyflow vault + // Replace "" with the actual SQL query you want to run + String query = ""; // Example: "SELECT * FROM table1 WHERE column1 = 'value'" -// sets the skyflow-java SDK log level to INFO -Configuration.setLogLevel(LogLevel.INFO); -``` + // Step 2: Create a QueryRequest with the specified SQL query + QueryRequest queryRequest = QueryRequest.builder() + .query(query) // SQL query to execute + .build(); + + // Step 3: Execute the query request on the specified Skyflow vault + QueryResponse queryResponse = skyflowClient.vault("").query(queryRequest); // Replace with your actual Vault ID + System.out.println(queryResponse); // Print the response containing the query results -Current the following 5 log levels are supported: + } catch (SkyflowException e) { + // Step 4: Handle any exceptions that occur during the query execution + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception stack trace for debugging + } + } +} +``` -- `DEBUG`: +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/QueryExample.java) of query call - When `LogLevel.DEBUG` is passed, all level of logs will be printed(DEBUG, INFO, WARN, ERROR) - -- `INFO`: +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.QueryRequest; +import com.skyflow.vault.data.QueryResponse; + +/** + * This example demonstrates how to execute a SQL query on a Skyflow vault to retrieve data. + * + * 1. Initializes the Skyflow client with the Vault ID. + * 2. Constructs a query request with a specified SQL query. + * 3. Executes the query against the Skyflow vault. + * 4. Prints the response from the query execution. + */ +public class QueryExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Define the SQL query + // Example query: Retrieve all records from the "cards" table with a specific skyflow_id + String query = "SELECT * FROM cards WHERE skyflow_id='3ea3861-x107-40w8-la98-106sp08ea83f'"; - When `LogLevel.INFO` is passed, INFO logs for every event that has occurred during the SDK flow execution will be printed along with WARN and ERROR logs - -- `WARN`: + // Step 2: Create a QueryRequest with the SQL query + QueryRequest queryRequest = QueryRequest.builder() + .query(query) // SQL query to execute + .build(); - When `LogLevel.WARN` is passed, WARN and ERROR logs will be printed - -- `ERROR`: + // Step 3: Execute the query request on the specified Skyflow vault + QueryResponse queryResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").query(queryRequest); // Vault ID: 9f27764a10f7946fe56b3258e117 + System.out.println(queryResponse); // Print the query response (contains query results) - When `LogLevel.ERROR` is passed, only ERROR logs will be printed. - -- `OFF`: + } catch (SkyflowException e) { + // Step 4: Handle any exceptions that occur during the query execution + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception stack trace for debugging + } + } +} +``` - `LogLevel.OFF` can be used to turn off all logging from the skyflow-java SDK. - +Sample response: -`Note`: - - The ranking of logging levels is as follows : `DEBUG` < `INFO` < `WARN` < `ERROR`. +```json +{ + "fields": [ + { + "card_number": "XXXXXXXXXXXX1112", + "name": "S***ar", + "skyflow_id": "3ea3861-x107-40w8-la98-106sp08ea83f", + "tokenizedData": null + } + ] +} +``` + +## Upload File + +To upload files to a Skyflow vault, use the `uploadFile` method. The `UploadFileRequest` class accepts parameters such as the file path, table name, and file name. + +### Construct a file upload request + +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.FileUploadRequest; +import com.skyflow.vault.data.FileUploadResponse; + +/** + * This example demonstrates how to upload a file to a Skyflow vault, along with the UploadFileRequest schema. + * + */ +public class UploadFileSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Specify file Object + File file = new File(""); + + // Step 2: Create an UploadFileRequest with the file details + FileUploadRequest uploadFileRequest = FileUploadRequest.builder() + .fileObject(file) // File object + .table("") // Vault table to upload into + .columnName("") // Column to assign to the uploaded file + .skyflowId("") // Skyflow id of the record + .build(); + + // Step 3: Execute the file upload request on the specified Skyflow vault + FileUploadResponse fileUploadResponse = skyflowClient.vault().uploadFile(uploadFileRequest); + System.out.println("File Upload Response: " + fileUploadResponse); + + } catch (SkyflowException e) { + // Step 4: Handle any exceptions that occur during the upload + System.out.println("Error occurred during file upload:"); + e.printStackTrace(); // Print the exception stack trace for debugging + } + } +} + +``` + +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/FileUploadExample.java) of file upload call +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.FileUploadRequest; +import com.skyflow.vault.data.FileUploadResponse; + +/** + * This example demonstrates how to upload a file to a Skyflow vault. + * + * 1. Initializes the Skyflow client with the Vault ID. + * 2. Constructs a file upload request with the file path, table name, and file name. + * 3. Executes the upload request against the Skyflow vault. + * 4. Prints the response from the upload. + */ +public class UploadFileExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Specify file Object + File file = new File("test/sample.txt"); + + // Step 2: Create an UploadFileRequest with the file details + FileUploadRequest uploadFileRequest = FileUploadRequest.builder() + .fileObject(file) // File object + .table("cards") // Vault table to upload into + .columnName("file") // Column to assign to the uploaded file + .skyflowId("c9312531-2087-439a-bd26-74c41f24db83") // Skyflow id of the record + .build(); + + // Step 3: Execute the file upload request + FileUploadResponse uploadResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").uploadFile(uploadFileRequest); + System.out.println("File Upload Response: " + fileUploadResponse); + + } catch (SkyflowException e) { + // Step 4: Handle any exceptions during the upload + System.out.println("Error occurred during file upload:"); + e.printStackTrace(); // Print exception details for debugging + } + } +} + +``` + +Sample response: + +```json +{ + "skyflowId": "c9312531-2087-439a-bd26-74c41f24db83", + "errors": null +} +``` + +# Detect +Skyflow Detect enables you to deidentify and reidentify sensitive data in text and files, supporting advanced privacy-preserving workflows. The Detect API supports the following operations: + +## Deidentify Text +To deidentify text, use the `deidentifyText` method. The `DeidentifyTextRequest` class creates a deidentify text request, which includes the text to be deidentified. Additionally, you can provide optional parameters using the `DeidentifyTextOptions` class. + +### Construct an deidentify text request + +```java +import com.skyflow.enums.DetectEntities; +import com.skyflow.vault.detect.DateTransformation; +import com.skyflow.vault.detect.DeidentifyTextRequest; +import com.skyflow.vault.detect.TokenFormat; +import com.skyflow.vault.detect.Transformations; +import com.skyflow.vault.detect.DeidentifyTextResponse; + +import java.util.ArrayList; +import java.util.List; + +/** + * This example demonstrate to build deidentify text request. + */ +public class DeidentifyTextSchema { + + public static void main(String[] args) { + + // Step 1: Initialise the Skyflow client by configuring the credentials & vault config. + + // Step 2: Configure the options for deidentify text + + // Replace with the entity you want to detect + List detectEntitiesList = new ArrayList<>(); + detectEntitiesList.add(DetectEntities.SSN); + + // Replace with the entity you want to detect with vault token + List vaultTokenList = new ArrayList<>(); + vaultTokenList.add(DetectEntities.CREDIT_CARD); + + // Replace with the entity you want to detect with entity only + List entityOnlyList = new ArrayList<>(); + entityOnlyList.add(DetectEntities.SSN); + + // Replace with the entity you want to detect with entity unique counter + List entityUniqueCounterList = new ArrayList<>(); + entityUniqueCounterList.add(DetectEntities.SSN); + + // Replace with the regex patterns you want to allow during deidentification + List allowRegexList = new ArrayList<>(); + allowRegexList.add(""); + + // Replace with the regex patterns you want to restrict during deidentification + List restrictRegexList = new ArrayList<>(); + restrictRegexList.add("YOUR_RESTRICT_REGEX_LIST"); + + // Configure Token Format + TokenFormat tokenFormat = TokenFormat.builder() + .vaultToken(vaultTokenList) + .entityOnly(entityOnlyList) + .entityUniqueCounter(entityUniqueCounterList) + .build(); + + // Configure Transformation + List detectEntitiesTransformationList = new ArrayList<>(); + detectEntitiesTransformationList.add(DetectEntities.DOB); // Replace with the entity you want to transform + + DateTransformation dateTransformation = new DateTransformation(20, 5, detectEntitiesTransformationList); + Transformations transformations = new Transformations(dateTransformation); + + // Step 3: Create a deidentify text request for the vault + DeidentifyTextRequest deidentifyTextRequest = DeidentifyTextRequest.builder() + .text("") // Replace with the text you want to deidentify + .entities(detectEntitiesList) + .allowRegexList(allowRegexList) + .restrictRegexList(restrictRegexList) + .tokenFormat(tokenFormat) + .transformations(transformations) + .build(); + + // Step 4: Use the Skyflow client to perform the deidentifyText operation + // Replace with your actual vault ID + DeidentifyTextResponse deidentifyTextResponse = skyflowClient.detect("").deidentifyText(deidentifyTextRequest); + + // Step 5: Print the response + System.out.println("Deidentify text Response: " + deidentifyTextResponse); + } +} + +``` + +## An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/detect/DeidentifyTextExample.java) of deidentify text: +```java +import java.util.ArrayList; +import java.util.List; + +import com.skyflow.enums.DetectEntities; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.detect.DateTransformation; +import com.skyflow.vault.detect.DeidentifyTextRequest; +import com.skyflow.vault.detect.DeidentifyTextResponse; +import com.skyflow.vault.detect.TokenFormat; +import com.skyflow.vault.detect.Transformations; + +/** + * Skyflow Deidentify Text Example + *

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

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

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

+ * This example demonstrates how to: + * 1. Configure credentials + * 2. Set up vault configuration + * 3. Create a get detect run request + * 4. Call getDetectRun to poll for file processing results + * 5. Handle response and errors + */ +public class GetDetectRunExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Initialise the Skyflow client by configuring the credentials & vault config. + try { + + // Step 2: Create a get detect run request + GetDetectRunRequest getDetectRunRequest = GetDetectRunRequest.builder() + .runId("e0038196-4a20-422b-bad7-e0477117f9bb") // Replace with the runId from deidentifyFile call + .build(); + + // Step 3: Call getDetectRun to poll for file processing results + // Replace `9f27764a10f7946fe56b3258e117` with the acutal vault id + DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect("9f27764a10f7946fe56b3258e117").getDetectRun(getDetectRunRequest); + System.out.println("Get Detect Run Response: " + deidentifyFileResponse); + } catch (SkyflowException e) { + System.err.println("Error occurred during get detect run: "); + e.printStackTrace(); + } + } +} +``` + +Sample Response: + +```json +{ + "file": "bmFtZTogW05BTET0JfMV0K", + "type": "redacted_file", + "extension": "txt", + "wordCount": 11, + "charCount": 61, + "sizeInKb": 0.0, + "entities": [ + { + "file": "gW05BTUVfMV0gCmNhcmQ0K", + "type": "entities", + "extension": "json" + } + ], + "runId": "e0038196-4a20-422b-bad7-e0477117f9bb", + "status": "success" +} + +``` + +# Connections + +Skyflow Connections is a gateway service that uses tokenization to securely send and receive data between your systems and first- or third-party services. The [connections](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault/connection) module invokes both inbound and/or outbound connections. + +- **Inbound connections**: Act as intermediaries between your client and server, tokenizing sensitive data before it reaches your backend, ensuring downstream services handle only tokenized data. +- **Outbound connections**: Enable secure extraction of data from the vault and transfer it to third-party services via your backend server, such as processing checkout or card issuance flows. + +## Invoke a connection + +To invoke a connection, use the `invoke` method of the Skyflow client. + +### Construct an invoke connection request + +```java +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; + +/** + * This example demonstrates how to invoke an external connection using the Skyflow SDK, along with corresponding InvokeConnectionRequest schema. + * + */ +public class InvokeConnectionSchema { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Define the request body parameters + // These are the values you want to send in the request body + Map requestBody = new HashMap<>(); + requestBody.put("", ""); + requestBody.put("", ""); + + // Step 2: Define the request headers + // Add any required headers that need to be sent with the request + Map requestHeaders = new HashMap<>(); + requestHeaders.put("", ""); + requestHeaders.put("", ""); + + // Step 3: Define the path parameters + // Path parameters are part of the URL and typically used in RESTful APIs + Map pathParams = new HashMap<>(); + pathParams.put("", ""); + pathParams.put("", ""); + + // Step 4: Define the query parameters + // Query parameters are included in the URL after a '?' and are used to filter or modify the response + Map queryParams = new HashMap<>(); + queryParams.put("", ""); + queryParams.put("", ""); + + // Step 5: Build the InvokeConnectionRequest using the provided parameters + InvokeConnectionRequest invokeConnectionRequest = InvokeConnectionRequest.builder() + .method(RequestMethod.POST) // The HTTP method to use for the request (POST in this case) + .requestBody(requestBody) // The body of the request + .requestHeaders(requestHeaders) // The headers to include in the request + .pathParams(pathParams) // The path parameters for the URL + .queryParams(queryParams) // The query parameters to append to the URL + .build(); + + // Step 6: Invoke the connection using the request + // Replace "" with the actual connection ID you are using + InvokeConnectionResponse invokeConnectionResponse = skyflowClient.connection("").invoke(invokeConnectionRequest); + + // Step 7: Print the response from the invoked connection + // This response contains the result of the request sent to the external system + System.out.println(invokeConnectionResponse); + + } catch (SkyflowException e) { + // Step 8: Handle any exceptions that occur during the connection invocation + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception stack trace for debugging + } + } +} +``` + +`method` supports the following methods: + +- GET +- POST +- PUT +- PATCH +- DELETE + +**pathParams, queryParams, requestHeader, requestBody** are the JSON objects represented as HashMaps, that will be sent through the connection integration url. + +### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/connection/InvokeConnectionExample.java) of invokeConnection + +```java +import com.skyflow.Skyflow; +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; + +/** + * This example demonstrates how to invoke an external connection using the Skyflow SDK. + * It configures a connection, sets up the request, and sends a POST request to the external service. + * + * 1. Initialize Skyflow client with connection details. + * 2. Define the request body, headers, and method. + * 3. Execute the connection request. + * 4. Print the response from the invoked connection. + */ +public class InvokeConnectionExample { + public static void main(String[] args) { + try { + // Initialize Skyflow client + // Step 1: Set up credentials and connection configuration + // Load credentials from a JSON file (you need to provide the correct path) + Credentials credentials = new Credentials(); + credentials.setPath("/path/to/credentials.json"); + + // Define the connection configuration (URL and credentials) + ConnectionConfig connectionConfig = new ConnectionConfig(); + connectionConfig.setConnectionId(""); // Replace with actual connection ID + connectionConfig.setConnectionUrl("https://connection.url.com"); // Replace with actual connection URL + connectionConfig.setCredentials(credentials); // Set credentials for the connection + + // Initialize the Skyflow client with the connection configuration + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) // Set log level to DEBUG for detailed logs + .addConnectionConfig(connectionConfig) // Add connection configuration to client + .build(); // Build the Skyflow client instance + + // Step 2: Define the request body and headers + // Map for request body parameters + Map requestBody = new HashMap<>(); + requestBody.put("card_number", "4337-1696-5866-0865"); // Example card number + requestBody.put("ssn", "524-41-4248"); // Example SSN + + // Map for request headers + Map requestHeaders = new HashMap<>(); + requestHeaders.put("Content-Type", "application/json"); // Set content type for the request + + // Step 3: Build the InvokeConnectionRequest with required parameters + // Set HTTP method to POST, include the request body and headers + InvokeConnectionRequest invokeConnectionRequest = InvokeConnectionRequest.builder() + .method(RequestMethod.POST) // HTTP POST method + .requestBody(requestBody) // Add request body parameters + .requestHeaders(requestHeaders) // Add headers + .build(); // Build the request + + // Step 4: Invoke the connection and capture the response + // Replace "" with the actual connection ID + InvokeConnectionResponse invokeConnectionResponse = skyflowClient.connection("").invoke(invokeConnectionRequest); + + // Step 5: Print the response from the connection invocation + System.out.println(invokeConnectionResponse); // Print the response to the console + + } catch (SkyflowException e) { + // Step 6: Handle any exceptions that occur during the connection invocation + System.out.println("Error occurred: "); + e.printStackTrace(); // Print the exception stack trace for debugging + } + } +} +``` + +Sample response: + +```json +{ + "data": { + "card_number": "4337-1696-5866-0865", + "ssn": "524-41-4248" + }, + "metadata": { + "requestId": "4a3453b5-7aa4-4373-98d7-cf102b1f6f97" + } +} +``` + +# Authenticate with bearer tokens + +This section covers methods for generating and managing tokens to authenticate API calls: + +- **Generate a bearer token**: + Enable the creation of bearer tokens using service account credentials. These tokens, valid for 60 minutes, provide secure access to Vault services and management APIs based on the service account's permissions. Use this for general API calls when you only need basic authentication without additional context or role-based restrictions. +- **Generate a bearer token with context**: + Support embedding context values into bearer tokens, enabling dynamic access control and the ability to track end-user identity. These tokens include context claims and allow flexible authorization for Vault services. Use this when policies depend on specific contextual attributes or when tracking end-user identity is required. +- **Generate a scoped bearer token**: + Facilitate the creation of bearer tokens with role-specific access, ensuring permissions are limited to the operations allowed by the designated role. This is particularly useful for service accounts with multiple roles. Use this to enforce fine-grained role-based access control, ensuring tokens only grant permissions for a specific role. +- **Generate signed data tokens**: + Add an extra layer of security by digitally signing data tokens with the service account's private key. These signed tokens can be securely detokenized, provided the necessary bearer token and permissions are available. Use this to add cryptographic protection to sensitive data, enabling secure detokenization with verified integrity and authenticity. + +## Generate a bearer token + +The [Service Account](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/serviceaccount/util) Java module generates service account tokens using a service account credentials file, which is provided when a service account is created. The tokens generated by this module are valid for 60 minutes and can be used to make API calls to the [Data](https://docs.skyflow.com/record/) and [Management](https://docs.skyflow.com/management/) APIs, depending on the permissions assigned to the service account. + +The `BearerToken` utility class generates bearer tokens using a credentials JSON file. Alternatively, you can pass the credentials as a string. + +[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java): + +```java +/** + * Example program to generate a Bearer Token using Skyflow's BearerToken utility. + * The token can be generated in two ways: + * 1. Using the file path to a credentials.json file. + * 2. Using the JSON content of the credentials file as a string. + */ +public class BearerTokenGenerationExample { + public static void main(String[] args) { + // Variable to store the generated token + String token = null; + + // Example 1: Generate Bearer Token using a credentials.json file + try { + // Specify the full file path to the credentials.json file + String filePath = ""; + + // Check if the token is either not initialized or has expired + if (Token.isExpired(token)) { + // Create a BearerToken object using the credentials file + BearerToken bearerToken = BearerToken.builder() + .setCredentials(new File(filePath)) // Set credentials from the file path + .build(); + + // Generate a new Bearer Token + token = bearerToken.getBearerToken(); + } + + // Print the generated Bearer Token to the console + System.out.println("Generated Bearer Token (from file): " + token); + } catch (SkyflowException e) { + // Handle any exceptions encountered during the token generation process + e.printStackTrace(); + } + + // Example 2: Generate Bearer Token using the credentials JSON as a string + try { + // Provide the credentials JSON content as a string + String fileContents = ""; + + // Check if the token is either not initialized or has expired + if (Token.isExpired(token)) { + // Create a BearerToken object using the credentials string + BearerToken bearerToken = BearerToken.builder() + .setCredentials(fileContents) // Set credentials from the string + .build(); + + // Generate a new Bearer Token + token = bearerToken.getBearerToken(); + } + + // Print the generated Bearer Token to the console + System.out.println("Generated Bearer Token (from string): " + token); + } catch (SkyflowException e) { + // Handle any exceptions encountered during the token generation process + e.printStackTrace(); + } + } +} +``` + +## Generate bearer tokens with context + +**Context-aware authorization** embeds context values into a bearer token during its generation and so you can reference those values in your policies. This enables more flexible access controls, such as helping you track end-user identity when making API calls using service accounts, and facilitates using signed data tokens during detokenization. . + +A service account with the `context_id` identifier generates bearer tokens containing context information, represented as a JWT claim in a Skyflow-generated bearer token. Tokens generated from such service accounts include a `context_identifier` claim, are valid for 60 minutes, and can be used to make API calls to the Data and Management APIs, depending on the service account's permissions. + +[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java): + +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.BearerToken; + +import java.io.File; + +/** + * Example program to generate a Bearer Token using Skyflow's BearerToken utility. + * The token is generated using two approaches: + * 1. By providing the credentials.json file path. + * 2. By providing the contents of credentials.json as a string. + */ +public class BearerTokenGenerationWithContextExample { + public static void main(String[] args) { + // Variable to store the generated Bearer Token + String bearerToken = null; + + // Approach 1: Generate Bearer Token by specifying the path to the credentials.json file + try { + // Replace with the full path to your credentials.json file + String filePath = ""; + + // Create a BearerToken object using the file path + BearerToken token = BearerToken.builder() + .setCredentials(new File(filePath)) // Set credentials using a File object + .setCtx("abc") // Set context string (example: "abc") + .build(); // Build the BearerToken object + + // Retrieve the Bearer Token as a string + bearerToken = token.getBearerToken(); + + // Print the generated Bearer Token to the console + System.out.println(bearerToken); + } catch (SkyflowException e) { + // Handle exceptions specific to Skyflow operations + e.printStackTrace(); + } + + // Approach 2: Generate Bearer Token by specifying the contents of credentials.json as a string + try { + // Replace with the actual contents of your credentials.json file + String fileContents = ""; + + // Create a BearerToken object using the file contents as a string + BearerToken token = BearerToken.builder() + .setCredentials(fileContents) // Set credentials using a string representation of the file + .setCtx("abc") // Set context string (example: "abc") + .build(); // Build the BearerToken object + + // Retrieve the Bearer Token as a string + bearerToken = token.getBearerToken(); + + // Print the generated Bearer Token to the console + System.out.println(bearerToken); + } catch (SkyflowException e) { + // Handle exceptions specific to Skyflow operations + e.printStackTrace(); + } + } +} +``` + +## Generate scoped bearer tokens + +A service account with multiple roles can generate bearer tokens with access limited to a specific role by specifying the appropriate `roleID`. This can be used to limit access to specific roles for services with multiple responsibilities, such as segregating access for billing and analytics. The generated bearer tokens are valid for 60 minutes and can only execute operations permitted by the permissions associated with the designated role. + +[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java): + +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.BearerToken; + +import java.io.File; +import java.util.ArrayList; + +/** + * Example program to generate a Scoped Token using Skyflow's BearerToken utility. + * The token is generated by providing the file path to the credentials.json file + * and specifying roles associated with the token. + */ +public class ScopedTokenGenerationExample { + public static void main(String[] args) { + // Variable to store the generated scoped token + String scopedToken = null; + + // Example: Generate Scoped Token by specifying the credentials.json file path + try { + // Create a list of roles that the generated token will be scoped to + ArrayList roles = new ArrayList<>(); + roles.add("ROLE_ID"); // Add a specific role to the list (e.g., "ROLE_ID") + + // Specify the full file path to the service account's credentials.json file + String filePath = ""; + + // Create a BearerToken object using the credentials file and associated roles + BearerToken bearerToken = BearerToken.builder() + .setCredentials(new File(filePath)) // Set credentials using the credentials.json file + .setRoles(roles) // Set the roles that the token should be scoped to + .build(); // Build the BearerToken object + + // Retrieve the generated scoped token + scopedToken = bearerToken.getBearerToken(); + + // Print the generated scoped token to the console + System.out.println(scopedToken); + } catch (SkyflowException e) { + // Handle exceptions that may occur during token generation + e.printStackTrace(); + } + } +} +``` + +Notes: + +- You can pass either the file path of a service account key credentials file or the service account key credentials as a string to the `setCredentials` method of the `BearerTokenBuilder` class. +- If both a file path and a string are provided, the last method used takes precedence. +- To generate multiple bearer tokens concurrently using threads, refer to the following [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java). + +## Generate Signed Data Tokens + +Skyflow generates data tokens when sensitive data is inserted into the vault. These data tokens can be digitally signed +with the private key of the service account credentials, which adds an additional layer of protection. Signed tokens can +be detokenized by passing the signed data token and a bearer token generated from service account credentials. The +service account must have appropriate permissions and context to detokenize the signed data tokens. + +[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java): + +```java +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.SignedDataTokenResponse; +import com.skyflow.serviceaccount.util.SignedDataTokens; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +public class SignedTokenGenerationExample { + public static void main(String[] args) { + List signedTokenValues; + // Generate Signed data token with context by specifying credentials.json file path + try { + String filePath = ""; + String context = "abc"; + ArrayList dataTokens = new ArrayList<>(); + dataTokens.add("YOUR_DATA_TOKEN_1"); + SignedDataTokens signedToken = SignedDataTokens.builder() + .setCredentials(new File(filePath)) + .setCtx(context) + .setTimeToLive(30) // in seconds + .setDataTokens(dataTokens) + .build(); + signedTokenValues = signedToken.getSignedDataTokens(); + System.out.println(signedTokenValues); + } catch (SkyflowException e) { + e.printStackTrace(); + } + + // Generate Signed data token with context by specifying credentials.json as string + try { + String fileContents = ""; + String context = "abc"; + ArrayList dataTokens = new ArrayList<>(); + dataTokens.add("YOUR_DATA_TOKEN_1"); + SignedDataTokens signedToken = SignedDataTokens.builder() + .setCredentials(fileContents) + .setCtx(context) + .setTimeToLive(30) // in seconds + .setDataTokens(dataTokens) + .build(); + signedTokenValues = signedToken.getSignedDataTokens(); + System.out.println(signedTokenValues); + } catch (SkyflowException e) { + e.printStackTrace(); + } + } +} +``` + +Response: + +```json +[ + { + "dataToken": "5530-4316-0674-5748", + "signedDataToken": "signed_token_eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJzLCpZjA" + } +] +``` + +Notes: + +- You can provide either the file path to a service account key credentials file or the service account key credentials as a string to the `setCredentials` method of the `SignedDataTokensBuilder` class. +- If both a file path and a string are passed to the `setCredentials` method, the most recently specified input takes precedence. +- The `time-to-live` (TTL) value should be specified in seconds. +- By default, the TTL value is set to 60 seconds. + +## Bearer token expiry edge case +When you use bearer tokens for authentication and API requests in SDKs, there's the potential for a token to expire after the token is verified as valid but before the actual API call is made, causing the request to fail unexpectedly due to the token's expiration. An error from this edge case would look something like this: + +```txt +message: Authentication failed. Bearer token is expired. Use a valid bearer token. See https://docs.skyflow.com/api-authentication/ +``` + +If you encounter this kind of error, retry the request. During the retry, the SDK detects that the previous bearer token has expired and generates a new one for the current and subsequent requests. + +#### [Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java): + +```java +package com.example.serviceaccount; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.DetokenizeResponse; +import io.github.cdimascio.dotenv.Dotenv; +import java.util.ArrayList; + +/** + * This example demonstrates how to configure and use the Skyflow SDK + * to detokenize sensitive data stored in a Skyflow vault. + * It includes setting up credentials, configuring the vault, and + * making a detokenization request. The code also implements a retry + * mechanism to handle unauthorized access errors (HTTP 401). + */ +public class DetokenizeExample { + public static void main(String[] args) { + try { + // Setting up credentials for accessing the Skyflow vault + Credentials vaultCredentials = new Credentials(); + vaultCredentials.setCredentialsString(""); + + // Configuring the Skyflow vault with necessary details + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Vault ID + vaultConfig.setClusterId(""); // Cluster ID + vaultConfig.setEnv(Env.PROD); // Environment (e.g., DEV, PROD) + vaultConfig.setCredentials(vaultCredentials); // Setting credentials + + // Creating a Skyflow client instance with the configured vault + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Setting log level to ERROR + .addVaultConfig(vaultConfig) // Adding vault configuration + .build(); + + // Attempting to detokenize data using the Skyflow client + try { + detokenizeData(skyflowClient); + } catch (SkyflowException e) { + // Retry detokenization if the error is due to unauthorized access (HTTP 401) + if (e.getHttpCode() == 401) { + detokenizeData(skyflowClient); + } else { + // Rethrow the exception for other error codes + throw e; + } + } + } catch (SkyflowException e) { + // Handling any exceptions that occur during the process + System.out.println("An error occurred: " + e.getMessage()); + } + } + + /** + * Method to detokenize data using the Skyflow client. + * It sends a detokenization request with a list of tokens and prints the response. + * + * @param skyflowClient The Skyflow client instance used for detokenization. + * @throws SkyflowException If an error occurs during the detokenization process. + */ + public static void detokenizeData(Skyflow skyflowClient) throws SkyflowException { + // Creating a list of tokens to be detokenized + ArrayList tokenList = new ArrayList<>(); + tokenList.add(""); // First token + tokenList.add(""); // Second token + + // Building a detokenization request with the token list and configuration + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .tokens(tokenList) // Adding tokens to the request + .continueOnError(false) // Stop on error + .redactionType(RedactionType.PLAIN_TEXT) // Redaction type (e.g., PLAIN_TEXT) + .build(); + + // Sending the detokenization request and receiving the response + DetokenizeResponse detokenizeResponse = skyflowClient.vault().detokenize(detokenizeRequest); + + // Printing the detokenized response + System.out.println(detokenizeResponse); + } +} +``` + +# Logging + +The SDK provides logging with Java's built-in logging library. By default, the SDK's logging level is set to `LogLevel.ERROR`. This can be changed using the `setLogLevel(logLevel)` method, as shown below: + +Currently, the following five log levels are supported: + +- `DEBUG`**:** + When `LogLevel.DEBUG` is passed, logs at all levels will be printed (DEBUG, INFO, WARN, ERROR). +- `INFO`**:** + When `LogLevel.INFO` is passed, INFO logs for every event that occurs during SDK flow execution will be printed, along with WARN and ERROR logs. +- `WARN`**:** + When `LogLevel.WARN` is passed, only WARN and ERROR logs will be printed. +- `ERROR`**:** + When `LogLevel.ERROR` is passed, only ERROR logs will be printed. +- `OFF`**:** + `LogLevel.OFF` can be used to turn off all logging from the Skyflow Java SDK. + +**Note:** The ranking of logging levels is as follows: `DEBUG` \< `INFO` \< `WARN` \< `ERROR` \< `OFF`. + +```java +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; + +/** + * This example demonstrates how to configure the Skyflow client with custom log levels + * and authentication credentials (either token, credentials string, or other methods). + * It also shows how to configure a vault connection using specific parameters. + * + * 1. Set up credentials with a Bearer token or credentials string. + * 2. Define the Vault configuration. + * 3. Build the Skyflow client with the chosen configuration and set log level. + * 4. Example of changing the log level from ERROR (default) to INFO. + */ +public class ChangeLogLevel { + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials - either pass token or use credentials string + // In this case, we are using a Bearer token for authentication + Credentials credentials = new Credentials(); + credentials.setToken(""); // Replace with actual Bearer token + + // Step 2: Define the Vault configuration + // Configure the vault with necessary details like vault ID, cluster ID, and environment + VaultConfig config = new VaultConfig(); + config.setVaultId(""); // Replace with actual Vault ID (primary vault) + config.setClusterId(""); // Replace with actual Cluster ID (from vault URL) + config.setEnv(Env.PROD); // Set the environment (default is PROD) + config.setCredentials(credentials); // Set credentials for the vault (either token or credentials) + + // Step 3: Define additional Skyflow credentials (optional, if needed for credentials string) + // Create a JSON object to hold your Skyflow credentials + JsonObject credentialsObject = new JsonObject(); + credentialsObject.addProperty("clientID", ""); // Replace with your client ID + credentialsObject.addProperty("clientName", ""); // Replace with your client name + credentialsObject.addProperty("TokenURI", ""); // Replace with your token URI + credentialsObject.addProperty("keyID", ""); // Replace with your key ID + credentialsObject.addProperty("privateKey", ""); // Replace with your private key + + // Convert the credentials object to a string format to be used for generating a Bearer Token + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(credentialsObject.toString()); // Set credentials string + + // Step 4: Build the Skyflow client with the chosen configuration and log level + Skyflow skyflowClient = Skyflow.builder() + .addVaultConfig(config) // Add the Vault configuration + .addSkyflowCredentials(skyflowCredentials) // Use Skyflow credentials if no token is passed + .setLogLevel(LogLevel.INFO) // Set log level to INFO (default is ERROR) + .build(); // Build the Skyflow client + + // Now, the Skyflow client is ready to use with the specified log level and credentials + System.out.println("Skyflow client has been successfully configured with log level: INFO."); + } +} +``` -## Reporting a Vulnerability +# Reporting a Vulnerability -If you discover a potential security issue in this project, please reach out to us at security@skyflow.com. Please do not create public GitHub issues or Pull Requests, as malicious actors could potentially view them. +If you discover a potential security issue in this project, please reach out to us at **security@skyflow.com**. Please do not create public GitHub issues or Pull Requests, as malicious actors could potentially view them. diff --git a/pom.xml b/pom.xml index 87e2d899..38869a73 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.skyflow skyflow-java - 1.15.0 + 2.0.0 jar ${project.groupId}:${project.artifactId} @@ -32,65 +32,98 @@ - 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 + jackson-databind + 2.17.2 + compile - com.googlecode.json-simple - json-simple - 1.1.1 + com.fasterxml.jackson.datatype + jackson-datatype-jdk8 + 2.17.2 + compile - io.jsonwebtoken - jjwt - 0.9.1 + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + 2.17.2 + compile + + + + io.github.cdimascio + dotenv-java + 2.2.0 + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + io.gsonfire + gson-fire + ${gson-fire-version} + + + com.google.code.gson + gson + ${gson-version} + + + com.squareup.okhttp3 + okhttp + ${okhttp-version} + + + com.squareup.okhttp3 + logging-interceptor + ${okhttp-version} + 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 test + org.powermock powermock-module-junit4 @@ -124,6 +157,11 @@ org.apache.maven.plugins maven-javadoc-plugin 3.2.0 + + + com.skyflow.generated.rest.* + + attach-javadocs @@ -136,17 +174,19 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.2 + 3.2.5 + + false + + **/*Test.java + **/*Tests.java + + org.jacoco jacoco-maven-plugin 0.8.7 - - - **/example/* - - prepare-agent @@ -162,6 +202,26 @@ + + + **/example/* + **/generated/** + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.3.0 + + + + test-jar + + + + + org.apache.maven.plugins @@ -186,31 +246,38 @@ + + + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ + + maven-central - ossrh - https://s01.oss.sonatype.org/service/local/staging/deploy/maven2 + central + https://central.sonatype.com/api/v1/publisher/upload - ossrh - https://s01.oss.sonatype.org/content/repositories/snapshots + central-snapshots + https://central.sonatype.com/api/v1/publisher/upload - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 + org.sonatype.central + central-publishing-maven-plugin + 0.4.0 true - ossrh - https://s01.oss.sonatype.org/ - true + central + true + true @@ -232,5 +299,4 @@ - - \ No newline at end of file + diff --git a/samples/pom.xml b/samples/pom.xml index c48ba302..9d690678 100644 --- a/samples/pom.xml +++ b/samples/pom.xml @@ -18,7 +18,7 @@ com.skyflow skyflow-java - 1.15.0 + 2.0.0 diff --git a/samples/src/main/java/com/example/BearerTokenGenerationUsingThreadsExample.java b/samples/src/main/java/com/example/BearerTokenGenerationUsingThreadsExample.java deleted file mode 100644 index 718aa21e..00000000 --- a/samples/src/main/java/com/example/BearerTokenGenerationUsingThreadsExample.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.BearerToken; - -import java.io.File; - -public class BearerTokenGenerationUsingThreadsExample { - public static void main(String args[]) { - - String bearerToken = null; - - // Generate BearerToken with context by specifying credentials.json file path - try { - String filePath = ""; - final BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(filePath)) - .setCtx("abc") - .build(); - - Thread t = new Thread(new Runnable() { - @Override - public void run() { - - for (int i = 0; i < 5; i++) { - try { - System.out.println(token.getBearerToken()); - } catch (SkyflowException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException(e); - - } - - } - } - }); - - t.start(); - - } catch (Exception e) { - e.printStackTrace(); - } - - } -} diff --git a/samples/src/main/java/com/example/BearerTokenWithContextGenerationExample.java b/samples/src/main/java/com/example/BearerTokenWithContextGenerationExample.java deleted file mode 100644 index 668b7c81..00000000 --- a/samples/src/main/java/com/example/BearerTokenWithContextGenerationExample.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.BearerToken; - -import java.io.File; - -public class BearerTokenWithContextGenerationExample { - public static void main(String args[]) { - - String bearerToken = null; - - // Generate BearerToken with context by specifying credentials.json file path - try { - String filePath = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(filePath)) - .setCtx("abc") - .build(); - - bearerToken = token.getBearerToken(); - System.out.println(bearerToken); - } catch (Exception e) { - e.printStackTrace(); - } - - // Generate BearerToken with context by specifying credentials.json as string - try { - String fileContents = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(fileContents) - .setCtx("abc") - .build(); - - bearerToken = token.getBearerToken(); - System.out.println(bearerToken); - - } catch (SkyflowException e) { - e.printStackTrace(); - } - - } -} diff --git a/samples/src/main/java/com/example/DeleteExample.java b/samples/src/main/java/com/example/DeleteExample.java deleted file mode 100644 index 9ee0fc28..00000000 --- a/samples/src/main/java/com/example/DeleteExample.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - Copyright (c) 2023 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.ResponseToken; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - - -public class DeleteExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration( - "", - "", - new DemoTokenProvider() - ); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - - record.put("id", ""); - record.put("table", ""); - recordsArray.add(record); - JSONObject record2 = new JSONObject(); - - record2.put("id", ""); - record2.put("table", ""); - recordsArray.add(record2); - - records.put("records", recordsArray); - - JSONObject response = skyflowClient.delete(records); - System.out.println(response); - } catch (SkyflowException e) { - e.printStackTrace(); - System.out.println("error" + e.getData()); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if (Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/DetokenizeExample.java b/samples/src/main/java/com/example/DetokenizeExample.java deleted file mode 100644 index acc29287..00000000 --- a/samples/src/main/java/com/example/DetokenizeExample.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.RedactionType; -import com.skyflow.entities.ResponseToken; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - - -public class DetokenizeExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration( - "", - "", - new DemoTokenProvider() - ); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record1 = new JSONObject(); - record1.put("token", ""); - record1.put("redaction", RedactionType.MASKED.toString()); - - JSONObject record2 = new JSONObject(); - record2.put("token", ""); // default Redaction "PLAIN_TEXT" will be applied for record2 - - recordsArray.add(record1); - recordsArray.add(record2); - records.put("records", recordsArray); - - JSONObject response = skyflowClient.detokenize(records); - System.out.println(response); - } catch (SkyflowException e) { - e.printStackTrace(); - System.out.println(e.getData()); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/GetByIdExample.java b/samples/src/main/java/com/example/GetByIdExample.java deleted file mode 100644 index b3576fb3..00000000 --- a/samples/src/main/java/com/example/GetByIdExample.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.RedactionType; -import com.skyflow.entities.ResponseToken; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - - -public class GetByIdExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - JSONArray ids = new JSONArray(); - ids.add(""); - - record.put("ids", ids); - record.put("table", ""); - record.put("redaction", RedactionType.PLAIN_TEXT.toString()); - recordsArray.add(record); - records.put("records", recordsArray); - - JSONObject response = skyflowClient.getById(records); - } catch (SkyflowException e) { - e.printStackTrace(); - System.out.println(e.getData()); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/GetExample.java b/samples/src/main/java/com/example/GetExample.java deleted file mode 100644 index 76cf826a..00000000 --- a/samples/src/main/java/com/example/GetExample.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.example; - -import com.skyflow.entities.RedactionType; -import com.skyflow.entities.ResponseToken; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -public class GetExample { - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject firstRecord = new JSONObject(); - - JSONArray ids = new JSONArray(); - ids.add(""); - - firstRecord.put("ids", ids); - firstRecord.put("table", ""); - firstRecord.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - JSONObject secondRecord = new JSONObject(); - - JSONArray valuesArray = new JSONArray(); - valuesArray.add(""); - - secondRecord.put("table", ""); - secondRecord.put("columnName", ""); - secondRecord.put("columnValues", valuesArray); - secondRecord.put("redaction", RedactionType.PLAIN_TEXT.toString()); - - recordsArray.add(firstRecord); - recordsArray.add(secondRecord); - records.put("records", recordsArray); - - JSONObject response = skyflowClient.get(records); - } catch (SkyflowException e) { - e.printStackTrace(); - System.out.println(e.getData()); - } - - } - - static class DemoTokenProvider implements TokenProvider { - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if (Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} \ No newline at end of file diff --git a/samples/src/main/java/com/example/InsertBulkExample.java b/samples/src/main/java/com/example/InsertBulkExample.java deleted file mode 100644 index bb191c7c..00000000 --- a/samples/src/main/java/com/example/InsertBulkExample.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.example; - -import com.skyflow.entities.*; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -public class InsertBulkExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", ""); - - JSONObject fields = new JSONObject(); - fields.put("", ""); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - JSONObject res = skyflowClient.insertBulk(records); - - System.out.println(res); - } catch (SkyflowException e) { - e.printStackTrace(); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} \ No newline at end of file diff --git a/samples/src/main/java/com/example/InsertBulkWithUpsertExample.java b/samples/src/main/java/com/example/InsertBulkWithUpsertExample.java deleted file mode 100644 index 57272e15..00000000 --- a/samples/src/main/java/com/example/InsertBulkWithUpsertExample.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.example; - -import com.skyflow.entities.*; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - - -public class InsertBulkWithUpsertExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", ""); - - JSONObject fields = new JSONObject(); - fields.put(""); - - record.put("fields", fields); - recordsArray.add(record); - - records.put("records", recordsArray); - - // create an upsert option and insert in UpsertOptions array. - UpsertOption[] upsertOptions = new UpsertOption[1]; - upsertOptions[0] = new UpsertOption("", ""); - - // pass upsert options in insert method options. - InsertBulkOptions insertOptions = new InsertBulkOptions(true, upsertOptions); - JSONObject res = skyflowClient.insertBulk(records, insertOptions); - - System.out.println(res); - } catch (SkyflowException e) { - e.printStackTrace(); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if (Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/InsertExample.java b/samples/src/main/java/com/example/InsertExample.java deleted file mode 100644 index faada157..00000000 --- a/samples/src/main/java/com/example/InsertExample.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.InsertOptions; -import com.skyflow.entities.ResponseToken; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -public class InsertExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", ""); - - JSONObject fields = new JSONObject(); - fields.put("", ""); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(); - JSONObject res = skyflowClient.insert(records, insertOptions); - - System.out.println(res); - } catch (SkyflowException e) { - e.printStackTrace(); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/InsertWithContinueOnErrorExample.java b/samples/src/main/java/com/example/InsertWithContinueOnErrorExample.java deleted file mode 100644 index 21e7df2f..00000000 --- a/samples/src/main/java/com/example/InsertWithContinueOnErrorExample.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - Copyright (c) 2024 Skyflow, Inc. -*/ -import com.skyflow.entities.*; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -public class InsertWithContinueOnErrorExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration( - "", - "", - new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record1 = new JSONObject(); - record1.put("table", ""); - JSONObject fields = new JSONObject(); - fields.put("", ""); - record1.put("fields", fields); - - JSONObject record2 = new JSONObject(); - record2.put("table", ""); - JSONObject fields2 = new JSONObject(); - fields2.put("", ""); - record2.put("fields", fields2); - - recordsArray.add(record1); - recordsArray.add(record2); - records.put("records", recordsArray); - - InsertOptions insertOptions = new InsertOptions(true,true); - JSONObject insertResponse = skyflowClient.insert(records, insertOptions); - System.out.println(insertResponse); - } catch (SkyflowException e) { - System.out.println(e); - e.printStackTrace(); - } - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if (Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/InsertWithUpsertExample.java b/samples/src/main/java/com/example/InsertWithUpsertExample.java deleted file mode 100644 index 3ae13357..00000000 --- a/samples/src/main/java/com/example/InsertWithUpsertExample.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.*; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -public class InsertWithUpsertExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - - JSONObject record = new JSONObject(); - record.put("table", ""); - - JSONObject fields = new JSONObject(); - fields.put(""); - - record.put("fields", fields); - recordsArray.add(record); - - records.put("records", recordsArray); - - // create an upsert option and insert in UpsertOptions array. - UpsertOption[] upsertOptions = new UpsertOption[1]; - upsertOptions[0] = new UpsertOption("", ""); - - // pass upsert options in insert method options. - InsertOptions insertOptions = new InsertOptions(true, upsertOptions); - JSONObject res = skyflowClient.insert(records, insertOptions); - - System.out.println(res); - } catch (SkyflowException e) { - e.printStackTrace(); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if (Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} diff --git a/samples/src/main/java/com/example/InvokeConnectionExample.java b/samples/src/main/java/com/example/InvokeConnectionExample.java deleted file mode 100644 index 8f5eac28..00000000 --- a/samples/src/main/java/com/example/InvokeConnectionExample.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -import com.skyflow.entities.*; -import com.skyflow.vault.Skyflow; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -public class InvokeConnectionExample { - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } - - public static void main(String[] args) { - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - JSONObject testConfig = new JSONObject(); - testConfig.put("connectionURL", ""); - testConfig.put("methodName", RequestMethod.POST); - - JSONObject pathParamsJson = new JSONObject(); - pathParamsJson.put("", ""); - testConfig.put("pathParams", pathParamsJson); - - JSONObject queryParamsJson = new JSONObject(); - queryParamsJson.put("", ""); - testConfig.put("queryParams", queryParamsJson); - - JSONObject requestHeadersJson = new JSONObject(); - requestHeadersJson.put("", ""); - testConfig.put("requestHeader", requestHeadersJson); - - JSONObject requestBodyJson = new JSONObject(); - requestBodyJson.put("", ""); - testConfig.put("requestBody", requestBodyJson); - - JSONObject gatewayResponse = skyflowClient.invokeConnection(testConfig); - System.out.println(gatewayResponse); - - } catch (SkyflowException exception) { - exception.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/java/com/example/QueryExample.java b/samples/src/main/java/com/example/QueryExample.java deleted file mode 100644 index 31d577c7..00000000 --- a/samples/src/main/java/com/example/QueryExample.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.ResponseToken; -import com.skyflow.entities.SkyflowConfiguration; -import com.skyflow.entities.TokenProvider; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONObject; - -public class QueryExample { - - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject queryInput = new JSONObject(); - - queryInput.put("query", ""); - - JSONObject res = skyflowClient.query(queryInput); - - System.out.println(res); - } catch (SkyflowException e) { - System.out.println(e.getData()); - e.printStackTrace(); - } - - } - - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} \ No newline at end of file diff --git a/samples/src/main/java/com/example/ScopedTokenGenerationExample.java b/samples/src/main/java/com/example/ScopedTokenGenerationExample.java deleted file mode 100644 index ed4dda5f..00000000 --- a/samples/src/main/java/com/example/ScopedTokenGenerationExample.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.serviceaccount.util.BearerToken; -import java.io.File; - -public class ScopedTokenGenerationExample { - public static void main(String args[]) { - - String scopedToken = null; - - // Generate Scoped Token by specifying credentials.json file path - try { - String filePath = ""; - BearerToken token = new BearerToken.BearerTokenBuilder() - .setCredentials(new File(filePath)) - .setRoles(new String[]{"roleID"}) - .build(); - - scopedToken = token.getBearerToken(); - System.out.println(scopedToken); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/samples/src/main/java/com/example/SignedTokenGenerationExample.java b/samples/src/main/java/com/example/SignedTokenGenerationExample.java deleted file mode 100644 index 1fde4236..00000000 --- a/samples/src/main/java/com/example/SignedTokenGenerationExample.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.SignedDataTokenResponse; -import com.skyflow.serviceaccount.util.SignedDataTokens; - -import java.io.File; -import java.util.List; - -public class SignedTokenGenerationExample { - public static void main(String args[]) { - - List signedTokenValue; - - // Generate Signed data token with context by specifying credentials.json file path - try { - String filePath = ""; - String context = "abc"; - SignedDataTokens signedToken = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(new File(filePath)) - .setCtx(context) - .setTimeToLive(30) // in seconds - .setDataTokens(new String[]{"dataToken1"}).build(); - - signedTokenValue = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValue); - } catch (Exception e) { - e.printStackTrace(); - } - - // Generate Signed data token with context by specifying credentials.json as string - try { - String fileContents = ""; - String context = "abc"; - SignedDataTokens signedToken = new SignedDataTokens.SignedDataTokensBuilder() - .setCredentials(fileContents) - .setCtx(context) - .setTimeToLive(30) // in seconds - .setDataTokens(new String[]{"dataToken1"}).build(); - - signedTokenValue = signedToken.getSignedDataTokens(); - System.out.println(signedTokenValue); - - } catch (SkyflowException e) { - e.printStackTrace(); - } - - - } -} diff --git a/samples/src/main/java/com/example/TokenGenerationExample.java b/samples/src/main/java/com/example/TokenGenerationExample.java deleted file mode 100644 index b4de6b87..00000000 --- a/samples/src/main/java/com/example/TokenGenerationExample.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ -package com.example; - -import com.skyflow.entities.ResponseToken; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; - -public class TokenGenerationExample { - public static void main(String args[]) { - - String bearerToken = null; - - // Generate BearerToken by specifying credentials.json file path - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - ResponseToken res = Token.generateBearerToken(filePath); - bearerToken = res.getAccessToken(); - } - System.out.println(bearerToken); - } catch (Exception e) { - e.printStackTrace(); - } - - // Generate BearerToken by specifying credentials.json as string - try { - String fileContents = ""; - if(Token.isExpired(bearerToken)) { - ResponseToken res = Token.generateBearerTokenFromCreds(fileContents); - bearerToken = res.getAccessToken(); - } - System.out.println(bearerToken); - } catch (SkyflowException e) { - e.printStackTrace(); - } - - } -} diff --git a/samples/src/main/java/com/example/UpdateExample.java b/samples/src/main/java/com/example/UpdateExample.java deleted file mode 100644 index 5e67d7ec..00000000 --- a/samples/src/main/java/com/example/UpdateExample.java +++ /dev/null @@ -1,59 +0,0 @@ -import com.skyflow.entities.*; -import com.skyflow.errors.SkyflowException; -import com.skyflow.serviceaccount.util.Token; -import com.skyflow.vault.Skyflow; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -public class UpdateExample { - public static void main(String[] args) { - - try { - SkyflowConfiguration config = new SkyflowConfiguration("", - "", new DemoTokenProvider()); - Skyflow skyflowClient = Skyflow.init(config); - - JSONObject records = new JSONObject(); - JSONArray recordsArray = new JSONArray(); - JSONObject record = new JSONObject(); - - record.put("table", ""); - record.put("id", ""); - - JSONObject fields = new JSONObject(); - fields.put("", ""); - record.put("fields", fields); - recordsArray.add(record); - records.put("records", recordsArray); - - UpdateOptions updateOptions = new UpdateOptions(true); - JSONObject res = skyflowClient.update(records, updateOptions); - - } - catch (SkyflowException e) { - System.out.println(e.getData()); - e.printStackTrace(); - } - } - static class DemoTokenProvider implements TokenProvider { - - private String bearerToken = null; - - @Override - public String getBearerToken() throws Exception { - ResponseToken response = null; - try { - String filePath = ""; - if(Token.isExpired(bearerToken)) { - response = Token.generateBearerToken(filePath); - bearerToken = response.getAccessToken(); - } - } catch (SkyflowException e) { - e.printStackTrace(); - } - - return bearerToken; - } - } -} - diff --git a/samples/src/main/java/com/example/connection/InvokeConnectionExample.java b/samples/src/main/java/com/example/connection/InvokeConnectionExample.java new file mode 100644 index 00000000..b2e80924 --- /dev/null +++ b/samples/src/main/java/com/example/connection/InvokeConnectionExample.java @@ -0,0 +1,101 @@ +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; + +/** + * This example demonstrates how to use the Skyflow SDK to invoke API connections. + * It includes: + * 1. Setting up credentials and connection configurations. + * 2. Creating a Skyflow client with multiple connections. + * 3. Sending a POST request with request body and headers. + * 4. Sending a GET request with path and query parameters. + */ +public class InvokeConnectionExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for API authentication + Credentials credentials = new Credentials(); + credentials.setApiKey(""); // Replace with the actual API key + + // Step 2: Configure the first connection + ConnectionConfig primaryConnectionConfig = new ConnectionConfig(); + primaryConnectionConfig.setConnectionId(""); // Replace with first connection ID + primaryConnectionConfig.setConnectionUrl(""); // Replace with first connection URL + primaryConnectionConfig.setCredentials(credentials); // Assign credentials + + // Step 3: Configure the second connection + ConnectionConfig secondaryConnectionConfig = new ConnectionConfig(); + secondaryConnectionConfig.setConnectionId(""); // Replace with second connection ID + secondaryConnectionConfig.setConnectionUrl(""); // Replace with second connection URL + + // Step 4: Set up credentials for the Skyflow client + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(""); // Replace with the credentials string + + // Step 5: Create a Skyflow client with connection configurations + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR + .addConnectionConfig(primaryConnectionConfig) // Add the first connection + .addConnectionConfig(secondaryConnectionConfig) // Add the second connection + .addSkyflowCredentials(skyflowCredentials) // Provide Skyflow credentials + .build(); + + // Example 1: Sending a POST request to the first connection + try { + // Set up request body and headers + Map requestBody = new HashMap<>(); + requestBody.put("", ""); // Replace with actual column name and value + requestBody.put("", ""); // Replace with another column name and value + + Map requestHeaders = new HashMap<>(); + requestHeaders.put("", ""); // Replace with actual header name and value + requestHeaders.put("", ""); // Replace with another header name and value + + // Build and send the POST request + InvokeConnectionRequest invokeConnectionRequest1 = InvokeConnectionRequest.builder() + .method(RequestMethod.POST) // HTTP method set to POST + .requestBody(requestBody) // Include request body + .requestHeaders(requestHeaders) // Include request headers + .build(); + + InvokeConnectionResponse invokeConnectionResponse1 = skyflowClient.connection().invoke(invokeConnectionRequest1); + System.out.println("Invoke Connection Response (POST): " + invokeConnectionResponse1); + } catch (SkyflowException e) { + System.out.println("Error while invoking connection (POST):" + e); + } + + // Example 2: Sending a GET request to the second connection + try { + // Set up path and query parameters + Map pathParams = new HashMap<>(); + pathParams.put("", ""); // Replace with actual path parameter + pathParams.put("", ""); // Replace with another path parameter + + Map queryParams = new HashMap<>(); + queryParams.put("", ""); // Replace with actual query parameter + queryParams.put("", ""); // Replace with another query parameter + + // Build and send the GET request + InvokeConnectionRequest invokeConnectionRequest2 = InvokeConnectionRequest.builder() + .method(RequestMethod.GET) // HTTP method set to GET + .pathParams(pathParams) // Include path parameters + .queryParams(queryParams) // Include query parameters + .build(); + + InvokeConnectionResponse invokeConnectionResponse2 = skyflowClient + .connection("").invoke(invokeConnectionRequest2); + System.out.println("Invoke Connection Response (GET): " + invokeConnectionResponse2); + } catch (SkyflowException e) { + System.out.println("Error while invoking connection (GET):" + e); + } + } +} diff --git a/samples/src/main/java/com/example/detect/DeidentifyFileExample.java b/samples/src/main/java/com/example/detect/DeidentifyFileExample.java new file mode 100644 index 00000000..214aa42d --- /dev/null +++ b/samples/src/main/java/com/example/detect/DeidentifyFileExample.java @@ -0,0 +1,114 @@ +package com.example.detect; + +import java.io.File; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.enums.MaskingMethod; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.detect.DeidentifyFileRequest; +import com.skyflow.vault.detect.DeidentifyFileResponse; +import com.skyflow.vault.detect.FileInput; + +/** + * Skyflow Deidentify File Example + *

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

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

+ * This example demonstrates how to: + * 1. Configure credentials + * 2. Set up vault configuration + * 3. Create a get detect run request + * 4. Call getDetectRun to poll for file processing results + * 5. Handle response and errors + */ +public class GetDetectRunExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Configure credentials + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + // Step 2: Configure the vault config + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the ID of the vault + vaultConfig.setClusterId(""); // Replace with the cluster ID of the vault + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate the credentials with the vault + + // Step 3: Create a Skyflow client + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR + .addVaultConfig(vaultConfig) // Add the vault configuration + .build(); + + try { + // Step 4: Create a get detect run request + GetDetectRunRequest getDetectRunRequest = GetDetectRunRequest.builder() + .runId("") // Replace with the runId from deidentifyFile call + .build(); + + // Step 5: Call getDetectRun to poll for file processing results + DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect(vaultConfig.getVaultId()).getDetectRun(getDetectRunRequest); + System.out.println("Get Detect Run Response: " + deidentifyFileResponse); + } catch (SkyflowException e) { + System.err.println("Error occurred during get detect run: "); + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java new file mode 100644 index 00000000..48889218 --- /dev/null +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java @@ -0,0 +1,88 @@ +package com.example.serviceaccount; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.enums.RedactionType; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.tokens.DetokenizeData; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.DetokenizeResponse; +import io.github.cdimascio.dotenv.Dotenv; +import java.util.ArrayList; + +/** + * This example demonstrates how to configure and use the Skyflow SDK + * to detokenize sensitive data stored in a Skyflow vault. + * It includes setting up credentials, configuring the vault, and + * making a detokenization request. The code also implements a retry + * mechanism to handle unauthorized access errors (HTTP 401). + */ +public class BearerTokenExpiryExample { + public static void main(String[] args) { + try { + // Setting up credentials for accessing the Skyflow vault + Credentials vaultCredentials = new Credentials(); + vaultCredentials.setCredentialsString(""); + + // Configuring the Skyflow vault with necessary details + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Vault ID + vaultConfig.setClusterId(""); // Cluster ID + vaultConfig.setEnv(Env.PROD); // Environment (e.g., DEV, PROD) + vaultConfig.setCredentials(vaultCredentials); // Setting credentials + + // Creating a Skyflow client instance with the configured vault + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Setting log level to ERROR + .addVaultConfig(vaultConfig) // Adding vault configuration + .build(); + + // Attempting to detokenize data using the Skyflow client + try { + detokenizeData(skyflowClient); + } catch (SkyflowException e) { + // Retry detokenization if the error is due to unauthorized access (HTTP 401) + if (e.getHttpCode() == 401) { + detokenizeData(skyflowClient); + } else { + // Rethrow the exception for other error codes + throw e; + } + } + } catch (SkyflowException e) { + // Handling any exceptions that occur during the process + System.out.println("An error occurred: " + e.getMessage()); + } + } + + /** + * Method to detokenize data using the Skyflow client. + * It sends a detokenization request with a list of tokens and prints the response. + * + * @param skyflowClient The Skyflow client instance used for detokenization. + * @throws SkyflowException If an error occurs during the detokenization process. + */ + public static void detokenizeData(Skyflow skyflowClient) throws SkyflowException { + // Creating a list of tokens to be detokenized + DetokenizeData detokenizeDataToken1 = new DetokenizeData("", RedactionType.PLAIN_TEXT); + DetokenizeData detokenizeDataToken2 = new DetokenizeData(""); + ArrayList detokenizeDataList = new ArrayList<>(); + detokenizeDataList.add(detokenizeDataToken1); // First token + detokenizeDataList.add(detokenizeDataToken2); // Second token + + // Building a detokenization request with the token list and configuration + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .detokenizeData(detokenizeDataList) // Adding tokens to the request + .continueOnError(false) // Stop on error + .build(); + + // Sending the detokenization request and receiving the response + DetokenizeResponse detokenizeResponse = skyflowClient.vault().detokenize(detokenizeRequest); + + // Printing the detokenized response + System.out.println(detokenizeResponse); + } +} 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..c4578545 --- /dev/null +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java @@ -0,0 +1,66 @@ +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; + +/** + * Example program to generate a Bearer Token using Skyflow's BearerToken utility. + * The token can be generated in two ways: + * 1. Using the file path to a credentials.json file. + * 2. Using the JSON content of the credentials file as a string. + */ +public class BearerTokenGenerationExample { + public static void main(String[] args) { + // Variable to store the generated token + String token = null; + + // Example 1: Generate Bearer Token using a credentials.json file + try { + // Specify the full file path to the credentials.json file + String filePath = ""; + + // Check if the token is either not initialized or has expired + if (Token.isExpired(token)) { + // Create a BearerToken object using the credentials file + BearerToken bearerToken = BearerToken.builder() + .setCredentials(new File(filePath)) // Set credentials from the file path + .build(); + + // Generate a new Bearer Token + token = bearerToken.getBearerToken(); + } + + // Print the generated Bearer Token to the console + System.out.println("Generated Bearer Token (from file): " + token); + } catch (SkyflowException e) { + // Handle any exceptions encountered during the token generation process + e.printStackTrace(); + } + + // Example 2: Generate Bearer Token using the credentials JSON as a string + try { + // Provide the credentials JSON content as a string + String fileContents = ""; + + // Check if the token is either not initialized or has expired + if (Token.isExpired(token)) { + // Create a BearerToken object using the credentials string + BearerToken bearerToken = BearerToken.builder() + .setCredentials(fileContents) // Set credentials from the string + .build(); + + // Generate a new Bearer Token + token = bearerToken.getBearerToken(); + } + + // Print the generated Bearer Token to the console + System.out.println("Generated Bearer Token (from string): " + token); + } catch (SkyflowException e) { + // Handle any exceptions encountered during the token generation process + e.printStackTrace(); + } + } +} 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..30d8f9ba --- /dev/null +++ b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java @@ -0,0 +1,72 @@ +package com.example.serviceaccount; + +import com.skyflow.errors.SkyflowException; +import com.skyflow.serviceaccount.util.BearerToken; + +import java.io.File; + +/** + * This example demonstrates how to generate Bearer tokens in two different ways: + * 1. Using a credentials file specified by its file path. + * 2. Using the credentials as a string. + *

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

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

+ * Signed data tokens are used to verify and securely transmit data with a specified context and TTL. + */ +public class SignedTokenGenerationExample { + public static void main(String[] args) { + List signedTokenValues; // List to store signed data token responses + + // Example 1: Generate Signed Data Token using a credentials file path + try { + // Step 1: Specify the path to the service account credentials JSON file + String filePath = ""; // Replace with the actual file path + + // Step 2: Set the context and create the list of data tokens to be signed + String context = "abc"; // Replace with your specific context (e.g., session identifier) + ArrayList dataTokens = new ArrayList<>(); + dataTokens.add("YOUR_DATA_TOKEN_1"); // Replace with your actual data token(s) + + // Step 3: Build the SignedDataTokens object + SignedDataTokens signedToken = SignedDataTokens.builder() + .setCredentials(new File(filePath)) // Provide the credentials file + .setCtx(context) // Set the context for the token + .setTimeToLive(30) // Set the TTL (in seconds) + .setDataTokens(dataTokens) // Set the data tokens to sign + .build(); + + // Step 4: Retrieve and print the signed data tokens + signedTokenValues = signedToken.getSignedDataTokens(); + System.out.println("Signed Tokens (using file path): " + signedTokenValues); + } catch (SkyflowException e) { + System.out.println("Error occurred while generating signed tokens using file path:"); + e.printStackTrace(); + } + + // Example 2: Generate Signed Data Token using credentials JSON as a string + try { + // Step 1: Provide the contents of the credentials JSON file as a string + String fileContents = ""; // Replace with actual JSON content + + // Step 2: Set the context and create the list of data tokens to be signed + String context = "abc"; // Replace with your specific context + ArrayList dataTokens = new ArrayList<>(); + dataTokens.add("YOUR_DATA_TOKEN_1"); // Replace with your actual data token(s) + + // Step 3: Build the SignedDataTokens object + SignedDataTokens signedToken = SignedDataTokens.builder() + .setCredentials(fileContents) // Provide the credentials as a string + .setCtx(context) // Set the context for the token + .setTimeToLive(30) // Set the TTL (in seconds) + .setDataTokens(dataTokens) // Set the data tokens to sign + .build(); + + // Step 4: Retrieve and print the signed data tokens + signedTokenValues = signedToken.getSignedDataTokens(); + System.out.println("Signed Tokens (using credentials string): " + signedTokenValues); + } catch (SkyflowException e) { + System.out.println("Error occurred while generating signed tokens using credentials string:"); + e.printStackTrace(); + } + } +} diff --git a/samples/src/main/java/com/example/vault/ClientOperations.java b/samples/src/main/java/com/example/vault/ClientOperations.java new file mode 100644 index 00000000..7931db34 --- /dev/null +++ b/samples/src/main/java/com/example/vault/ClientOperations.java @@ -0,0 +1,95 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.DeleteRequest; +import com.skyflow.vault.data.DeleteResponse; + +import java.util.ArrayList; + +/** + * This class demonstrates how to configure and interact with Skyflow vaults using the Skyflow Java SDK. + *

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

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

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

+ * Steps include: + * 1. Setting up Skyflow credentials. + * 2. Configuring the vault. + * 3. Creating a Skyflow client. + * 4. Setting the log level for debugging and error tracking. + * 5. Deleting records from the specified vault(s) using record IDs and table names. + */ +public class DeleteExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up Skyflow credentials + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the actual path to the credentials file + + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the ID of the first vault + vaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate the credentials with the vault + + // Step 3: Set up credentials for the Skyflow client + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(""); // Replace with credentials string + + // Step 4: Create a Skyflow client and add vault configurations + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Set log level for debugging and error tracking + .addVaultConfig(vaultConfig) // Add the vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials + .build(); + + // Step 5: Delete a record from the vault + try { + ArrayList ids = new ArrayList<>(); + ids.add(""); // Replace with the ID of the record to delete + DeleteRequest deleteRequest = DeleteRequest.builder() + .ids(ids) // Specify the record IDs to delete + .table("") // Replace with the table name + .build(); + + DeleteResponse deleteResponse = skyflowClient.vault().delete(deleteRequest); // Perform the delete operation + System.out.println("Delete Response: " + deleteResponse); + } catch (SkyflowException e) { + System.out.println("Error during delete operation in Vault: " + e); + } + } +} 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..ec9c37df --- /dev/null +++ b/samples/src/main/java/com/example/vault/DetokenizeExample.java @@ -0,0 +1,68 @@ +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.DetokenizeData; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.DetokenizeResponse; + +import java.util.ArrayList; + +/** + * This example demonstrates how to use the Skyflow SDK to detokenize sensitive data. + * The steps include: + * 1. Setting up Skyflow credentials. + * 2. Configuring the vault. + * 3. Creating a Skyflow client. + * 4. Detokenizing tokens from specified vaults. + */ +public class DetokenizeExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up Skyflow credentials + Credentials credentials = new Credentials(); + credentials.setToken(""); // Replace with the actual bearer token + + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the ID of the first vault + vaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate the credentials with the vault + + // Step 3: Set up credentials for the Skyflow client + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(""); // Replace with credentials string + + // Step 4: Create a Skyflow client and add vault configurations + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR to capture only critical logs + .addVaultConfig(vaultConfig) // Add the vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials + .build(); + + // Step 5: Detokenize tokens from the vault + try { + ArrayList detokenizeData1 = new ArrayList<>(); + DetokenizeData detokenizeDataRecord1 = new DetokenizeData("", RedactionType.MASKED); // Replace with a token to detokenize with MASKED redaction + DetokenizeData detokenizeDataRecord2 = new DetokenizeData(""); // Replace with another token to detokenize with PLAIN_TEXT redaction + detokenizeData1.add(detokenizeDataRecord1); + detokenizeData1.add(detokenizeDataRecord2); + + DetokenizeRequest detokenizeRequest1 = DetokenizeRequest.builder() + .detokenizeData(detokenizeData1) // Specify detokenize data with specified redaction types + .continueOnError(true) // Continue processing even if an error occurs for some tokens + .build(); + + DetokenizeResponse detokenizeResponse1 = skyflowClient.vault().detokenize(detokenizeRequest1); // Perform detokenization + System.out.println("Detokenize Response (Vault 1): " + detokenizeResponse1); + } catch (SkyflowException e) { + System.out.println("Error during detokenization in Vault 1:"); + e.printStackTrace(); + } + } +} diff --git a/samples/src/main/java/com/example/vault/FileUploadExample.java b/samples/src/main/java/com/example/vault/FileUploadExample.java new file mode 100644 index 00000000..0ad267c2 --- /dev/null +++ b/samples/src/main/java/com/example/vault/FileUploadExample.java @@ -0,0 +1,69 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.FileUploadRequest; +import com.skyflow.vault.data.FileUploadResponse; + +import java.io.File; + +/** + * This example demonstrates how to use the Skyflow SDK to securely upload a file into a vault. + * + * It includes: + * 1. Setting up vault configurations. + * 2. Creating a Skyflow client. + * 3. Uploading a file to the vault. + * 4. Handling errors during the upload process. + */ +public class FileUploadExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the vault configuration + Credentials credentials = new Credentials(); + credentials.setApiKey(""); // Replace with the actual API key + + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with your vault ID + vaultConfig.setClusterId(""); // Replace with your vault cluster ID + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, SANDBOX) + vaultConfig.setCredentials(credentials); // Associate credentials with the vault configuration + + // Step 3: Set up general Skyflow client credentials + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(""); // Replace with the actual credentials string + + // Step 4: Create the Skyflow client and add vault configurations + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR to limit output + .addVaultConfig(vaultConfig) // Add the vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials + .build(); + + // Example: Upload a file to the vault + try { + // Step 5: Specify the file to be uploaded + File file = new File(""); // Replace with the path to the file you want to upload + + // Step 6: Create the file upload request + FileUploadRequest uploadFileRequest = FileUploadRequest.builder() + .fileObject(file) // File object + .table("") // Vault table to upload into + .columnName("") // Column to assign to the uploaded file + .skyflowId("") // Skyflow id of the record + .build(); + + // Step 7: Perform the file upload operation + FileUploadResponse fileUploadResponse = skyflowClient.vault().uploadFile(uploadFileRequest); + System.out.println("File Upload Response: " + fileUploadResponse); + + } catch (SkyflowException e) { + // Handle any errors that occur during the file upload process + System.out.println("Error during file upload: " + e); + } + } +} 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..8d4cee2e --- /dev/null +++ b/samples/src/main/java/com/example/vault/GetExample.java @@ -0,0 +1,82 @@ +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; + +/** + * This example demonstrates how to use the Skyflow SDK to fetch sensitive data securely. + * The steps include: + * 1. Setting up vault configurations. + * 2. Creating a Skyflow client. + * 3. Retrieving records using Skyflow IDs and column values. + */ +public class GetExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the first vault configuration + Credentials credentials = new Credentials(); + credentials.setCredentialsString(""); // Replace with the actual credentials string + + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the ID of the first vault + vaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate the credentials with the vault + + // Step 3: Set up credentials for the Skyflow client + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(""); // Replace with another credentials string + + // Step 4: Create a Skyflow client and add vault configurations + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR to minimize log output + .addVaultConfig(vaultConfig) // Add the first vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials + .build(); + + // Example 1: Fetch records by Skyflow IDs from the vault + try { + ArrayList ids = new ArrayList<>(); + ids.add(""); // Replace with the Skyflow ID to fetch the record + + GetRequest getByIdRequest = GetRequest.builder() + .ids(ids) // Specify the list of Skyflow IDs + .table("") // Replace with the table name + .build(); + + GetResponse getByIdResponse = skyflowClient.vault().get(getByIdRequest); // Fetch via skyflow IDs + System.out.println("Get Response (By ID): " + getByIdResponse); + } catch (SkyflowException e) { + System.out.println("Error during fetch by ID:"); + e.printStackTrace(); + } + + // Example 2: Fetch records by column values from the vault + try { + ArrayList columnValues = new ArrayList<>(); + columnValues.add(""); // Replace with the column value to fetch the record + + GetRequest getByColumnRequest = GetRequest.builder() + .table("") // Replace with the table name + .columnName("") // Replace with the column name + .columnValues(columnValues) // Specify the list of column values + .redactionType(RedactionType.PLAIN_TEXT) // Fetch the data in plain text format + .build(); + + GetResponse getByColumnResponse = skyflowClient.vault().get(getByColumnRequest); // Fetch via column values + System.out.println("Get Response (By Column): " + getByColumnResponse); + } catch (SkyflowException e) { + System.out.println("Error during fetch by column:"); + e.printStackTrace(); + } + } +} diff --git a/samples/src/main/java/com/example/vault/InsertExample.java b/samples/src/main/java/com/example/vault/InsertExample.java new file mode 100644 index 00000000..a6b4ca83 --- /dev/null +++ b/samples/src/main/java/com/example/vault/InsertExample.java @@ -0,0 +1,99 @@ +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.TokenMode; +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; + +/** + * This example demonstrates how to use the Skyflow SDK to securely insert records into a vault. + * It includes: + * 1. Setting up vault configurations. + * 2. Creating a Skyflow client. + * 3. Performing record insertion with and without TokenMode. + * 4. Using upsert functionality to handle conflicts. + */ +public class InsertExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the first vault configuration + Credentials credentials = new Credentials(); + credentials.setApiKey(""); // Replace with the actual API key + + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the vault ID + vaultConfig.setClusterId(""); // Replace with the first vault cluster ID + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, SANDBOX) + vaultConfig.setCredentials(credentials); // Associate credentials with the vault + + // Step 3: Set up credentials for the Skyflow client + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(""); // Replace with the actual credentials string + + // Step 4: Create a Skyflow client and add vault configurations + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR to limit output + .addVaultConfig(vaultConfig) // Add the vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials + .build(); + + // Example 1: Insert records into the vault with TokenMode enabled + try { + ArrayList> values1 = new ArrayList<>(); + HashMap value1 = new HashMap<>(); + value1.put("", ""); // Replace with actual column name and value + value1.put("", ""); // Replace with actual column name and value + values1.add(value1); + + ArrayList> tokens = new ArrayList<>(); + HashMap token = new HashMap<>(); + token.put("", ""); // Replace with actual token value for COLUMN_NAME_2 + tokens.add(token); + + InsertRequest insertRequest = InsertRequest.builder() + .table("") // Replace with the actual table name + .continueOnError(true) // Continue inserting even if some records fail + .tokenMode(TokenMode.ENABLE) // Enable TokenMode for token validation + .values(values1) // Data to insert + .tokens(tokens) // Provide tokens for TokenMode columns + .returnTokens(true) // Return tokens in the response + .build(); + + InsertResponse insertResponse = skyflowClient.vault().insert(insertRequest); // Perform the insertion + System.out.println("Insert Response (TokenMode Enabled): " + insertResponse); + } catch (SkyflowException e) { + System.out.println("Error during insertion with TokenMode enabled:" + e); + } + + // Example 2: Insert records into the vault with TokenMode disabled and upsert enabled + try { + ArrayList> values2 = new ArrayList<>(); + HashMap value2 = new HashMap<>(); + value2.put("", ""); // Replace with actual column name and value + value2.put("", ""); // Replace with actual column name and value + values2.add(value2); + + InsertRequest upsertRequest = InsertRequest.builder() + .table("") // Replace with the actual table name + .continueOnError(false) // Stop inserting if any record fails + .tokenMode(TokenMode.DISABLE) // Disable TokenMode + .values(values2) // Data to insert + .returnTokens(false) // Do not return tokens + .upsert("") // Replace with the actual column name used for upsert logic + .build(); + + InsertResponse upsertResponse = skyflowClient.vault().insert(upsertRequest); // Perform upsert operation + System.out.println("Insert Response (Upsert Enabled): " + upsertResponse); + } catch (SkyflowException e) { + System.out.println("Error during insertion with upsert enabled:" + e); + } + } +} \ No newline at end of file diff --git a/samples/src/main/java/com/example/vault/QueryExample.java b/samples/src/main/java/com/example/vault/QueryExample.java new file mode 100644 index 00000000..bde5c697 --- /dev/null +++ b/samples/src/main/java/com/example/vault/QueryExample.java @@ -0,0 +1,56 @@ +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; + +/** + * This example demonstrates how to use the Skyflow SDK to perform secure queries on a vault. + * It includes: + * 1. Setting up vault configurations. + * 2. Creating a Skyflow client. + * 3. Performing SQL queries on the vault. + */ +public class QueryExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the vault configuration + Credentials credentials = new Credentials(); + credentials.setApiKey(""); // Replace with the actual API key + + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the ID of the vault + vaultConfig.setClusterId(""); // Replace with the cluster ID of the vault + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate the credentials with the vault + + // Step 3: Set up credentials for the Skyflow client + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(""); // Replace with the actual credentials string + + // Step 4: Create a Skyflow client and add vault configuration + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Set log level to ERROR for minimal logging + .addVaultConfig(vaultConfig) // Add the vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials + .build(); + + // Example: Perform a query on the vault + try { + String query = ""; // Replace with a valid SQL query for the vault + QueryRequest queryRequest = QueryRequest.builder() + .query(query) // Build the query request + .build(); + + QueryResponse queryResponse = skyflowClient.vault().query(queryRequest); // Execute the query + System.out.println("Query Response: " + queryResponse); // Print the query response + } catch (SkyflowException e) { + System.out.println("Error while querying the vault: " + e); + } + } +} diff --git a/samples/src/main/java/com/example/vault/TokenizeExample.java b/samples/src/main/java/com/example/vault/TokenizeExample.java new file mode 100644 index 00000000..2c390be8 --- /dev/null +++ b/samples/src/main/java/com/example/vault/TokenizeExample.java @@ -0,0 +1,63 @@ +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; + +/** + * This example demonstrates how to use the Skyflow SDK to tokenize data using a vault configuration. + * It includes: + * 1. Setting up a vault configuration. + * 2. Creating a Skyflow client. + * 3. Performing tokenization. + */ +public class TokenizeExample { + public static void main(String[] args) { + try { + // Step 1: Set up credentials + Credentials credentials = new Credentials(); + credentials.setPath(""); // Replace with the path to the credentials file + + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the vault ID + vaultConfig.setClusterId(""); // Replace with the cluster ID + vaultConfig.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate credentials with the vault + + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(""); // Replace with the actual credentials string + + // Step 3: Create a Skyflow client + Skyflow skyflowClient = Skyflow.builder().setLogLevel(LogLevel.ERROR) // Set log level + .addVaultConfig(vaultConfig) // Add vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials + .build(); + + // Step 4: Prepare data for tokenization + ArrayList columnValues = new ArrayList<>(); + columnValues.add(ColumnValue.builder().value("") // Replace with the actual value to tokenize + .columnGroup("") // Replace with the actual column group name + .build()); + columnValues.add(ColumnValue.builder().value("") // Replace with another value to tokenize + .columnGroup("") // Replace with the column group name + .build()); + + // Step 5: Build and execute the tokenization request + TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); + + TokenizeResponse tokenizeResponse = skyflowClient.vault().tokenize(tokenizeRequest); + System.out.println("Tokenization Response: " + tokenizeResponse); + } catch (SkyflowException e) { + System.out.println("Error while tokenizing data for Vault:" + e); + } + } +} diff --git a/samples/src/main/java/com/example/vault/UpdateExample.java b/samples/src/main/java/com/example/vault/UpdateExample.java new file mode 100644 index 00000000..a5947780 --- /dev/null +++ b/samples/src/main/java/com/example/vault/UpdateExample.java @@ -0,0 +1,91 @@ +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.TokenMode; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.UpdateRequest; +import com.skyflow.vault.data.UpdateResponse; + +import java.util.HashMap; + +/** + * This example demonstrates how to use the Skyflow SDK to securely update records in a vault. + * It includes: + * 1. Setting up vault configurations. + * 2. Creating a Skyflow client. + * 3. Updating records with and without TokenMode. + */ +public class UpdateExample { + public static void main(String[] args) throws SkyflowException { + // Step 1: Set up credentials for the first vault configuration + Credentials credentials = new Credentials(); + credentials.setApiKey(""); // Replace with the actual API key + + // Step 2: Configure the vault + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); // Replace with the ID of the vault + vaultConfig.setClusterId(""); // Replace with the cluster ID of the vault + vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) + vaultConfig.setCredentials(credentials); // Associate the credentials with the vault + + // Step 3: Set up credentials for the Skyflow client + Credentials skyflowCredentials = new Credentials(); + skyflowCredentials.setCredentialsString(""); // Replace with the actual credentials string + + // Step 4: Create a Skyflow client and add vault configurations + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) // Enable debugging for detailed logs + .addVaultConfig(vaultConfig) // Add the vault configuration + .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials + .build(); + + // Step 5: Update records with TokenMode enabled + try { + HashMap data1 = new HashMap<>(); + data1.put("skyflow_id", ""); // Replace with the Skyflow ID of the record + data1.put("", ""); // Replace with column name and value to update + data1.put("", ""); // Replace with another column name and value + + HashMap tokens = new HashMap<>(); + tokens.put("", ""); // Replace with the token for COLUMN_NAME_2 + + UpdateRequest updateRequest1 = UpdateRequest.builder() + .table("") // Replace with the table name + .tokenMode(TokenMode.ENABLE) // Enable TokenMode for token validation + .data(data1) // Data to update + .tokens(tokens) // Provide tokens for TokenMode columns + .returnTokens(true) // Return tokens along with the update response + .build(); + + UpdateResponse updateResponse1 = skyflowClient.vault().update(updateRequest1); // Perform the update + System.out.println("Update Response (TokenMode Enabled): " + updateResponse1); + } catch (SkyflowException e) { + System.out.println("Error during update with TokenMode enabled:"); + e.printStackTrace(); + } + + // Step 6: Update records with TokenMode disabled + try { + HashMap data2 = new HashMap<>(); + data2.put("skyflow_id", ""); // Replace with the Skyflow ID of the record + data2.put("", ""); // Replace with column name and value to update + data2.put("", ""); // Replace with another column name and value + + UpdateRequest updateRequest2 = UpdateRequest.builder() + .table("") // Replace with the table name + .tokenMode(TokenMode.DISABLE) // Disable TokenMode + .data(data2) // Data to update + .returnTokens(false) // Do not return tokens + .build(); + + UpdateResponse updateResponse2 = skyflowClient.vault().update(updateRequest2); // Perform the update + System.out.println("Update Response (TokenMode Disabled): " + updateResponse2); + } catch (SkyflowException e) { + System.out.println("Error during update with TokenMode disabled:" + e); + } + } +} diff --git a/scripts/bump_version.sh b/scripts/bump_version.sh old mode 100644 new mode 100755 index 008cae3f..d729ea63 --- a/scripts/bump_version.sh +++ b/scripts/bump_version.sh @@ -37,4 +37,4 @@ else echo "--------------------------" echo "Done. Main project version now at $Version-dev.$CommitHash" -fi \ No newline at end of file +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..7cb10713 --- /dev/null +++ b/src/main/java/com/skyflow/ConnectionClient.java @@ -0,0 +1,94 @@ +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; +import io.github.cdimascio.dotenv.DotenvException; + +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) throws SkyflowException { + this.commonCredentials = commonCredentials; + prioritiseCredentials(); + } + + protected void updateConnectionConfig(ConnectionConfig connectionConfig) throws SkyflowException { + prioritiseCredentials(); + } + + protected void setBearerToken() throws SkyflowException { + prioritiseCredentials(); + Validations.validateCredentials(this.finalCredentials); + if (this.finalCredentials.getApiKey() != null) { + setApiKey(); + } 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() throws SkyflowException { + try { + Credentials original = this.finalCredentials; + 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); + } + } + if (original != null && !original.equals(this.finalCredentials)) { + token = null; + apiKey = null; + } + } catch (DotenvException e) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.EmptyCredentials.getMessage()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/src/main/java/com/skyflow/Skyflow.java b/src/main/java/com/skyflow/Skyflow.java new file mode 100644 index 00000000..8e51da57 --- /dev/null +++ b/src/main/java/com/skyflow/Skyflow.java @@ -0,0 +1,307 @@ +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.DetectController; +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() throws SkyflowException { + Object[] array = this.builder.vaultClientsMap.keySet().toArray(); + if (array.length < 1) { + LogUtil.printErrorLog(ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultIdNotInConfigList.getMessage()); + } + String vaultId = (String) array[0]; + return this.vault(vaultId); + } + + public VaultController vault(String vaultId) throws SkyflowException { + VaultController controller = this.builder.vaultClientsMap.get(vaultId); + if (controller == null) { + LogUtil.printErrorLog(ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultIdNotInConfigList.getMessage()); + } + return controller; + } + + + public ConnectionController connection() throws SkyflowException { + Object[] array = this.builder.connectionsMap.keySet().toArray(); + if (array.length < 1) { + LogUtil.printErrorLog(ErrorLogs.CONNECTION_CONFIG_DOES_NOT_EXIST.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ConnectionIdNotInConfigList.getMessage()); + } + String connectionId = (String) array[0]; + return this.connection(connectionId); + } + + public ConnectionController connection(String connectionId) throws SkyflowException { + ConnectionController controller = this.builder.connectionsMap.get(connectionId); + if (controller == null) { + LogUtil.printErrorLog(ErrorLogs.CONNECTION_CONFIG_DOES_NOT_EXIST.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ConnectionIdNotInConfigList.getMessage()); + } + return controller; + } + + public DetectController detect() throws SkyflowException { + Object[] array = this.builder.detectClientsMap.keySet().toArray(); + if (array.length < 1) { + LogUtil.printErrorLog(ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultIdNotInConfigList.getMessage()); + } + String detectId = (String) array[0]; + return this.detect(detectId); + } + + public DetectController detect(String vaultId) throws SkyflowException { + DetectController controller = this.builder.detectClientsMap.get(vaultId); + if (controller == null) { + LogUtil.printErrorLog(ErrorLogs.VAULT_CONFIG_DOES_NOT_EXIST.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultIdNotInConfigList.getMessage()); + } + return controller; + } + + public static final class SkyflowClientBuilder { + private final LinkedHashMap connectionsMap; + private final LinkedHashMap vaultClientsMap; + private final LinkedHashMap detectClientsMap; + private final LinkedHashMap vaultConfigMap; + private final LinkedHashMap connectionConfigMap; + private Credentials skyflowCredentials; + private LogLevel logLevel; + + public SkyflowClientBuilder() { + this.vaultClientsMap = new LinkedHashMap<>(); + this.detectClientsMap = 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)); + this.detectClientsMap.put(vaultConfig.getVaultId(), new DetectController(vaultConfig, this.skyflowCredentials)); + LogUtil.printInfoLog(Utils.parameterizedString( + InfoLogs.VAULT_CONTROLLER_INITIALIZED.getLog(), vaultConfig.getVaultId())); + LogUtil.printInfoLog(Utils.parameterizedString( + InfoLogs.DETECT_CONTROLLER_INITIALIZED.getLog(), vaultConfig.getVaultId())); + } + return this; + } + + 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 (DetectController detect : this.detectClientsMap.values()) { + detect.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..edb8ee47 --- /dev/null +++ b/src/main/java/com/skyflow/VaultClient.java @@ -0,0 +1,831 @@ +package com.skyflow; + +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.DetectEntities; +import com.skyflow.enums.DetectOutputTranscriptions; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.generated.rest.ApiClientBuilder; +import com.skyflow.generated.rest.resources.files.FilesClient; +import com.skyflow.generated.rest.resources.files.requests.*; +import com.skyflow.generated.rest.resources.files.types.*; +import com.skyflow.generated.rest.resources.query.QueryClient; +import com.skyflow.generated.rest.resources.records.RecordsClient; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.resources.records.requests.UploadFileV2Request; +import com.skyflow.generated.rest.resources.strings.StringsClient; +import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; +import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; +import com.skyflow.generated.rest.resources.strings.types.ReidentifyStringRequestFormat; +import com.skyflow.generated.rest.resources.tokens.TokensClient; +import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; +import com.skyflow.generated.rest.types.*; +import com.skyflow.generated.rest.types.Transformations; +import com.skyflow.logs.InfoLogs; +import com.skyflow.serviceaccount.util.Token; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.logger.LogUtil; +import com.skyflow.utils.validations.Validations; +import com.skyflow.vault.data.FileUploadRequest; +import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.UpdateRequest; +import com.skyflow.vault.detect.*; +import com.skyflow.vault.detect.DeidentifyFileRequest; +import com.skyflow.vault.detect.DeidentifyTextRequest; +import com.skyflow.vault.tokens.ColumnValue; +import com.skyflow.vault.tokens.DetokenizeData; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.TokenizeRequest; +import io.github.cdimascio.dotenv.Dotenv; +import io.github.cdimascio.dotenv.DotenvException; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.*; +import java.util.stream.Collectors; + + +public class VaultClient { + private final VaultConfig vaultConfig; + private final ApiClientBuilder apiClientBuilder; + private ApiClient apiClient; + 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.apiClientBuilder = new ApiClientBuilder(); + this.apiClient = null; + updateVaultURL(); + } + + protected RecordsClient getRecordsApi() { + return this.apiClient.records(); + } + + protected TokensClient getTokensApi() { + return this.apiClient.tokens(); + } + + protected StringsClient getDetectTextApi() { + return this.apiClient.strings(); + } + + protected FilesClient getDetectFileAPi(){ + return this.apiClient.files(); + } + + protected QueryClient getQueryApi() { + return this.apiClient.query(); + } + + protected VaultConfig getVaultConfig() { + return vaultConfig; + } + + protected void setCommonCredentials(Credentials commonCredentials) throws SkyflowException { + this.commonCredentials = commonCredentials; + prioritiseCredentials(); + } + + protected void updateVaultConfig() throws SkyflowException { + updateVaultURL(); + prioritiseCredentials(); + } + + protected V1DetokenizePayload getDetokenizePayload(DetokenizeRequest request) { + List recordRequests = new ArrayList<>(); + + for (DetokenizeData detokenizeDataRecord : request.getDetokenizeData()) { + V1DetokenizeRecordRequest recordRequest = V1DetokenizeRecordRequest.builder() + .token(detokenizeDataRecord.getToken()) + .redaction(detokenizeDataRecord.getRedactionType().getRedaction()) + .build(); + recordRequests.add(recordRequest); + } + + return V1DetokenizePayload.builder() + .continueOnError(request.getContinueOnError()) + .downloadUrl(request.getDownloadURL()) + .detokenizationParameters(recordRequests) + .build(); + } + + protected RecordServiceInsertRecordBody getBulkInsertRequestBody(InsertRequest request) { + List> values = request.getValues(); + List> tokens = request.getTokens(); + List records = new ArrayList<>(); + + for (int index = 0; index < values.size(); index++) { + V1FieldRecords.Builder recordBuilder = V1FieldRecords.builder().fields(values.get(index)); + if (tokens != null && index < tokens.size()) { + recordBuilder.tokens(tokens.get(index)); + } + records.add(recordBuilder.build()); + } + + return RecordServiceInsertRecordBody.builder() + .tokenization(request.getReturnTokens()) + .homogeneous(request.getHomogeneous()) + .upsert(request.getUpsert()) + .byot(request.getTokenMode().getBYOT()) + .records(records) + .build(); + } + + protected RecordServiceBatchOperationBody getBatchInsertRequestBody(InsertRequest request) { + ArrayList> values = request.getValues(); + ArrayList> tokens = request.getTokens(); + List records = new ArrayList<>(); + + for (int index = 0; index < values.size(); index++) { + V1BatchRecord.Builder recordBuilder = V1BatchRecord.builder() + .method(BatchRecordMethod.POST) + .tableName(request.getTable()) + .upsert(request.getUpsert()) + .tokenization(request.getReturnTokens()) + .fields(values.get(index)); + + if (tokens != null && index < tokens.size()) { + recordBuilder.tokens(tokens.get(index)); + } + + records.add(recordBuilder.build()); + } + + return RecordServiceBatchOperationBody.builder() + .continueOnError(true) + .byot(request.getTokenMode().getBYOT()) + .records(records) + .build(); + } + + protected RecordServiceUpdateRecordBody getUpdateRequestBody(UpdateRequest request) { + RecordServiceUpdateRecordBody.Builder updateRequestBodyBuilder = RecordServiceUpdateRecordBody.builder(); + updateRequestBodyBuilder.byot(request.getTokenMode().getBYOT()); + updateRequestBodyBuilder.tokenization(request.getReturnTokens()); + V1FieldRecords.Builder recordBuilder = V1FieldRecords.builder(); + HashMap values = request.getData(); + + if (values != null) { + recordBuilder.fields(values); + } + + HashMap tokens = request.getTokens(); + if (tokens != null) { + recordBuilder.tokens(tokens); + } + + updateRequestBodyBuilder.record(recordBuilder.build()); + + return updateRequestBodyBuilder.build(); + } + + protected V1TokenizePayload getTokenizePayload(TokenizeRequest request) { + List tokenizationParameters = new ArrayList<>(); + + for (ColumnValue columnValue : request.getColumnValues()) { + V1TokenizeRecordRequest.Builder recordBuilder = V1TokenizeRecordRequest.builder(); + String value = columnValue.getValue(); + recordBuilder.value(value); + String columnGroup = columnValue.getColumnGroup(); + recordBuilder.columnGroup(columnGroup); + tokenizationParameters.add(recordBuilder.build()); + } + + V1TokenizePayload.Builder payloadBuilder = V1TokenizePayload.builder(); + + if (!tokenizationParameters.isEmpty()) { + payloadBuilder.tokenizationParameters(tokenizationParameters); + } + + return payloadBuilder.build(); + } + + protected File getFileForFileUpload(FileUploadRequest fileUploadRequest) throws IOException { + if (fileUploadRequest.getFilePath() != null) { + return new File(fileUploadRequest.getFilePath()); + } + else if (fileUploadRequest.getBase64() != null) { + byte[] decodedBytes = Base64.getDecoder().decode(fileUploadRequest.getBase64()); + File file = new File(fileUploadRequest.getFileName()); + Files.write(file.toPath(), decodedBytes); + return file; + } + else if (fileUploadRequest.getFileObject() != null) { + return fileUploadRequest.getFileObject(); + } + return null; + } + + protected void setBearerToken() throws SkyflowException { + prioritiseCredentials(); + Validations.validateCredentials(this.finalCredentials); + if (this.finalCredentials.getApiKey() != null) { + LogUtil.printInfoLog(InfoLogs.REUSE_API_KEY.getLog()); + token=this.finalCredentials.getApiKey(); + } else if (Token.isExpired(token)) { + LogUtil.printInfoLog(InfoLogs.BEARER_TOKEN_EXPIRED.getLog()); + token = Utils.generateBearerToken(this.finalCredentials); + } else { + LogUtil.printInfoLog(InfoLogs.REUSE_BEARER_TOKEN.getLog()); + } + this.apiClientBuilder.token(token); + this.apiClient = this.apiClientBuilder.build(); + } + + protected DeidentifyTextResponse getDeIdentifyTextResponse(DeidentifyStringResponse deidentifyStringResponse) { + List entities = deidentifyStringResponse.getEntities() != null + ? deidentifyStringResponse.getEntities().stream() + .map(this::convertDetectedEntityToEntityInfo) + .collect(Collectors.toList()) + : null; + + return new DeidentifyTextResponse( + deidentifyStringResponse.getProcessedText(), + entities, + deidentifyStringResponse.getWordCount(), + deidentifyStringResponse.getCharacterCount() + ); + } + + protected DeidentifyStringRequest getDeidentifyStringRequest(DeidentifyTextRequest deIdentifyTextRequest, String vaultId) throws SkyflowException { + List entities = deIdentifyTextRequest.getEntities(); + + List mappedEntityTypes = null; + if (entities != null) { + mappedEntityTypes = deIdentifyTextRequest.getEntities().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList()); + } + + TokenFormat tokenFormat = deIdentifyTextRequest.getTokenFormat(); + + Optional> vaultToken = Optional.empty(); + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(deIdentifyTextRequest.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(deIdentifyTextRequest.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(deIdentifyTextRequest.getTransformations())); + + if (tokenFormat != null) { + if (tokenFormat.getVaultToken() != null && !tokenFormat.getVaultToken().isEmpty()) { + vaultToken = Optional.of(tokenFormat.getVaultToken().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { + entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { + entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + } + + TokenType tokenType = TokenType.builder() + .vaultToken(vaultToken) + .entityOnly(entityTypes) + .entityUnqCounter(entityUniqueCounter) + .build(); + + + return DeidentifyStringRequest.builder() + .vaultId(vaultId) + .text(deIdentifyTextRequest.getText()) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .transformations(transformations) + .build(); + } + + protected ReidentifyStringRequest getReidentifyStringRequest(ReidentifyTextRequest reidentifyTextRequest, String vaultId) throws SkyflowException { + List maskEntities = null; + List redactedEntities = null; + List plaintextEntities = null; + + if (reidentifyTextRequest.getMaskedEntities() != null) { + maskEntities = reidentifyTextRequest.getMaskedEntities().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList()); + } + + if (reidentifyTextRequest.getPlainTextEntities() != null) { + plaintextEntities = reidentifyTextRequest.getPlainTextEntities().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList()); + } + + if (reidentifyTextRequest.getRedactedEntities() != null) { + redactedEntities = reidentifyTextRequest.getRedactedEntities().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList()); + } + + ReidentifyStringRequestFormat reidentifyStringRequestFormat = ReidentifyStringRequestFormat.builder() + .masked(maskEntities) + .plaintext(plaintextEntities) + .redacted(redactedEntities) + .build(); + + + return ReidentifyStringRequest.builder() + .text(reidentifyTextRequest.getText()) + .vaultId(vaultId) + .format(reidentifyStringRequestFormat) + .build(); + } + + + private EntityInfo convertDetectedEntityToEntityInfo(DetectedEntity detectedEntity) { + TextIndex textIndex = new TextIndex( + detectedEntity.getLocation().get().getStartIndex().orElse(0), + detectedEntity.getLocation().get().getEndIndex().orElse(0) + ); + TextIndex processedIndex = new TextIndex( + detectedEntity.getLocation().get().getStartIndexProcessed().orElse(0), + detectedEntity.getLocation().get().getEndIndexProcessed().orElse(0) + ); + + Map entityScores = detectedEntity.getEntityScores() + .map(doubleMap -> doubleMap.entrySet().stream() + .collect(Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue + ))) + .orElse(Collections.emptyMap()); + + + return new EntityInfo( + detectedEntity.getToken().orElse(""), + detectedEntity.getValue().orElse(""), + textIndex, + processedIndex, + detectedEntity.getEntityType().orElse(""), + entityScores); + } + + + private Transformations getTransformations(com.skyflow.vault.detect.Transformations transformations) { + if (transformations == null || transformations.getShiftDates() == null) { + return null; + } + + List entityTypes = null; + if (!transformations.getShiftDates().getEntities().isEmpty()) { + entityTypes = transformations.getShiftDates().getEntities().stream() + .map(entity -> TransformationsShiftDatesEntityTypesItem.valueOf(entity.name())) + .collect(Collectors.toList()); + } else { + entityTypes = Collections.emptyList(); + } + + return Transformations.builder() + .shiftDates(TransformationsShiftDates.builder() + .maxDays(transformations.getShiftDates().getMax()) + .minDays(transformations.getShiftDates().getMin()) + .entityTypes(entityTypes) + .build()) + .build(); + } + + private List getEntityTypes(List entities){ + List mappedEntityTypes = null; + if (entities != null) { + mappedEntityTypes = entities.stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList()); + } + + return mappedEntityTypes; + } + + protected com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest getDeidentifyTextFileRequest(DeidentifyFileRequest request, String vaultId, String base64Content){ + List mappedEntityTypes = getEntityTypes(request.getEntities()); + + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); + + if (tokenFormat != null) { + + if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { + entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { + entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + } + + TokenTypeWithoutVault tokenType = TokenTypeWithoutVault.builder() + .entityOnly(entityTypes) + .entityUnqCounter(entityUniqueCounter) + .build(); + + DeidentifyTextRequestFile file = DeidentifyTextRequestFile.builder() + .base64(base64Content) + .build(); + + // Build the final request + com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest req = + com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .transformations(transformations) + .build(); + + return req; + } + + + protected DeidentifyAudioRequest getDeidentifyAudioRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String dataFormat) throws SkyflowException { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); + + if (tokenFormat != null) { + + if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { + entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { + entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + } + + TokenTypeWithoutVault tokenType = TokenTypeWithoutVault.builder() + .entityOnly(entityTypes) + .entityUnqCounter(entityUniqueCounter) + .build(); + + DeidentifyAudioRequestFile deidentifyAudioRequestFile = DeidentifyAudioRequestFile.builder().base64(base64Content).dataFormat(mapAudioDataFormat(dataFormat)).build(); + DetectOutputTranscriptions transcription = request.getOutputTranscription(); + DeidentifyAudioRequestOutputTranscription outputTranscriptionType = null; + if (transcription != null) { + outputTranscriptionType = DeidentifyAudioRequestOutputTranscription.valueOf(transcription.name()); + } + + return DeidentifyAudioRequest.builder() + .vaultId(vaultId) + .file(deidentifyAudioRequestFile) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .entityTypes(mappedEntityTypes) + .bleepFrequency(request.getBleep() != null ? request.getBleep().getFrequency() : null) + .bleepGain(request.getBleep() != null ? request.getBleep().getGain() : null) + .bleepStartPadding(request.getBleep() != null ? request.getBleep().getStartPadding() : null) + .bleepStopPadding(request.getBleep() != null ? request.getBleep().getStopPadding() : null) + .outputProcessedAudio(request.getOutputProcessedAudio()) + .outputTranscription(outputTranscriptionType) + .tokenType(tokenType) + .transformations(transformations) + .build(); + } + + protected DeidentifyPdfRequest getDeidentifyPdfRequest(DeidentifyFileRequest request, String vaultId, String base64Content) { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + + TokenFormat tokenFormat = request.getTokenFormat(); + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + + if (tokenFormat != null) { + if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { + entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { + entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + } + + TokenTypeWithoutVault tokenType = TokenTypeWithoutVault.builder() + .entityOnly(entityTypes) + .entityUnqCounter(entityUniqueCounter) + .build(); + + DeidentifyPdfRequestFile file = DeidentifyPdfRequestFile.builder() + .base64(base64Content) + .build(); + + return DeidentifyPdfRequest.builder() + .vaultId(vaultId) + .file(file) + .density(request.getPixelDensity() != null ? request.getPixelDensity().doubleValue() : null) + .maxResolution(request.getMaxResolution() != null ? request.getMaxResolution().doubleValue() : null) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .build(); + } + + protected DeidentifyImageRequest getDeidentifyImageRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + + TokenFormat tokenFormat = request.getTokenFormat(); + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + + TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); + + DeidentifyImageRequestFile file = DeidentifyImageRequestFile.builder() + .base64(base64Content) + .dataFormat(DeidentifyImageRequestFileDataFormat.valueOf(format.toUpperCase())) + .build(); + + Optional maskingMethod = Optional.empty(); + if (request.getMaskingMethod() != null) { + maskingMethod = Optional.of(DeidentifyImageRequestMaskingMethod.valueOf(request.getMaskingMethod().name())); + } + + return DeidentifyImageRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .maskingMethod(maskingMethod) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .outputProcessedImage(request.getOutputProcessedImage()) + .outputOcrText(request.getOutputOcrText()) + .build(); + } + + protected DeidentifyPresentationRequest getDeidentifyPresentationRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + + TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); + + DeidentifyPresentationRequestFile file = DeidentifyPresentationRequestFile.builder() + .base64(base64Content) + .dataFormat(DeidentifyPresentationRequestFileDataFormat.valueOf(format.toUpperCase())) + .build(); + + return DeidentifyPresentationRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .build(); + } + + protected DeidentifySpreadsheetRequest getDeidentifySpreadsheetRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + + TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); + + DeidentifySpreadsheetRequestFile file = DeidentifySpreadsheetRequestFile.builder() + .base64(base64Content) + .dataFormat(DeidentifySpreadsheetRequestFileDataFormat.valueOf(format.toUpperCase())) + .build(); + + return DeidentifySpreadsheetRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .build(); + } + + protected DeidentifyStructuredTextRequest getDeidentifyStructuredTextRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); + + TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); + + DeidentifyStructuredTextRequestFile file = DeidentifyStructuredTextRequestFile.builder() + .base64(base64Content) + .dataFormat(DeidentifyStructuredTextRequestFileDataFormat.valueOf(format.toUpperCase())) + .build(); + + return DeidentifyStructuredTextRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .transformations(transformations) + .build(); + } + + protected DeidentifyDocumentRequest getDeidentifyDocumentRequest(DeidentifyFileRequest request, String vaultId, String base64Content, String format) { + List mappedEntityTypes = getEntityTypes(request.getEntities()); + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + + TokenTypeWithoutVault tokenType = buildTokenType(tokenFormat, entityTypes, entityUniqueCounter); + + DeidentifyDocumentRequestFile file = DeidentifyDocumentRequestFile.builder() + .base64(base64Content) + .dataFormat(DeidentifyDocumentRequestFileDataFormat.valueOf(format.toUpperCase())) + .build(); + + return DeidentifyDocumentRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .build(); + } + + protected com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest getDeidentifyGenericFileRequest( + DeidentifyFileRequest request, String vaultId, String base64Content, String fileExtension) { + + List mappedEntityTypes = getEntityTypes(request.getEntities()); + + TokenFormat tokenFormat = request.getTokenFormat(); + + Optional> entityTypes = Optional.empty(); + Optional> entityUniqueCounter = Optional.empty(); + Optional> allowRegex = Optional.ofNullable(request.getAllowRegexList()); + Optional> restrictRegex = Optional.ofNullable(request.getRestrictRegexList()); + Optional transformations = Optional.ofNullable(getTransformations(request.getTransformations())); + + if (tokenFormat != null) { + if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { + entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { + entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + } + + TokenTypeWithoutVault tokenType = TokenTypeWithoutVault.builder() + .entityOnly(entityTypes) + .entityUnqCounter(entityUniqueCounter) + .build(); + + DeidentifyFileRequestFile file = + DeidentifyFileRequestFile.builder() + .base64(base64Content) + .dataFormat(fileExtension != null ? DeidentifyFileRequestFileDataFormat.valueOf(fileExtension.toUpperCase()) : null) + .build(); + + return com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest.builder() + .vaultId(vaultId) + .file(file) + .entityTypes(mappedEntityTypes) + .tokenType(tokenType) + .allowRegex(allowRegex) + .restrictRegex(restrictRegex) + .transformations(transformations) + .build(); + } + + private TokenTypeWithoutVault buildTokenType(TokenFormat tokenFormat, + Optional> entityTypes, + Optional> entityUniqueCounter) { + + if (tokenFormat != null) { + if (tokenFormat.getEntityOnly() != null && !tokenFormat.getEntityOnly().isEmpty()) { + entityTypes = Optional.of(tokenFormat.getEntityOnly().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + + if (tokenFormat.getEntityUniqueCounter() != null && !tokenFormat.getEntityUniqueCounter().isEmpty()) { + entityUniqueCounter = Optional.of(tokenFormat.getEntityUniqueCounter().stream() + .map(detectEntity -> EntityType.valueOf(detectEntity.name())) + .collect(Collectors.toList())); + } + } + + return TokenTypeWithoutVault.builder() + .entityOnly(entityTypes) + .entityUnqCounter(entityUniqueCounter) + .build(); + } + + private DeidentifyAudioRequestFileDataFormat mapAudioDataFormat(String dataFormat) throws SkyflowException { + switch (dataFormat) { + case "mp3": + return DeidentifyAudioRequestFileDataFormat.MP_3; + case "wav": + return DeidentifyAudioRequestFileDataFormat.WAV; + default: + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidAudioFileType.getMessage()); + } + } + + private void updateVaultURL() { + String vaultURL = Utils.getVaultURL(this.vaultConfig.getClusterId(), this.vaultConfig.getEnv()); + this.apiClientBuilder.url(vaultURL); + } + + private void prioritiseCredentials() throws SkyflowException { + try { + Credentials original = this.finalCredentials; + if (this.vaultConfig.getCredentials() != null) { + this.finalCredentials = this.vaultConfig.getCredentials(); + } else if (this.commonCredentials != null) { + 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); + } + } + if (original != null && !original.equals(this.finalCredentials)) { + token = null; + apiKey = null; + } + } catch (DotenvException e) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.EmptyCredentials.getMessage()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/com/skyflow/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..4f61af2a --- /dev/null +++ b/src/main/java/com/skyflow/config/VaultConfig.java @@ -0,0 +1,49 @@ +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; + } +} 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/DeidentifyFileStatus.java b/src/main/java/com/skyflow/enums/DeidentifyFileStatus.java new file mode 100644 index 00000000..87ffc109 --- /dev/null +++ b/src/main/java/com/skyflow/enums/DeidentifyFileStatus.java @@ -0,0 +1,18 @@ +package com.skyflow.enums; + +public enum DeidentifyFileStatus { + IN_PROGRESS("IN_PROGRESS"), + FAILED("FAILED"), + SUCCESS("SUCCESS"), + UNKNOWN("UNKNOWN"); + + private final String value; + + DeidentifyFileStatus(String value) { + this.value = value; + } + + public String value() { + return value; + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/enums/DetectEntities.java b/src/main/java/com/skyflow/enums/DetectEntities.java new file mode 100644 index 00000000..3fd15a67 --- /dev/null +++ b/src/main/java/com/skyflow/enums/DetectEntities.java @@ -0,0 +1,90 @@ +package com.skyflow.enums; + + +public enum DetectEntities { + ACCOUNT_NUMBER("account_number"), + AGE("age"), + ALL("all"), + BANK_ACCOUNT("bank_account"), + BLOOD_TYPE("blood_type"), + CONDITION("condition"), + CORPORATE_ACTION("corporate_action"), + CREDIT_CARD("credit_card"), + CREDIT_CARD_EXPIRATION("credit_card_expiration"), + CVV("cvv"), + DATE("date"), + DAY("day"), + DATE_INTERVAL("date_interval"), + DOB("dob"), + DOSE("dose"), + DRIVER_LICENSE("driver_license"), + DRUG("drug"), + DURATION("duration"), + EFFECT("effect"), + EMAIL_ADDRESS("email_address"), + EVENT("event"), + FILENAME("filename"), + FINANCIAL_METRIC("financial_metric"), + GENDER("gender"), + HEALTHCARE_NUMBER("healthcare_number"), + INJURY("injury"), + IP_ADDRESS("ip_address"), + LANGUAGE("language"), + LOCATION("location"), + LOCATION_ADDRESS("location_address"), + LOCATION_ADDRESS_STREET("location_address_street"), + LOCATION_CITY("location_city"), + LOCATION_COORDINATE("location_coordinate"), + LOCATION_COUNTRY("location_country"), + LOCATION_STATE("location_state"), + LOCATION_ZIP("location_zip"), + MARITAL_STATUS("marital_status"), + MEDICAL_CODE("medical_code"), + MEDICAL_PROCESS("medical_process"), + MONEY("money"), + MONTH("month"), + NAME("name"), + NAME_FAMILY("name_family"), + NAME_GIVEN("name_given"), + NAME_MEDICAL_PROFESSIONAL("name_medical_professional"), + NUMERICAL_PII("numerical_pii"), + OCCUPATION("occupation"), + ORGANIZATION("organization"), + ORGANIZATION_ID("organization_id"), + ORGANIZATION_MEDICAL_FACILITY("organization_medical_facility"), + ORIGIN("origin"), + PASSPORT_NUMBER("passport_number"), + PASSWORD("password"), + PHONE_NUMBER("phone_number"), + PROJECT("project"), + PHYSICAL_ATTRIBUTE("physical_attribute"), + POLITICAL_AFFILIATION("political_affiliation"), + PRODUCT("product"), + RELIGION("religion"), + ROUTING_NUMBER("routing_number"), + SEXUALITY("sexuality"), + SSN("ssn"), + STATISTICS("statistics"), + TIME("time"), + TREND("trend"), + URL("url"), + USERNAME("username"), + VEHICLE_ID("vehicle_id"), + YEAR("year"), + ZODIAC_SIGN("zodiac_sign"); + + private final String detectEntities; + + DetectEntities(String detectEntities) { + this.detectEntities = detectEntities; + } + + public String getDetectEntities() { + return detectEntities; + } + + @Override + public String toString() { + return detectEntities; + } +} diff --git a/src/main/java/com/skyflow/enums/DetectOutputTranscriptions.java b/src/main/java/com/skyflow/enums/DetectOutputTranscriptions.java new file mode 100644 index 00000000..43251c61 --- /dev/null +++ b/src/main/java/com/skyflow/enums/DetectOutputTranscriptions.java @@ -0,0 +1,24 @@ +package com.skyflow.enums; + +public enum DetectOutputTranscriptions { + DIARIZED_TRANSCRIPTION("diarized_transcription"), + MEDICAL_DIARIZED_TRANSCRIPTION("medical_diarized_transcription"), + MEDICAL_TRANSCRIPTION("medical_transcription"), + PLAINTEXT_TRANSCRIPTION("plaintext_transcription"), + TRANSCRIPTION("transcription"); + + private final String detectOutputTranscriptions; + + DetectOutputTranscriptions(String detectOutputTranscriptions) { + this.detectOutputTranscriptions = detectOutputTranscriptions; + } + + public String getDetectOutputTranscriptions() { + return detectOutputTranscriptions; + } + + @Override + public String toString() { + return detectOutputTranscriptions; + } +} diff --git a/src/main/java/com/skyflow/enums/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..98992f21 --- /dev/null +++ b/src/main/java/com/skyflow/enums/InterfaceName.java @@ -0,0 +1,24 @@ +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"), + DETECT("detect"), + 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/MaskingMethod.java b/src/main/java/com/skyflow/enums/MaskingMethod.java new file mode 100644 index 00000000..e3ff252c --- /dev/null +++ b/src/main/java/com/skyflow/enums/MaskingMethod.java @@ -0,0 +1,21 @@ +package com.skyflow.enums; + +public enum MaskingMethod { + BLACKBOX("blackbox"), + BLUR("blur"); + + private final String maskingMethod; + + MaskingMethod(String maskingMethod) { + this.maskingMethod = maskingMethod; + } + + public String getMaskingMethod() { + return maskingMethod; + } + + @Override + public String toString() { + return maskingMethod; + } +} diff --git a/src/main/java/com/skyflow/enums/RedactionType.java b/src/main/java/com/skyflow/enums/RedactionType.java new file mode 100644 index 00000000..9c76cc7d --- /dev/null +++ b/src/main/java/com/skyflow/enums/RedactionType.java @@ -0,0 +1,26 @@ +package com.skyflow.enums; + + +import com.skyflow.generated.rest.types.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/enums/TokenMode.java b/src/main/java/com/skyflow/enums/TokenMode.java new file mode 100644 index 00000000..63e9b8a9 --- /dev/null +++ b/src/main/java/com/skyflow/enums/TokenMode.java @@ -0,0 +1,24 @@ +package com.skyflow.enums; + +import com.skyflow.generated.rest.types.V1Byot; + +public enum TokenMode { + DISABLE(V1Byot.DISABLE), + ENABLE(V1Byot.ENABLE), + ENABLE_STRICT(V1Byot.ENABLE_STRICT); + + private final V1Byot byot; + + TokenMode(V1Byot byot) { + this.byot = byot; + } + + public V1Byot getBYOT() { + return byot; + } + + @Override + public String toString() { + return byot.toString(); + } +} diff --git a/src/main/java/com/skyflow/enums/TokenType.java b/src/main/java/com/skyflow/enums/TokenType.java new file mode 100644 index 00000000..4a619e9c --- /dev/null +++ b/src/main/java/com/skyflow/enums/TokenType.java @@ -0,0 +1,27 @@ +package com.skyflow.enums; + +public enum TokenType { + VAULT_TOKEN("vault_token"), + ENTITY_UNIQUE_COUNTER("entity_unq_counter"), + ENTITY_ONLY("entity_only"); + + private final String tokenType; + + TokenType(String tokenType) { + this.tokenType = tokenType; + } + + public String getTokenType() { + return tokenType; + } + + public String getDefault() { + return ENTITY_UNIQUE_COUNTER.getTokenType(); + } + + @Override + public String toString() { + return tokenType; + } +} + diff --git a/src/main/java/com/skyflow/errors/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..ac6adfd0 --- /dev/null +++ b/src/main/java/com/skyflow/errors/ErrorMessage.java @@ -0,0 +1,170 @@ +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. Credentials must not be empty."), + + // 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 must not be empty."), + EmptyApikey("%s0 Initialization failed. Invalid credentials. Api key must not be empty."), + InvalidApikey("%s0 Initialization failed. Invalid credentials. Specify valid api key."), + EmptyRoles("%s0 Initialization failed. Invalid roles. Specify at least one role."), + 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'."), + TokensPassedForTokenModeDisable("%s0 Validation error. 'tokenMode' wasn't specified. Set 'tokenMode' to 'ENABLE' to insert tokens."), + NoTokensWithTokenMode("%s0 Validation error. Tokens weren't specified for records while 'tokenMode' was %s1. Specify tokens."), + MismatchOfFieldsAndTokens("%s0 Validation error. 'fields' and 'tokens' have different columns names. Verify that 'fields' and 'tokens' columns match."), + InsufficientTokensPassedForTokenModeEnableStrict("%s0 Validation error. 'tokenMode' is set to 'ENABLE_STRICT', but some fields are missing tokens. Specify tokens for all fields."), + BatchInsertPartialSuccess("%s0 Insert operation completed with partial success."), + BatchInsertFailure("%s0 Insert operation failed."), + + // Detokenize + InvalidDetokenizeData("%s0 Validation error. Invalid detokenize data. Specify valid detokenize data."), + EmptyDetokenizeData("%s0 Validation error. Invalid data tokens. Specify at least one data token."), + EmptyTokenInDetokenizeData("%s0 Validation error. Invalid data tokens. Specify a valid data token."), + + // Get + 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."), + + // File upload + ColumnNameKeyErrorFileUpload("%s0 Validation error. columnName is missing from the payload. Specify a columnName key."), + MissingFileSourceInUploadFileRequest("%s0 Validation error. Provide exactly one of filePath, base64, or fileObject."), + FileNameMustBeProvidedWithFileObject("%s0 Validation error. fileName must be provided when using fileObject."), + InvalidFileObject("%s0 Validation error. Invalid file object in file upload request. Specify a valid file object."), + InvalidBase64("%s0 Validation error. Invalid base64 string in file upload request. Specify a valid base64 string."), + + // detect + InvalidTextInDeIdentify("%s0 Validation error. The text field is required and must be a non-empty string. Specify a valid text."), + InvalidTextInReIdentify("%s0 Validation error. The text field is required and must be a non-empty string. Specify a valid text."), + + //Detect Files + InvalidNullFileInDeIdentifyFile("%s0 Validation error. The file field is required and must not be null. Specify a valid file object."), + InvalidFilePath("%s0 Validation error. The file path is invalid. Specify a valid file path."), + BothFileAndFilePathProvided("%s0 Validation error. Both file and filePath are provided. Specify either file object or filePath, not both."), + FileNotFoundToDeidentify("%s0 Validation error. The file to deidentify was not found at the specified path. Verify the file path and try again."), + FileNotReadableToDeidentify("%s0 Validation error. The file to deidentify is not readable. Check the file permissions and try again."), + InvalidPixelDensityToDeidentifyFile("%s0 Validation error. Should be a positive integer. Specify a valid pixel density."), + InvalidMaxResolution("%s0 Validation error. Should be a positive integer. Specify a valid max resolution."), + OutputDirectoryNotFound("%s0 Validation error. The output directory for deidentified files was not found at the specified path. Verify the output directory path and try again."), + InvalidPermission("%s0 Validation error. The output directory for deidentified files is not writable. Check the directory permissions and try again."), + InvalidWaitTime("%s0 Validation error. The wait time for deidentify file operation should be a positive integer. Specify a valid wait time."), + WaitTimeExceedsLimit("%s0 Validation error. The wait time for deidentify file operation exceeds the maximum limit of 64 seconds. Specify a wait time less than or equal to 60 seconds."), + InvalidOrEmptyRunId("%s0 Validation error. The run ID is invalid or empty. Specify a valid run ID."), + FailedToEncodeFile("%s0 Validation error. Failed to encode the file. Ensure the file is in a supported format and try again."), + FailedToDecodeFileFromResponse("%s0 Failed to decode the file from the response. Ensure the response is valid and try again."), + EmptyFileAndFilePathInDeIdentifyFile("%s0 Validation error. Both file and filePath are empty. Specify either file object or filePath, not both."), + VaultTokenFormatIsNotAllowedForFiles("%s0 Validation error. Vault token format is not allowed for deidentify file request."), + PollingForResultsFailed("%s0 API error. Polling for results failed. Unable to retrieve the deidentified file"), + FailedtoSaveProcessedFile("%s0 Validation error. Failed to save the processed file. Ensure the output directory is valid and writable."), + InvalidAudioFileType("%s0 Validation error. The file type is not supported. Specify a valid file type mp3 or wav."), + // Generic + ErrorOccurred("%s0 API error. Error occurred.") + ; + 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/HttpStatus.java b/src/main/java/com/skyflow/errors/HttpStatus.java new file mode 100644 index 00000000..2cdadbb0 --- /dev/null +++ b/src/main/java/com/skyflow/errors/HttpStatus.java @@ -0,0 +1,15 @@ +package com.skyflow.errors; + +public enum HttpStatus { + BAD_REQUEST("Bad Request"); + + private final String httpStatus; + + HttpStatus(String httpStatus) { + this.httpStatus = httpStatus; + } + + public String getHttpStatus() { + return httpStatus; + } +} diff --git a/src/main/java/com/skyflow/errors/SkyflowException.java b/src/main/java/com/skyflow/errors/SkyflowException.java index 129eb67d..32c71f39 100644 --- a/src/main/java/com/skyflow/errors/SkyflowException.java +++ b/src/main/java/com/skyflow/errors/SkyflowException.java @@ -1,54 +1,135 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ package com.skyflow.errors; -import org.json.simple.JSONObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.skyflow.utils.Constants; -public final class SkyflowException extends Exception { - private int code; - private JSONObject data; +import java.util.List; +import java.util.Map; - 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; + this.httpStatus = HttpStatus.BAD_REQUEST.getHttpStatus(); + this.details = new JsonArray(); + } + + public SkyflowException(int httpCode, Throwable cause, Map> responseHeaders, String responseBody) { + super(cause); + this.httpCode = httpCode > 0 ? httpCode : 400; + try { + setRequestId(responseHeaders); + setResponseBody(responseBody, responseHeaders); + } catch (Exception e) { + this.httpStatus = HttpStatus.BAD_REQUEST.getHttpStatus(); + String fullMessage = responseBody != null ? responseBody : + (cause.getLocalizedMessage() != null ? cause.getMessage() : ErrorMessage.ErrorOccurred.getMessage()); + this.message = fullMessage.split("HTTP response code:")[0].trim(); + } } - public SkyflowException(ErrorCode errorCode, Throwable cause) { - super(errorCode.getDescription(), cause); - this.setCode(errorCode.getCode()); + private void setResponseBody(String responseBody, Map> responseHeaders) { + this.responseBody = JsonParser.parseString(responseBody).getAsJsonObject(); + if (this.responseBody.get("error") != null) { + setGrpcCode(); + setHttpStatus(); + setMessage(); + setDetails(responseHeaders); + } } - 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) { + List ids = responseHeaders.get(Constants.REQUEST_ID_HEADER_KEY); + this.requestId = ids == null ? null : ids.get(0); } - public SkyflowException(int code, String description, JSONObject data) { - super(description); - this.setCode(code); - setData(data); + private void setMessage() { + JsonElement messageElement = ((JsonObject) responseBody.get("error")).get("message"); + this.message = messageElement == null ? null : messageElement.getAsString(); } - public int getCode() { - return code; + private void setGrpcCode() { + JsonElement grpcElement = ((JsonObject) responseBody.get("error")).get("grpc_code"); + this.grpcCode = grpcElement == null ? null : grpcElement.getAsInt(); } - void setCode(int code) { - this.code = code; + private void setHttpStatus() { + JsonElement statusElement = ((JsonObject) responseBody.get("error")).get("http_status"); + this.httpStatus = statusElement == null ? null : statusElement.getAsString(); } + public int getHttpCode() { + return httpCode; + } + + public JsonArray getDetails() { + return details; + } + + private void setDetails(Map> responseHeaders) { + JsonElement detailsElement = ((JsonObject) responseBody.get("error")).get("details"); + List errorFromClientHeader = responseHeaders.get(Constants.ERROR_FROM_CLIENT_HEADER_KEY); + if (detailsElement != null) { + this.details = detailsElement.getAsJsonArray(); + } + if (errorFromClientHeader != null) { + this.details = this.details == null ? new JsonArray() : this.details; + String errorFromClient = errorFromClientHeader.get(0); + JsonObject detailObject = new JsonObject(); + detailObject.addProperty("errorFromClient", errorFromClient); + this.details.add(detailObject); + } + } + + public 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/ApiClient.java b/src/main/java/com/skyflow/generated/rest/ApiClient.java new file mode 100644 index 00000000..7c5ae554 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/ApiClient.java @@ -0,0 +1,92 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.Suppliers; +import com.skyflow.generated.rest.resources.audit.AuditClient; +import com.skyflow.generated.rest.resources.authentication.AuthenticationClient; +import com.skyflow.generated.rest.resources.binlookup.BinLookupClient; +import com.skyflow.generated.rest.resources.files.FilesClient; +import com.skyflow.generated.rest.resources.guardrails.GuardrailsClient; +import com.skyflow.generated.rest.resources.query.QueryClient; +import com.skyflow.generated.rest.resources.records.RecordsClient; +import com.skyflow.generated.rest.resources.strings.StringsClient; +import com.skyflow.generated.rest.resources.tokens.TokensClient; +import java.util.function.Supplier; + +public class ApiClient { + protected final ClientOptions clientOptions; + + protected final Supplier auditClient; + + protected final Supplier binLookupClient; + + protected final Supplier recordsClient; + + protected final Supplier tokensClient; + + protected final Supplier queryClient; + + protected final Supplier authenticationClient; + + protected final Supplier guardrailsClient; + + protected final Supplier stringsClient; + + protected final Supplier filesClient; + + public ApiClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.auditClient = Suppliers.memoize(() -> new AuditClient(clientOptions)); + this.binLookupClient = Suppliers.memoize(() -> new BinLookupClient(clientOptions)); + this.recordsClient = Suppliers.memoize(() -> new RecordsClient(clientOptions)); + this.tokensClient = Suppliers.memoize(() -> new TokensClient(clientOptions)); + this.queryClient = Suppliers.memoize(() -> new QueryClient(clientOptions)); + this.authenticationClient = Suppliers.memoize(() -> new AuthenticationClient(clientOptions)); + this.guardrailsClient = Suppliers.memoize(() -> new GuardrailsClient(clientOptions)); + this.stringsClient = Suppliers.memoize(() -> new StringsClient(clientOptions)); + this.filesClient = Suppliers.memoize(() -> new FilesClient(clientOptions)); + } + + public AuditClient audit() { + return this.auditClient.get(); + } + + public BinLookupClient binLookup() { + return this.binLookupClient.get(); + } + + public RecordsClient records() { + return this.recordsClient.get(); + } + + public TokensClient tokens() { + return this.tokensClient.get(); + } + + public QueryClient query() { + return this.queryClient.get(); + } + + public AuthenticationClient authentication() { + return this.authenticationClient.get(); + } + + public GuardrailsClient guardrails() { + return this.guardrailsClient.get(); + } + + public StringsClient strings() { + return this.stringsClient.get(); + } + + public FilesClient files() { + return this.filesClient.get(); + } + + public static ApiClientBuilder builder() { + return new ApiClientBuilder(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/ApiClientBuilder.java b/src/main/java/com/skyflow/generated/rest/ApiClientBuilder.java new file mode 100644 index 00000000..b361812a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/ApiClientBuilder.java @@ -0,0 +1,67 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.Environment; +import okhttp3.OkHttpClient; + +public final class ApiClientBuilder { + private ClientOptions.Builder clientOptionsBuilder = ClientOptions.builder(); + + private String token = null; + + private Environment environment = Environment.PRODUCTION; + + /** + * Sets token + */ + public ApiClientBuilder token(String token) { + this.token = token; + return this; + } + + public ApiClientBuilder environment(Environment environment) { + this.environment = environment; + return this; + } + + public ApiClientBuilder url(String url) { + this.environment = Environment.custom(url); + return this; + } + + /** + * Sets the timeout (in seconds) for the client. Defaults to 60 seconds. + */ + public ApiClientBuilder timeout(int timeout) { + this.clientOptionsBuilder.timeout(timeout); + return this; + } + + /** + * Sets the maximum number of retries for the client. Defaults to 2 retries. + */ + public ApiClientBuilder maxRetries(int maxRetries) { + this.clientOptionsBuilder.maxRetries(maxRetries); + return this; + } + + /** + * Sets the underlying OkHttp client + */ + public ApiClientBuilder httpClient(OkHttpClient httpClient) { + this.clientOptionsBuilder.httpClient(httpClient); + return this; + } + + public ApiClient build() { + if (token == null) { + throw new RuntimeException("Please provide token"); + } + this.clientOptionsBuilder.addHeader("Authorization", "Bearer " + this.token); + clientOptionsBuilder.environment(this.environment); + return new ApiClient(clientOptionsBuilder.build()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java b/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java new file mode 100644 index 00000000..1fb7b844 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/AsyncApiClient.java @@ -0,0 +1,92 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.Suppliers; +import com.skyflow.generated.rest.resources.audit.AsyncAuditClient; +import com.skyflow.generated.rest.resources.authentication.AsyncAuthenticationClient; +import com.skyflow.generated.rest.resources.binlookup.AsyncBinLookupClient; +import com.skyflow.generated.rest.resources.files.AsyncFilesClient; +import com.skyflow.generated.rest.resources.guardrails.AsyncGuardrailsClient; +import com.skyflow.generated.rest.resources.query.AsyncQueryClient; +import com.skyflow.generated.rest.resources.records.AsyncRecordsClient; +import com.skyflow.generated.rest.resources.strings.AsyncStringsClient; +import com.skyflow.generated.rest.resources.tokens.AsyncTokensClient; +import java.util.function.Supplier; + +public class AsyncApiClient { + protected final ClientOptions clientOptions; + + protected final Supplier auditClient; + + protected final Supplier binLookupClient; + + protected final Supplier recordsClient; + + protected final Supplier tokensClient; + + protected final Supplier queryClient; + + protected final Supplier authenticationClient; + + protected final Supplier guardrailsClient; + + protected final Supplier stringsClient; + + protected final Supplier filesClient; + + public AsyncApiClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.auditClient = Suppliers.memoize(() -> new AsyncAuditClient(clientOptions)); + this.binLookupClient = Suppliers.memoize(() -> new AsyncBinLookupClient(clientOptions)); + this.recordsClient = Suppliers.memoize(() -> new AsyncRecordsClient(clientOptions)); + this.tokensClient = Suppliers.memoize(() -> new AsyncTokensClient(clientOptions)); + this.queryClient = Suppliers.memoize(() -> new AsyncQueryClient(clientOptions)); + this.authenticationClient = Suppliers.memoize(() -> new AsyncAuthenticationClient(clientOptions)); + this.guardrailsClient = Suppliers.memoize(() -> new AsyncGuardrailsClient(clientOptions)); + this.stringsClient = Suppliers.memoize(() -> new AsyncStringsClient(clientOptions)); + this.filesClient = Suppliers.memoize(() -> new AsyncFilesClient(clientOptions)); + } + + public AsyncAuditClient audit() { + return this.auditClient.get(); + } + + public AsyncBinLookupClient binLookup() { + return this.binLookupClient.get(); + } + + public AsyncRecordsClient records() { + return this.recordsClient.get(); + } + + public AsyncTokensClient tokens() { + return this.tokensClient.get(); + } + + public AsyncQueryClient query() { + return this.queryClient.get(); + } + + public AsyncAuthenticationClient authentication() { + return this.authenticationClient.get(); + } + + public AsyncGuardrailsClient guardrails() { + return this.guardrailsClient.get(); + } + + public AsyncStringsClient strings() { + return this.stringsClient.get(); + } + + public AsyncFilesClient files() { + return this.filesClient.get(); + } + + public static AsyncApiClientBuilder builder() { + return new AsyncApiClientBuilder(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/AsyncApiClientBuilder.java b/src/main/java/com/skyflow/generated/rest/AsyncApiClientBuilder.java new file mode 100644 index 00000000..8e4b8474 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/AsyncApiClientBuilder.java @@ -0,0 +1,67 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.Environment; +import okhttp3.OkHttpClient; + +public final class AsyncApiClientBuilder { + private ClientOptions.Builder clientOptionsBuilder = ClientOptions.builder(); + + private String token = null; + + private Environment environment = Environment.PRODUCTION; + + /** + * Sets token + */ + public AsyncApiClientBuilder token(String token) { + this.token = token; + return this; + } + + public AsyncApiClientBuilder environment(Environment environment) { + this.environment = environment; + return this; + } + + public AsyncApiClientBuilder url(String url) { + this.environment = Environment.custom(url); + return this; + } + + /** + * Sets the timeout (in seconds) for the client. Defaults to 60 seconds. + */ + public AsyncApiClientBuilder timeout(int timeout) { + this.clientOptionsBuilder.timeout(timeout); + return this; + } + + /** + * Sets the maximum number of retries for the client. Defaults to 2 retries. + */ + public AsyncApiClientBuilder maxRetries(int maxRetries) { + this.clientOptionsBuilder.maxRetries(maxRetries); + return this; + } + + /** + * Sets the underlying OkHttp client + */ + public AsyncApiClientBuilder httpClient(OkHttpClient httpClient) { + this.clientOptionsBuilder.httpClient(httpClient); + return this; + } + + public AsyncApiClient build() { + if (token == null) { + throw new RuntimeException("Please provide token"); + } + this.clientOptionsBuilder.addHeader("Authorization", "Bearer " + this.token); + clientOptionsBuilder.environment(this.environment); + return new AsyncApiClient(clientOptionsBuilder.build()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/ApiClientApiException.java b/src/main/java/com/skyflow/generated/rest/core/ApiClientApiException.java new file mode 100644 index 00000000..a4487b1e --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ApiClientApiException.java @@ -0,0 +1,73 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import okhttp3.Response; + +/** + * This exception type will be thrown for any non-2XX API responses. + */ +public class ApiClientApiException extends ApiClientException { + /** + * The error code of the response that triggered the exception. + */ + private final int statusCode; + + /** + * The body of the response that triggered the exception. + */ + private final Object body; + + private final Map> headers; + + public ApiClientApiException(String message, int statusCode, Object body) { + super(message); + this.statusCode = statusCode; + this.body = body; + this.headers = new HashMap<>(); + } + + public ApiClientApiException(String message, int statusCode, Object body, Response rawResponse) { + super(message); + this.statusCode = statusCode; + this.body = body; + this.headers = new HashMap<>(); + rawResponse.headers().forEach(header -> { + String key = header.component1(); + String value = header.component2(); + this.headers.computeIfAbsent(key, _str -> new ArrayList<>()).add(value); + }); + } + + /** + * @return the statusCode + */ + public int statusCode() { + return this.statusCode; + } + + /** + * @return the body + */ + public Object body() { + return this.body; + } + + /** + * @return the headers + */ + public Map> headers() { + return this.headers; + } + + @java.lang.Override + public String toString() { + return "ApiClientApiException{" + "message: " + getMessage() + ", statusCode: " + statusCode + ", body: " + body + + "}"; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/ApiClientException.java b/src/main/java/com/skyflow/generated/rest/core/ApiClientException.java new file mode 100644 index 00000000..7987eba6 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ApiClientException.java @@ -0,0 +1,17 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +/** + * This class serves as the base exception for all errors in the SDK. + */ +public class ApiClientException extends RuntimeException { + public ApiClientException(String message) { + super(message); + } + + public ApiClientException(String message, Exception e) { + super(message, e); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/ApiClientHttpResponse.java b/src/main/java/com/skyflow/generated/rest/core/ApiClientHttpResponse.java new file mode 100644 index 00000000..9c81f1f5 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ApiClientHttpResponse.java @@ -0,0 +1,37 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import okhttp3.Response; + +public final class ApiClientHttpResponse { + + private final T body; + + private final Map> headers; + + public ApiClientHttpResponse(T body, Response rawResponse) { + this.body = body; + + Map> headers = new HashMap<>(); + rawResponse.headers().forEach(header -> { + String key = header.component1(); + String value = header.component2(); + headers.computeIfAbsent(key, _str -> new ArrayList<>()).add(value); + }); + this.headers = headers; + } + + public T body() { + return this.body; + } + + public Map> headers() { + return headers; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java b/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java new file mode 100644 index 00000000..fe635bf1 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ClientOptions.java @@ -0,0 +1,170 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import okhttp3.OkHttpClient; + +public final class ClientOptions { + private final Environment environment; + + private final Map headers; + + private final Map> headerSuppliers; + + private final OkHttpClient httpClient; + + private final int timeout; + + private ClientOptions( + Environment environment, + Map headers, + Map> headerSuppliers, + OkHttpClient httpClient, + int timeout) { + this.environment = environment; + this.headers = new HashMap<>(); + this.headers.putAll(headers); + this.headers.putAll(new HashMap() { + { + put("X-Fern-Language", "JAVA"); + put("X-Fern-SDK-Name", "com.skyflow.fern:api-sdk"); + put("X-Fern-SDK-Version", "0.0.322"); + } + }); + this.headerSuppliers = headerSuppliers; + this.httpClient = httpClient; + this.timeout = timeout; + } + + public Environment environment() { + return this.environment; + } + + public Map headers(RequestOptions requestOptions) { + Map values = new HashMap<>(this.headers); + headerSuppliers.forEach((key, supplier) -> { + values.put(key, supplier.get()); + }); + if (requestOptions != null) { + values.putAll(requestOptions.getHeaders()); + } + return values; + } + + public int timeout(RequestOptions requestOptions) { + if (requestOptions == null) { + return this.timeout; + } + return requestOptions.getTimeout().orElse(this.timeout); + } + + public OkHttpClient httpClient() { + return this.httpClient; + } + + public OkHttpClient httpClientWithTimeout(RequestOptions requestOptions) { + if (requestOptions == null) { + return this.httpClient; + } + return this.httpClient + .newBuilder() + .callTimeout(requestOptions.getTimeout().get(), requestOptions.getTimeoutTimeUnit()) + .connectTimeout(0, TimeUnit.SECONDS) + .writeTimeout(0, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.SECONDS) + .build(); + } + + public static Builder builder() { + return new Builder(); + } + + public static final class Builder { + private Environment environment; + + private final Map headers = new HashMap<>(); + + private final Map> headerSuppliers = new HashMap<>(); + + private int maxRetries = 2; + + private Optional timeout = Optional.empty(); + + private OkHttpClient httpClient = null; + + public Builder environment(Environment environment) { + this.environment = environment; + return this; + } + + public Builder addHeader(String key, String value) { + this.headers.put(key, value); + return this; + } + + public Builder addHeader(String key, Supplier value) { + this.headerSuppliers.put(key, value); + return this; + } + + /** + * Override the timeout in seconds. Defaults to 60 seconds. + */ + public Builder timeout(int timeout) { + this.timeout = Optional.of(timeout); + return this; + } + + /** + * Override the timeout in seconds. Defaults to 60 seconds. + */ + public Builder timeout(Optional timeout) { + this.timeout = timeout; + return this; + } + + /** + * Override the maximum number of retries. Defaults to 2 retries. + */ + public Builder maxRetries(int maxRetries) { + this.maxRetries = maxRetries; + return this; + } + + public Builder httpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + public ClientOptions build() { + OkHttpClient.Builder httpClientBuilder = + this.httpClient != null ? this.httpClient.newBuilder() : new OkHttpClient.Builder(); + + if (this.httpClient != null) { + timeout.ifPresent(timeout -> httpClientBuilder + .callTimeout(timeout, TimeUnit.SECONDS) + .connectTimeout(0, TimeUnit.SECONDS) + .writeTimeout(0, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.SECONDS)); + } else { + httpClientBuilder + .callTimeout(this.timeout.orElse(60), TimeUnit.SECONDS) + .connectTimeout(0, TimeUnit.SECONDS) + .writeTimeout(0, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.SECONDS) + .addInterceptor(new RetryInterceptor(this.maxRetries)); + } + + this.httpClient = httpClientBuilder.build(); + this.timeout = Optional.of(httpClient.callTimeoutMillis() / 1000); + + return new ClientOptions(environment, headers, headerSuppliers, httpClient, this.timeout.get()); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/DateTimeDeserializer.java b/src/main/java/com/skyflow/generated/rest/core/DateTimeDeserializer.java new file mode 100644 index 00000000..6be10979 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/DateTimeDeserializer.java @@ -0,0 +1,55 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.module.SimpleModule; +import java.io.IOException; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.TemporalAccessor; +import java.time.temporal.TemporalQueries; + +/** + * Custom deserializer that handles converting ISO8601 dates into {@link OffsetDateTime} objects. + */ +class DateTimeDeserializer extends JsonDeserializer { + private static final SimpleModule MODULE; + + static { + MODULE = new SimpleModule().addDeserializer(OffsetDateTime.class, new DateTimeDeserializer()); + } + + /** + * Gets a module wrapping this deserializer as an adapter for the Jackson ObjectMapper. + * + * @return A {@link SimpleModule} to be plugged onto Jackson ObjectMapper. + */ + public static SimpleModule getModule() { + return MODULE; + } + + @Override + public OffsetDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException { + JsonToken token = parser.currentToken(); + if (token == JsonToken.VALUE_NUMBER_INT) { + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(parser.getValueAsLong()), ZoneOffset.UTC); + } else { + TemporalAccessor temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest( + parser.getValueAsString(), OffsetDateTime::from, LocalDateTime::from); + + if (temporal.query(TemporalQueries.offset()) == null) { + return LocalDateTime.from(temporal).atOffset(ZoneOffset.UTC); + } else { + return OffsetDateTime.from(temporal); + } + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/Environment.java b/src/main/java/com/skyflow/generated/rest/core/Environment.java new file mode 100644 index 00000000..c0adb233 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/Environment.java @@ -0,0 +1,24 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +public final class Environment { + public static final Environment PRODUCTION = new Environment("https://identifier.vault.skyflowapis.com"); + + public static final Environment SANDBOX = new Environment("https://identifier.vault.skyflowapis-preview.com"); + + private final String url; + + private Environment(String url) { + this.url = url; + } + + public String getUrl() { + return this.url; + } + + public static Environment custom(String url) { + return new Environment(url); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/FileStream.java b/src/main/java/com/skyflow/generated/rest/core/FileStream.java new file mode 100644 index 00000000..6b459431 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/FileStream.java @@ -0,0 +1,60 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.InputStream; +import java.util.Objects; +import okhttp3.MediaType; +import okhttp3.RequestBody; +import org.jetbrains.annotations.Nullable; + +/** + * Represents a file stream with associated metadata for file uploads. + */ +public class FileStream { + private final InputStream inputStream; + private final String fileName; + private final MediaType contentType; + + /** + * Constructs a FileStream with the given input stream and optional metadata. + * + * @param inputStream The input stream of the file content. Must not be null. + * @param fileName The name of the file, or null if unknown. + * @param contentType The MIME type of the file content, or null if unknown. + * @throws NullPointerException if inputStream is null + */ + public FileStream(InputStream inputStream, @Nullable String fileName, @Nullable MediaType contentType) { + this.inputStream = Objects.requireNonNull(inputStream, "Input stream cannot be null"); + this.fileName = fileName; + this.contentType = contentType; + } + + public FileStream(InputStream inputStream) { + this(inputStream, null, null); + } + + public InputStream getInputStream() { + return inputStream; + } + + @Nullable + public String getFileName() { + return fileName; + } + + @Nullable + public MediaType getContentType() { + return contentType; + } + + /** + * Creates a RequestBody suitable for use with OkHttp client. + * + * @return A RequestBody instance representing this file stream. + */ + public RequestBody toRequestBody() { + return new InputStreamRequestBody(contentType, inputStream); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/InputStreamRequestBody.java b/src/main/java/com/skyflow/generated/rest/core/InputStreamRequestBody.java new file mode 100644 index 00000000..545f6088 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/InputStreamRequestBody.java @@ -0,0 +1,79 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Objects; +import okhttp3.MediaType; +import okhttp3.RequestBody; +import okhttp3.internal.Util; +import okio.BufferedSink; +import okio.Okio; +import okio.Source; +import org.jetbrains.annotations.Nullable; + +/** + * A custom implementation of OkHttp's RequestBody that wraps an InputStream. + * This class allows streaming of data from an InputStream directly to an HTTP request body, + * which is useful for file uploads or sending large amounts of data without loading it all into memory. + */ +public class InputStreamRequestBody extends RequestBody { + private final InputStream inputStream; + private final MediaType contentType; + + /** + * Constructs an InputStreamRequestBody with the specified content type and input stream. + * + * @param contentType the MediaType of the content, or null if not known + * @param inputStream the InputStream containing the data to be sent + * @throws NullPointerException if inputStream is null + */ + public InputStreamRequestBody(@Nullable MediaType contentType, InputStream inputStream) { + this.contentType = contentType; + this.inputStream = Objects.requireNonNull(inputStream, "inputStream == null"); + } + + /** + * Returns the content type of this request body. + * + * @return the MediaType of the content, or null if not specified + */ + @Nullable + @Override + public MediaType contentType() { + return contentType; + } + + /** + * Returns the content length of this request body, if known. + * This method attempts to determine the length using the InputStream's available() method, + * which may not always accurately reflect the total length of the stream. + * + * @return the content length, or -1 if the length is unknown + * @throws IOException if an I/O error occurs + */ + @Override + public long contentLength() throws IOException { + return inputStream.available() == 0 ? -1 : inputStream.available(); + } + + /** + * Writes the content of the InputStream to the given BufferedSink. + * This method is responsible for transferring the data from the InputStream to the network request. + * + * @param sink the BufferedSink to write the content to + * @throws IOException if an I/O error occurs during writing + */ + @Override + public void writeTo(BufferedSink sink) throws IOException { + Source source = null; + try { + source = Okio.source(inputStream); + sink.writeAll(source); + } finally { + Util.closeQuietly(Objects.requireNonNull(source)); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/MediaTypes.java b/src/main/java/com/skyflow/generated/rest/core/MediaTypes.java new file mode 100644 index 00000000..11714cb8 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/MediaTypes.java @@ -0,0 +1,13 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import okhttp3.MediaType; + +public final class MediaTypes { + + public static final MediaType APPLICATION_JSON = MediaType.parse("application/json"); + + private MediaTypes() {} +} diff --git a/src/main/java/com/skyflow/generated/rest/core/Nullable.java b/src/main/java/com/skyflow/generated/rest/core/Nullable.java new file mode 100644 index 00000000..5929c12d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/Nullable.java @@ -0,0 +1,140 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.Optional; +import java.util.function.Function; + +public final class Nullable { + + private final Either, Null> value; + + private Nullable() { + this.value = Either.left(Optional.empty()); + } + + private Nullable(T value) { + if (value == null) { + this.value = Either.right(Null.INSTANCE); + } else { + this.value = Either.left(Optional.of(value)); + } + } + + public static Nullable ofNull() { + return new Nullable<>(null); + } + + public static Nullable of(T value) { + return new Nullable<>(value); + } + + public static Nullable empty() { + return new Nullable<>(); + } + + public static Nullable ofOptional(Optional value) { + if (value.isPresent()) { + return of(value.get()); + } else { + return empty(); + } + } + + public boolean isNull() { + return this.value.isRight(); + } + + public boolean isEmpty() { + return this.value.isLeft() && !this.value.getLeft().isPresent(); + } + + public T get() { + if (this.isNull()) { + return null; + } + + return this.value.getLeft().get(); + } + + public Nullable map(Function mapper) { + if (this.isNull()) { + return Nullable.ofNull(); + } + + return Nullable.ofOptional(this.value.getLeft().map(mapper)); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof Nullable)) { + return false; + } + + if (((Nullable) other).isNull() && this.isNull()) { + return true; + } + + return this.value.getLeft().equals(((Nullable) other).value.getLeft()); + } + + private static final class Either { + private L left = null; + private R right = null; + + private Either(L left, R right) { + if (left != null && right != null) { + throw new IllegalArgumentException("Left and right argument cannot both be non-null."); + } + + if (left == null && right == null) { + throw new IllegalArgumentException("Left and right argument cannot both be null."); + } + + if (left != null) { + this.left = left; + } + + if (right != null) { + this.right = right; + } + } + + public static Either left(L left) { + return new Either<>(left, null); + } + + public static Either right(R right) { + return new Either<>(null, right); + } + + public boolean isLeft() { + return this.left != null; + } + + public boolean isRight() { + return this.right != null; + } + + public L getLeft() { + if (!this.isLeft()) { + throw new IllegalArgumentException("Cannot get left from right Either."); + } + return this.left; + } + + public R getRight() { + if (!this.isRight()) { + throw new IllegalArgumentException("Cannot get right from left Either."); + } + return this.right; + } + } + + private static final class Null { + private static final Null INSTANCE = new Null(); + + private Null() {} + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/NullableNonemptyFilter.java b/src/main/java/com/skyflow/generated/rest/core/NullableNonemptyFilter.java new file mode 100644 index 00000000..98c33be4 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/NullableNonemptyFilter.java @@ -0,0 +1,19 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.Optional; + +public final class NullableNonemptyFilter { + @Override + public boolean equals(Object o) { + boolean isOptionalEmpty = isOptionalEmpty(o); + + return isOptionalEmpty; + } + + private boolean isOptionalEmpty(Object o) { + return o instanceof Optional && !((Optional) o).isPresent(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/ObjectMappers.java b/src/main/java/com/skyflow/generated/rest/core/ObjectMappers.java new file mode 100644 index 00000000..3b7894e0 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ObjectMappers.java @@ -0,0 +1,36 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import java.io.IOException; + +public final class ObjectMappers { + public static final ObjectMapper JSON_MAPPER = JsonMapper.builder() + .addModule(new Jdk8Module()) + .addModule(new JavaTimeModule()) + .addModule(DateTimeDeserializer.getModule()) + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .build(); + + private ObjectMappers() {} + + public static String stringify(Object o) { + try { + return JSON_MAPPER + .setSerializationInclusion(JsonInclude.Include.ALWAYS) + .writerWithDefaultPrettyPrinter() + .writeValueAsString(o); + } catch (IOException e) { + return o.getClass().getName() + "@" + Integer.toHexString(o.hashCode()); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/QueryStringMapper.java b/src/main/java/com/skyflow/generated/rest/core/QueryStringMapper.java new file mode 100644 index 00000000..e9e18fb9 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/QueryStringMapper.java @@ -0,0 +1,142 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import okhttp3.HttpUrl; +import okhttp3.MultipartBody; + +public class QueryStringMapper { + + private static final ObjectMapper MAPPER = ObjectMappers.JSON_MAPPER; + + public static void addQueryParameter(HttpUrl.Builder httpUrl, String key, Object value, boolean arraysAsRepeats) { + JsonNode valueNode = MAPPER.valueToTree(value); + + List> flat; + if (valueNode.isObject()) { + flat = flattenObject((ObjectNode) valueNode, arraysAsRepeats); + } else if (valueNode.isArray()) { + flat = flattenArray((ArrayNode) valueNode, "", arraysAsRepeats); + } else { + if (valueNode.isTextual()) { + httpUrl.addQueryParameter(key, valueNode.textValue()); + } else { + httpUrl.addQueryParameter(key, valueNode.toString()); + } + return; + } + + for (Map.Entry field : flat) { + if (field.getValue().isTextual()) { + httpUrl.addQueryParameter(key + field.getKey(), field.getValue().textValue()); + } else { + httpUrl.addQueryParameter(key + field.getKey(), field.getValue().toString()); + } + } + } + + public static void addFormDataPart( + MultipartBody.Builder multipartBody, String key, Object value, boolean arraysAsRepeats) { + JsonNode valueNode = MAPPER.valueToTree(value); + + List> flat; + if (valueNode.isObject()) { + flat = flattenObject((ObjectNode) valueNode, arraysAsRepeats); + } else if (valueNode.isArray()) { + flat = flattenArray((ArrayNode) valueNode, "", arraysAsRepeats); + } else { + if (valueNode.isTextual()) { + multipartBody.addFormDataPart(key, valueNode.textValue()); + } else { + multipartBody.addFormDataPart(key, valueNode.toString()); + } + return; + } + + for (Map.Entry field : flat) { + if (field.getValue().isTextual()) { + multipartBody.addFormDataPart( + key + field.getKey(), field.getValue().textValue()); + } else { + multipartBody.addFormDataPart( + key + field.getKey(), field.getValue().toString()); + } + } + } + + public static List> flattenObject(ObjectNode object, boolean arraysAsRepeats) { + List> flat = new ArrayList<>(); + + Iterator> fields = object.fields(); + while (fields.hasNext()) { + Map.Entry field = fields.next(); + + String key = "[" + field.getKey() + "]"; + + if (field.getValue().isObject()) { + List> flatField = + flattenObject((ObjectNode) field.getValue(), arraysAsRepeats); + addAll(flat, flatField, key); + } else if (field.getValue().isArray()) { + List> flatField = + flattenArray((ArrayNode) field.getValue(), key, arraysAsRepeats); + addAll(flat, flatField, ""); + } else { + flat.add(new AbstractMap.SimpleEntry<>(key, field.getValue())); + } + } + + return flat; + } + + private static List> flattenArray( + ArrayNode array, String key, boolean arraysAsRepeats) { + List> flat = new ArrayList<>(); + + Iterator elements = array.elements(); + + int index = 0; + while (elements.hasNext()) { + JsonNode element = elements.next(); + + String indexKey = key + "[" + index + "]"; + + if (arraysAsRepeats) { + indexKey = key; + } + + if (element.isObject()) { + List> flatField = flattenObject((ObjectNode) element, arraysAsRepeats); + addAll(flat, flatField, indexKey); + } else if (element.isArray()) { + List> flatField = flattenArray((ArrayNode) element, "", arraysAsRepeats); + addAll(flat, flatField, indexKey); + } else { + flat.add(new AbstractMap.SimpleEntry<>(indexKey, element)); + } + + index++; + } + + return flat; + } + + private static void addAll( + List> target, List> source, String prefix) { + for (Map.Entry entry : source) { + Map.Entry entryToAdd = + new AbstractMap.SimpleEntry<>(prefix + entry.getKey(), entry.getValue()); + target.add(entryToAdd); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/RequestOptions.java b/src/main/java/com/skyflow/generated/rest/core/RequestOptions.java new file mode 100644 index 00000000..edc6d0ae --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/RequestOptions.java @@ -0,0 +1,101 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +public final class RequestOptions { + private final String token; + + private final Optional timeout; + + private final TimeUnit timeoutTimeUnit; + + private final Map headers; + + private final Map> headerSuppliers; + + private RequestOptions( + String token, + Optional timeout, + TimeUnit timeoutTimeUnit, + Map headers, + Map> headerSuppliers) { + this.token = token; + this.timeout = timeout; + this.timeoutTimeUnit = timeoutTimeUnit; + this.headers = headers; + this.headerSuppliers = headerSuppliers; + } + + public Optional getTimeout() { + return timeout; + } + + public TimeUnit getTimeoutTimeUnit() { + return timeoutTimeUnit; + } + + public Map getHeaders() { + Map headers = new HashMap<>(); + if (this.token != null) { + headers.put("Authorization", "Bearer " + this.token); + } + headers.putAll(this.headers); + this.headerSuppliers.forEach((key, supplier) -> { + headers.put(key, supplier.get()); + }); + return headers; + } + + public static Builder builder() { + return new Builder(); + } + + public static final class Builder { + private String token = null; + + private Optional timeout = Optional.empty(); + + private TimeUnit timeoutTimeUnit = TimeUnit.SECONDS; + + private final Map headers = new HashMap<>(); + + private final Map> headerSuppliers = new HashMap<>(); + + public Builder token(String token) { + this.token = token; + return this; + } + + public Builder timeout(Integer timeout) { + this.timeout = Optional.of(timeout); + return this; + } + + public Builder timeout(Integer timeout, TimeUnit timeoutTimeUnit) { + this.timeout = Optional.of(timeout); + this.timeoutTimeUnit = timeoutTimeUnit; + return this; + } + + public Builder addHeader(String key, String value) { + this.headers.put(key, value); + return this; + } + + public Builder addHeader(String key, Supplier value) { + this.headerSuppliers.put(key, value); + return this; + } + + public RequestOptions build() { + return new RequestOptions(token, timeout, timeoutTimeUnit, headers, headerSuppliers); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/ResponseBodyInputStream.java b/src/main/java/com/skyflow/generated/rest/core/ResponseBodyInputStream.java new file mode 100644 index 00000000..d8df7715 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ResponseBodyInputStream.java @@ -0,0 +1,45 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.FilterInputStream; +import java.io.IOException; +import okhttp3.Response; + +/** + * A custom InputStream that wraps the InputStream from the OkHttp Response and ensures that the + * OkHttp Response object is properly closed when the stream is closed. + * + * This class extends FilterInputStream and takes an OkHttp Response object as a parameter. + * It retrieves the InputStream from the Response and overrides the close method to close + * both the InputStream and the Response object, ensuring proper resource management and preventing + * premature closure of the underlying HTTP connection. + */ +public class ResponseBodyInputStream extends FilterInputStream { + private final Response response; + + /** + * Constructs a ResponseBodyInputStream that wraps the InputStream from the given OkHttp + * Response object. + * + * @param response the OkHttp Response object from which the InputStream is retrieved + * @throws IOException if an I/O error occurs while retrieving the InputStream + */ + public ResponseBodyInputStream(Response response) throws IOException { + super(response.body().byteStream()); + this.response = response; + } + + /** + * Closes the InputStream and the associated OkHttp Response object. This ensures that the + * underlying HTTP connection is properly closed after the stream is no longer needed. + * + * @throws IOException if an I/O error occurs + */ + @Override + public void close() throws IOException { + super.close(); + response.close(); // Ensure the response is closed when the stream is closed + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/ResponseBodyReader.java b/src/main/java/com/skyflow/generated/rest/core/ResponseBodyReader.java new file mode 100644 index 00000000..ed894407 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/ResponseBodyReader.java @@ -0,0 +1,44 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.FilterReader; +import java.io.IOException; +import okhttp3.Response; + +/** + * A custom Reader that wraps the Reader from the OkHttp Response and ensures that the + * OkHttp Response object is properly closed when the reader is closed. + * + * This class extends FilterReader and takes an OkHttp Response object as a parameter. + * It retrieves the Reader from the Response and overrides the close method to close + * both the Reader and the Response object, ensuring proper resource management and preventing + * premature closure of the underlying HTTP connection. + */ +public class ResponseBodyReader extends FilterReader { + private final Response response; + + /** + * Constructs a ResponseBodyReader that wraps the Reader from the given OkHttp Response object. + * + * @param response the OkHttp Response object from which the Reader is retrieved + * @throws IOException if an I/O error occurs while retrieving the Reader + */ + public ResponseBodyReader(Response response) throws IOException { + super(response.body().charStream()); + this.response = response; + } + + /** + * Closes the Reader and the associated OkHttp Response object. This ensures that the + * underlying HTTP connection is properly closed after the reader is no longer needed. + * + * @throws IOException if an I/O error occurs + */ + @Override + public void close() throws IOException { + super.close(); + response.close(); // Ensure the response is closed when the reader is closed + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/RetryInterceptor.java b/src/main/java/com/skyflow/generated/rest/core/RetryInterceptor.java new file mode 100644 index 00000000..eda7d265 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/RetryInterceptor.java @@ -0,0 +1,78 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.IOException; +import java.time.Duration; +import java.util.Optional; +import java.util.Random; +import okhttp3.Interceptor; +import okhttp3.Response; + +public class RetryInterceptor implements Interceptor { + + private static final Duration ONE_SECOND = Duration.ofSeconds(1); + private final ExponentialBackoff backoff; + private final Random random = new Random(); + + public RetryInterceptor(int maxRetries) { + this.backoff = new ExponentialBackoff(maxRetries); + } + + @Override + public Response intercept(Chain chain) throws IOException { + Response response = chain.proceed(chain.request()); + + if (shouldRetry(response.code())) { + return retryChain(response, chain); + } + + return response; + } + + private Response retryChain(Response response, Chain chain) throws IOException { + Optional nextBackoff = this.backoff.nextBackoff(); + while (nextBackoff.isPresent()) { + try { + Thread.sleep(nextBackoff.get().toMillis()); + } catch (InterruptedException e) { + throw new IOException("Interrupted while trying request", e); + } + response.close(); + response = chain.proceed(chain.request()); + if (shouldRetry(response.code())) { + nextBackoff = this.backoff.nextBackoff(); + } else { + return response; + } + } + + return response; + } + + private static boolean shouldRetry(int statusCode) { + return statusCode == 408 || statusCode == 429 || statusCode >= 500; + } + + private final class ExponentialBackoff { + + private final int maxNumRetries; + + private int retryNumber = 0; + + ExponentialBackoff(int maxNumRetries) { + this.maxNumRetries = maxNumRetries; + } + + public Optional nextBackoff() { + retryNumber += 1; + if (retryNumber > maxNumRetries) { + return Optional.empty(); + } + + int upperBound = (int) Math.pow(2, retryNumber); + return Optional.of(ONE_SECOND.multipliedBy(random.nextInt(upperBound))); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/Stream.java b/src/main/java/com/skyflow/generated/rest/core/Stream.java new file mode 100644 index 00000000..f037712a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/Stream.java @@ -0,0 +1,97 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.io.Reader; +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.Scanner; + +/** + * The {@code Stream} class implements {@link Iterable} to provide a simple mechanism for reading and parsing + * objects of a given type from data streamed via a {@link Reader} using a specified delimiter. + *

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

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

+ * Will block and wait for input if the stream has not ended and the next object is not yet available. + * + * @return The next element in the stream. + * @throws NoSuchElementException If there are no more elements in the stream. + */ + @Override + public T next() { + if (!scanner.hasNext()) { + throw new NoSuchElementException(); + } else { + try { + T parsedResponse = ObjectMappers.JSON_MAPPER.readValue( + scanner.next().trim(), valueType); + return parsedResponse; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + /** + * Removing elements from {@code Stream} is not supported. + * + * @throws UnsupportedOperationException Always, as removal is not supported. + */ + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/core/Suppliers.java b/src/main/java/com/skyflow/generated/rest/core/Suppliers.java new file mode 100644 index 00000000..307d5852 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/core/Suppliers.java @@ -0,0 +1,23 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.core; + +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; + +public final class Suppliers { + private Suppliers() {} + + public static Supplier memoize(Supplier delegate) { + AtomicReference value = new AtomicReference<>(); + return () -> { + T val = value.get(); + if (val == null) { + val = value.updateAndGet(cur -> cur == null ? Objects.requireNonNull(delegate.get()) : cur); + } + return val; + }; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/errors/BadRequestError.java b/src/main/java/com/skyflow/generated/rest/errors/BadRequestError.java new file mode 100644 index 00000000..c8d4bb99 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/errors/BadRequestError.java @@ -0,0 +1,32 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.errors; + +import com.skyflow.generated.rest.core.ApiClientApiException; +import okhttp3.Response; + +public final class BadRequestError extends ApiClientApiException { + /** + * The body of the response that triggered the exception. + */ + private final Object body; + + public BadRequestError(Object body) { + super("BadRequestError", 400, body); + this.body = body; + } + + public BadRequestError(Object body, Response rawResponse) { + super("BadRequestError", 400, body, rawResponse); + this.body = body; + } + + /** + * @return the body + */ + @java.lang.Override + public Object body() { + return this.body; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/errors/InternalServerError.java b/src/main/java/com/skyflow/generated/rest/errors/InternalServerError.java new file mode 100644 index 00000000..d29f2b82 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/errors/InternalServerError.java @@ -0,0 +1,33 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.errors; + +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.types.ErrorResponse; +import okhttp3.Response; + +public final class InternalServerError extends ApiClientApiException { + /** + * The body of the response that triggered the exception. + */ + private final ErrorResponse body; + + public InternalServerError(ErrorResponse body) { + super("InternalServerError", 500, body); + this.body = body; + } + + public InternalServerError(ErrorResponse body, Response rawResponse) { + super("InternalServerError", 500, body, rawResponse); + this.body = body; + } + + /** + * @return the body + */ + @java.lang.Override + public ErrorResponse body() { + return this.body; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/errors/NotFoundError.java b/src/main/java/com/skyflow/generated/rest/errors/NotFoundError.java new file mode 100644 index 00000000..efa94aad --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/errors/NotFoundError.java @@ -0,0 +1,32 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.errors; + +import com.skyflow.generated.rest.core.ApiClientApiException; +import okhttp3.Response; + +public final class NotFoundError extends ApiClientApiException { + /** + * The body of the response that triggered the exception. + */ + private final Object body; + + public NotFoundError(Object body) { + super("NotFoundError", 404, body); + this.body = body; + } + + public NotFoundError(Object body, Response rawResponse) { + super("NotFoundError", 404, body, rawResponse); + this.body = body; + } + + /** + * @return the body + */ + @java.lang.Override + public Object body() { + return this.body; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/errors/UnauthorizedError.java b/src/main/java/com/skyflow/generated/rest/errors/UnauthorizedError.java new file mode 100644 index 00000000..3b6d6ae1 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/errors/UnauthorizedError.java @@ -0,0 +1,32 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.errors; + +import com.skyflow.generated.rest.core.ApiClientApiException; +import okhttp3.Response; + +public final class UnauthorizedError extends ApiClientApiException { + /** + * The body of the response that triggered the exception. + */ + private final Object body; + + public UnauthorizedError(Object body) { + super("UnauthorizedError", 401, body); + this.body = body; + } + + public UnauthorizedError(Object body, Response rawResponse) { + super("UnauthorizedError", 401, body, rawResponse); + this.body = body; + } + + /** + * @return the body + */ + @java.lang.Override + public Object body() { + return this.body; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncAuditClient.java b/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncAuditClient.java new file mode 100644 index 00000000..0064558d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncAuditClient.java @@ -0,0 +1,45 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.audit.requests.AuditServiceListAuditEventsRequest; +import com.skyflow.generated.rest.types.V1AuditResponse; +import java.util.concurrent.CompletableFuture; + +public class AsyncAuditClient { + protected final ClientOptions clientOptions; + + private final AsyncRawAuditClient rawClient; + + public AsyncAuditClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new AsyncRawAuditClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public AsyncRawAuditClient withRawResponse() { + return this.rawClient; + } + + /** + * Lists audit events that match query parameters. + */ + public CompletableFuture auditServiceListAuditEvents(AuditServiceListAuditEventsRequest request) { + return this.rawClient.auditServiceListAuditEvents(request).thenApply(response -> response.body()); + } + + /** + * Lists audit events that match query parameters. + */ + public CompletableFuture auditServiceListAuditEvents( + AuditServiceListAuditEventsRequest request, RequestOptions requestOptions) { + return this.rawClient + .auditServiceListAuditEvents(request, requestOptions) + .thenApply(response -> response.body()); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncRawAuditClient.java b/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncRawAuditClient.java new file mode 100644 index 00000000..875ca259 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/AsyncRawAuditClient.java @@ -0,0 +1,296 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.audit.requests.AuditServiceListAuditEventsRequest; +import com.skyflow.generated.rest.types.V1AuditResponse; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.NotNull; + +public class AsyncRawAuditClient { + protected final ClientOptions clientOptions; + + public AsyncRawAuditClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Lists audit events that match query parameters. + */ + public CompletableFuture> auditServiceListAuditEvents( + AuditServiceListAuditEventsRequest request) { + return auditServiceListAuditEvents(request, null); + } + + /** + * Lists audit events that match query parameters. + */ + public CompletableFuture> auditServiceListAuditEvents( + AuditServiceListAuditEventsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/audit/events"); + if (request.getFilterOpsContextChangeId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.changeID", + request.getFilterOpsContextChangeId().get(), + false); + } + if (request.getFilterOpsContextRequestId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.requestID", + request.getFilterOpsContextRequestId().get(), + false); + } + if (request.getFilterOpsContextTraceId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.traceID", + request.getFilterOpsContextTraceId().get(), + false); + } + if (request.getFilterOpsContextSessionId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.sessionID", + request.getFilterOpsContextSessionId().get(), + false); + } + if (request.getFilterOpsContextActor().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.actor", + request.getFilterOpsContextActor().get(), + false); + } + if (request.getFilterOpsContextActorType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.actorType", + request.getFilterOpsContextActorType().get(), + false); + } + if (request.getFilterOpsContextAccessType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.accessType", + request.getFilterOpsContextAccessType().get(), + false); + } + if (request.getFilterOpsContextIpAddress().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.ipAddress", + request.getFilterOpsContextIpAddress().get(), + false); + } + if (request.getFilterOpsContextOrigin().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.origin", + request.getFilterOpsContextOrigin().get(), + false); + } + if (request.getFilterOpsContextAuthMode().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.authMode", + request.getFilterOpsContextAuthMode().get(), + false); + } + if (request.getFilterOpsContextJwtId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.jwtID", + request.getFilterOpsContextJwtId().get(), + false); + } + if (request.getFilterOpsContextBearerTokenContextId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.bearerTokenContextID", + request.getFilterOpsContextBearerTokenContextId().get(), + false); + } + if (request.getFilterOpsParentAccountId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.parentAccountID", + request.getFilterOpsParentAccountId().get(), + false); + } + QueryStringMapper.addQueryParameter(httpUrl, "filterOps.accountID", request.getFilterOpsAccountId(), false); + if (request.getFilterOpsWorkspaceId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.workspaceID", + request.getFilterOpsWorkspaceId().get(), + false); + } + if (request.getFilterOpsVaultId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.vaultID", request.getFilterOpsVaultId().get(), false); + } + if (request.getFilterOpsResourceIDs().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.resourceIDs", + request.getFilterOpsResourceIDs().get(), + false); + } + if (request.getFilterOpsActionType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.actionType", + request.getFilterOpsActionType().get(), + false); + } + if (request.getFilterOpsResourceType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.resourceType", + request.getFilterOpsResourceType().get(), + false); + } + if (request.getFilterOpsTags().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.tags", request.getFilterOpsTags().get(), false); + } + if (request.getFilterOpsResponseCode().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.responseCode", + request.getFilterOpsResponseCode().get(), + false); + } + if (request.getFilterOpsStartTime().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.startTime", + request.getFilterOpsStartTime().get(), + false); + } + if (request.getFilterOpsEndTime().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.endTime", request.getFilterOpsEndTime().get(), false); + } + if (request.getFilterOpsApiName().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.apiName", request.getFilterOpsApiName().get(), false); + } + if (request.getFilterOpsResponseMessage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.responseMessage", + request.getFilterOpsResponseMessage().get(), + false); + } + if (request.getFilterOpsHttpMethod().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.httpMethod", + request.getFilterOpsHttpMethod().get(), + false); + } + if (request.getFilterOpsHttpUri().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.httpURI", request.getFilterOpsHttpUri().get(), false); + } + if (request.getSortOpsSortBy().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "sortOps.sortBy", request.getSortOpsSortBy().get(), false); + } + if (request.getSortOpsOrderBy().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "sortOps.orderBy", request.getSortOpsOrderBy().get(), false); + } + if (request.getAfterOpsTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "afterOps.timestamp", + request.getAfterOpsTimestamp().get(), + false); + } + if (request.getAfterOpsChangeId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "afterOps.changeID", request.getAfterOpsChangeId().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getOffset().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "offset", request.getOffset().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + CompletableFuture> future = new CompletableFuture<>(); + client.newCall(okhttpRequest).enqueue(new Callback() { + @Override + public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (response.isSuccessful()) { + future.complete(new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1AuditResponse.class), + response)); + return; + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + future.completeExceptionally(new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response)); + return; + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + future.completeExceptionally(new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response)); + return; + } catch (IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + } + + @Override + public void onFailure(@NotNull Call call, @NotNull IOException e) { + future.completeExceptionally(new ApiClientException("Network error executing HTTP request", e)); + } + }); + return future; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/AuditClient.java b/src/main/java/com/skyflow/generated/rest/resources/audit/AuditClient.java new file mode 100644 index 00000000..bac81431 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/AuditClient.java @@ -0,0 +1,44 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit; + +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.resources.audit.requests.AuditServiceListAuditEventsRequest; +import com.skyflow.generated.rest.types.V1AuditResponse; + +public class AuditClient { + protected final ClientOptions clientOptions; + + private final RawAuditClient rawClient; + + public AuditClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + this.rawClient = new RawAuditClient(clientOptions); + } + + /** + * Get responses with HTTP metadata like headers + */ + public RawAuditClient withRawResponse() { + return this.rawClient; + } + + /** + * Lists audit events that match query parameters. + */ + public V1AuditResponse auditServiceListAuditEvents(AuditServiceListAuditEventsRequest request) { + return this.rawClient.auditServiceListAuditEvents(request).body(); + } + + /** + * Lists audit events that match query parameters. + */ + public V1AuditResponse auditServiceListAuditEvents( + AuditServiceListAuditEventsRequest request, RequestOptions requestOptions) { + return this.rawClient + .auditServiceListAuditEvents(request, requestOptions) + .body(); + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/RawAuditClient.java b/src/main/java/com/skyflow/generated/rest/resources/audit/RawAuditClient.java new file mode 100644 index 00000000..bfec3bf2 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/RawAuditClient.java @@ -0,0 +1,277 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.core.ClientOptions; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.core.QueryStringMapper; +import com.skyflow.generated.rest.core.RequestOptions; +import com.skyflow.generated.rest.errors.NotFoundError; +import com.skyflow.generated.rest.resources.audit.requests.AuditServiceListAuditEventsRequest; +import com.skyflow.generated.rest.types.V1AuditResponse; +import java.io.IOException; +import okhttp3.Headers; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; + +public class RawAuditClient { + protected final ClientOptions clientOptions; + + public RawAuditClient(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + } + + /** + * Lists audit events that match query parameters. + */ + public ApiClientHttpResponse auditServiceListAuditEvents( + AuditServiceListAuditEventsRequest request) { + return auditServiceListAuditEvents(request, null); + } + + /** + * Lists audit events that match query parameters. + */ + public ApiClientHttpResponse auditServiceListAuditEvents( + AuditServiceListAuditEventsRequest request, RequestOptions requestOptions) { + HttpUrl.Builder httpUrl = HttpUrl.parse(this.clientOptions.environment().getUrl()) + .newBuilder() + .addPathSegments("v1/audit/events"); + if (request.getFilterOpsContextChangeId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.changeID", + request.getFilterOpsContextChangeId().get(), + false); + } + if (request.getFilterOpsContextRequestId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.requestID", + request.getFilterOpsContextRequestId().get(), + false); + } + if (request.getFilterOpsContextTraceId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.traceID", + request.getFilterOpsContextTraceId().get(), + false); + } + if (request.getFilterOpsContextSessionId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.sessionID", + request.getFilterOpsContextSessionId().get(), + false); + } + if (request.getFilterOpsContextActor().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.actor", + request.getFilterOpsContextActor().get(), + false); + } + if (request.getFilterOpsContextActorType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.actorType", + request.getFilterOpsContextActorType().get(), + false); + } + if (request.getFilterOpsContextAccessType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.accessType", + request.getFilterOpsContextAccessType().get(), + false); + } + if (request.getFilterOpsContextIpAddress().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.ipAddress", + request.getFilterOpsContextIpAddress().get(), + false); + } + if (request.getFilterOpsContextOrigin().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.origin", + request.getFilterOpsContextOrigin().get(), + false); + } + if (request.getFilterOpsContextAuthMode().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.authMode", + request.getFilterOpsContextAuthMode().get(), + false); + } + if (request.getFilterOpsContextJwtId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.jwtID", + request.getFilterOpsContextJwtId().get(), + false); + } + if (request.getFilterOpsContextBearerTokenContextId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.context.bearerTokenContextID", + request.getFilterOpsContextBearerTokenContextId().get(), + false); + } + if (request.getFilterOpsParentAccountId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.parentAccountID", + request.getFilterOpsParentAccountId().get(), + false); + } + QueryStringMapper.addQueryParameter(httpUrl, "filterOps.accountID", request.getFilterOpsAccountId(), false); + if (request.getFilterOpsWorkspaceId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.workspaceID", + request.getFilterOpsWorkspaceId().get(), + false); + } + if (request.getFilterOpsVaultId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.vaultID", request.getFilterOpsVaultId().get(), false); + } + if (request.getFilterOpsResourceIDs().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.resourceIDs", + request.getFilterOpsResourceIDs().get(), + false); + } + if (request.getFilterOpsActionType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.actionType", + request.getFilterOpsActionType().get(), + false); + } + if (request.getFilterOpsResourceType().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.resourceType", + request.getFilterOpsResourceType().get(), + false); + } + if (request.getFilterOpsTags().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.tags", request.getFilterOpsTags().get(), false); + } + if (request.getFilterOpsResponseCode().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.responseCode", + request.getFilterOpsResponseCode().get(), + false); + } + if (request.getFilterOpsStartTime().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.startTime", + request.getFilterOpsStartTime().get(), + false); + } + if (request.getFilterOpsEndTime().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.endTime", request.getFilterOpsEndTime().get(), false); + } + if (request.getFilterOpsApiName().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.apiName", request.getFilterOpsApiName().get(), false); + } + if (request.getFilterOpsResponseMessage().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.responseMessage", + request.getFilterOpsResponseMessage().get(), + false); + } + if (request.getFilterOpsHttpMethod().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "filterOps.httpMethod", + request.getFilterOpsHttpMethod().get(), + false); + } + if (request.getFilterOpsHttpUri().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "filterOps.httpURI", request.getFilterOpsHttpUri().get(), false); + } + if (request.getSortOpsSortBy().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "sortOps.sortBy", request.getSortOpsSortBy().get(), false); + } + if (request.getSortOpsOrderBy().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "sortOps.orderBy", request.getSortOpsOrderBy().get(), false); + } + if (request.getAfterOpsTimestamp().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, + "afterOps.timestamp", + request.getAfterOpsTimestamp().get(), + false); + } + if (request.getAfterOpsChangeId().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "afterOps.changeID", request.getAfterOpsChangeId().get(), false); + } + if (request.getLimit().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "limit", request.getLimit().get(), false); + } + if (request.getOffset().isPresent()) { + QueryStringMapper.addQueryParameter( + httpUrl, "offset", request.getOffset().get(), false); + } + Request.Builder _requestBuilder = new Request.Builder() + .url(httpUrl.build()) + .method("GET", null) + .headers(Headers.of(clientOptions.headers(requestOptions))) + .addHeader("Accept", "application/json"); + Request okhttpRequest = _requestBuilder.build(); + OkHttpClient client = clientOptions.httpClient(); + if (requestOptions != null && requestOptions.getTimeout().isPresent()) { + client = clientOptions.httpClientWithTimeout(requestOptions); + } + try (Response response = client.newCall(okhttpRequest).execute()) { + ResponseBody responseBody = response.body(); + if (response.isSuccessful()) { + return new ApiClientHttpResponse<>( + ObjectMappers.JSON_MAPPER.readValue(responseBody.string(), V1AuditResponse.class), response); + } + String responseBodyString = responseBody != null ? responseBody.string() : "{}"; + try { + if (response.code() == 404) { + throw new NotFoundError( + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), response); + } + } catch (JsonProcessingException ignored) { + // unable to map error response, throwing generic error + } + throw new ApiClientApiException( + "Error with status code " + response.code(), + response.code(), + ObjectMappers.JSON_MAPPER.readValue(responseBodyString, Object.class), + response); + } catch (IOException e) { + throw new ApiClientException("Network error executing HTTP request", e); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/audit/requests/AuditServiceListAuditEventsRequest.java b/src/main/java/com/skyflow/generated/rest/resources/audit/requests/AuditServiceListAuditEventsRequest.java new file mode 100644 index 00000000..3da04589 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/audit/requests/AuditServiceListAuditEventsRequest.java @@ -0,0 +1,1589 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.audit.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.audit.types.AuditServiceListAuditEventsRequestFilterOpsActionType; +import com.skyflow.generated.rest.resources.audit.types.AuditServiceListAuditEventsRequestFilterOpsContextAccessType; +import com.skyflow.generated.rest.resources.audit.types.AuditServiceListAuditEventsRequestFilterOpsContextActorType; +import com.skyflow.generated.rest.resources.audit.types.AuditServiceListAuditEventsRequestFilterOpsContextAuthMode; +import com.skyflow.generated.rest.resources.audit.types.AuditServiceListAuditEventsRequestFilterOpsResourceType; +import com.skyflow.generated.rest.resources.audit.types.AuditServiceListAuditEventsRequestSortOpsOrderBy; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = AuditServiceListAuditEventsRequest.Builder.class) +public final class AuditServiceListAuditEventsRequest { + private final Optional filterOpsContextChangeId; + + private final Optional filterOpsContextRequestId; + + private final Optional filterOpsContextTraceId; + + private final Optional filterOpsContextSessionId; + + private final Optional filterOpsContextActor; + + private final Optional filterOpsContextActorType; + + private final Optional filterOpsContextAccessType; + + private final Optional filterOpsContextIpAddress; + + private final Optional filterOpsContextOrigin; + + private final Optional filterOpsContextAuthMode; + + private final Optional filterOpsContextJwtId; + + private final Optional filterOpsContextBearerTokenContextId; + + private final Optional filterOpsParentAccountId; + + private final String filterOpsAccountId; + + private final Optional filterOpsWorkspaceId; + + private final Optional filterOpsVaultId; + + private final Optional filterOpsResourceIDs; + + private final Optional filterOpsActionType; + + private final Optional filterOpsResourceType; + + private final Optional filterOpsTags; + + private final Optional filterOpsResponseCode; + + private final Optional filterOpsStartTime; + + private final Optional filterOpsEndTime; + + private final Optional filterOpsApiName; + + private final Optional filterOpsResponseMessage; + + private final Optional filterOpsHttpMethod; + + private final Optional filterOpsHttpUri; + + private final Optional sortOpsSortBy; + + private final Optional sortOpsOrderBy; + + private final Optional afterOpsTimestamp; + + private final Optional afterOpsChangeId; + + private final Optional limit; + + private final Optional offset; + + private final Map additionalProperties; + + private AuditServiceListAuditEventsRequest( + Optional filterOpsContextChangeId, + Optional filterOpsContextRequestId, + Optional filterOpsContextTraceId, + Optional filterOpsContextSessionId, + Optional filterOpsContextActor, + Optional filterOpsContextActorType, + Optional filterOpsContextAccessType, + Optional filterOpsContextIpAddress, + Optional filterOpsContextOrigin, + Optional filterOpsContextAuthMode, + Optional filterOpsContextJwtId, + Optional filterOpsContextBearerTokenContextId, + Optional filterOpsParentAccountId, + String filterOpsAccountId, + Optional filterOpsWorkspaceId, + Optional filterOpsVaultId, + Optional filterOpsResourceIDs, + Optional filterOpsActionType, + Optional filterOpsResourceType, + Optional filterOpsTags, + Optional filterOpsResponseCode, + Optional filterOpsStartTime, + Optional filterOpsEndTime, + Optional filterOpsApiName, + Optional filterOpsResponseMessage, + Optional filterOpsHttpMethod, + Optional filterOpsHttpUri, + Optional sortOpsSortBy, + Optional sortOpsOrderBy, + Optional afterOpsTimestamp, + Optional afterOpsChangeId, + Optional limit, + Optional offset, + Map additionalProperties) { + this.filterOpsContextChangeId = filterOpsContextChangeId; + this.filterOpsContextRequestId = filterOpsContextRequestId; + this.filterOpsContextTraceId = filterOpsContextTraceId; + this.filterOpsContextSessionId = filterOpsContextSessionId; + this.filterOpsContextActor = filterOpsContextActor; + this.filterOpsContextActorType = filterOpsContextActorType; + this.filterOpsContextAccessType = filterOpsContextAccessType; + this.filterOpsContextIpAddress = filterOpsContextIpAddress; + this.filterOpsContextOrigin = filterOpsContextOrigin; + this.filterOpsContextAuthMode = filterOpsContextAuthMode; + this.filterOpsContextJwtId = filterOpsContextJwtId; + this.filterOpsContextBearerTokenContextId = filterOpsContextBearerTokenContextId; + this.filterOpsParentAccountId = filterOpsParentAccountId; + this.filterOpsAccountId = filterOpsAccountId; + this.filterOpsWorkspaceId = filterOpsWorkspaceId; + this.filterOpsVaultId = filterOpsVaultId; + this.filterOpsResourceIDs = filterOpsResourceIDs; + this.filterOpsActionType = filterOpsActionType; + this.filterOpsResourceType = filterOpsResourceType; + this.filterOpsTags = filterOpsTags; + this.filterOpsResponseCode = filterOpsResponseCode; + this.filterOpsStartTime = filterOpsStartTime; + this.filterOpsEndTime = filterOpsEndTime; + this.filterOpsApiName = filterOpsApiName; + this.filterOpsResponseMessage = filterOpsResponseMessage; + this.filterOpsHttpMethod = filterOpsHttpMethod; + this.filterOpsHttpUri = filterOpsHttpUri; + this.sortOpsSortBy = sortOpsSortBy; + this.sortOpsOrderBy = sortOpsOrderBy; + this.afterOpsTimestamp = afterOpsTimestamp; + this.afterOpsChangeId = afterOpsChangeId; + this.limit = limit; + this.offset = offset; + this.additionalProperties = additionalProperties; + } + + /** + * @return ID for the audit event. + */ + @JsonProperty("filterOps.context.changeID") + public Optional getFilterOpsContextChangeId() { + return filterOpsContextChangeId; + } + + /** + * @return ID for the request that caused the event. + */ + @JsonProperty("filterOps.context.requestID") + public Optional getFilterOpsContextRequestId() { + return filterOpsContextRequestId; + } + + /** + * @return ID for the request set by the service that received the request. + */ + @JsonProperty("filterOps.context.traceID") + public Optional getFilterOpsContextTraceId() { + return filterOpsContextTraceId; + } + + /** + * @return ID for the session in which the request was sent. + */ + @JsonProperty("filterOps.context.sessionID") + public Optional getFilterOpsContextSessionId() { + return filterOpsContextSessionId; + } + + /** + * @return Member who sent the request. Depending on actorType, this may be a user ID or a service account ID. + */ + @JsonProperty("filterOps.context.actor") + public Optional getFilterOpsContextActor() { + return filterOpsContextActor; + } + + /** + * @return Type of member who sent the request. + */ + @JsonProperty("filterOps.context.actorType") + public Optional getFilterOpsContextActorType() { + return filterOpsContextActorType; + } + + /** + * @return Type of access for the request. + */ + @JsonProperty("filterOps.context.accessType") + public Optional getFilterOpsContextAccessType() { + return filterOpsContextAccessType; + } + + /** + * @return IP Address of the client that made the request. + */ + @JsonProperty("filterOps.context.ipAddress") + public Optional getFilterOpsContextIpAddress() { + return filterOpsContextIpAddress; + } + + /** + * @return HTTP Origin request header (including scheme, hostname, and port) of the request. + */ + @JsonProperty("filterOps.context.origin") + public Optional getFilterOpsContextOrigin() { + return filterOpsContextOrigin; + } + + /** + * @return Authentication mode the actor used. + */ + @JsonProperty("filterOps.context.authMode") + public Optional getFilterOpsContextAuthMode() { + return filterOpsContextAuthMode; + } + + /** + * @return ID of the JWT token. + */ + @JsonProperty("filterOps.context.jwtID") + public Optional getFilterOpsContextJwtId() { + return filterOpsContextJwtId; + } + + /** + * @return Embedded User Context. + */ + @JsonProperty("filterOps.context.bearerTokenContextID") + public Optional getFilterOpsContextBearerTokenContextId() { + return filterOpsContextBearerTokenContextId; + } + + /** + * @return Resources with the specified parent account ID. + */ + @JsonProperty("filterOps.parentAccountID") + public Optional getFilterOpsParentAccountId() { + return filterOpsParentAccountId; + } + + /** + * @return Resources with the specified account ID. + */ + @JsonProperty("filterOps.accountID") + public String getFilterOpsAccountId() { + return filterOpsAccountId; + } + + /** + * @return Resources with the specified workspace ID. + */ + @JsonProperty("filterOps.workspaceID") + public Optional getFilterOpsWorkspaceId() { + return filterOpsWorkspaceId; + } + + /** + * @return Resources with the specified vault ID. + */ + @JsonProperty("filterOps.vaultID") + public Optional getFilterOpsVaultId() { + return filterOpsVaultId; + } + + /** + * @return Resources with a specified ID. If a resource matches at least one ID, the associated event is returned. Format is a comma-separated list of "<resourceType>/<resourceID>". For example, "VAULT/12345, USER/67890". + */ + @JsonProperty("filterOps.resourceIDs") + public Optional getFilterOpsResourceIDs() { + return filterOpsResourceIDs; + } + + /** + * @return Events with the specified action type. + */ + @JsonProperty("filterOps.actionType") + public Optional getFilterOpsActionType() { + return filterOpsActionType; + } + + /** + * @return Resources with the specified type. + */ + @JsonProperty("filterOps.resourceType") + public Optional getFilterOpsResourceType() { + return filterOpsResourceType; + } + + /** + * @return Events with associated tags. If an event matches at least one tag, the event is returned. Comma-separated list. For example, "login, get". + */ + @JsonProperty("filterOps.tags") + public Optional getFilterOpsTags() { + return filterOpsTags; + } + + /** + * @return HTTP response code of the request. + */ + @JsonProperty("filterOps.responseCode") + public Optional getFilterOpsResponseCode() { + return filterOpsResponseCode; + } + + /** + * @return Start timestamp for the query, in SQL format. + */ + @JsonProperty("filterOps.startTime") + public Optional getFilterOpsStartTime() { + return filterOpsStartTime; + } + + /** + * @return End timestamp for the query, in SQL format. + */ + @JsonProperty("filterOps.endTime") + public Optional getFilterOpsEndTime() { + return filterOpsEndTime; + } + + /** + * @return Name of the API called in the request. + */ + @JsonProperty("filterOps.apiName") + public Optional getFilterOpsApiName() { + return filterOpsApiName; + } + + /** + * @return Response message of the request. + */ + @JsonProperty("filterOps.responseMessage") + public Optional getFilterOpsResponseMessage() { + return filterOpsResponseMessage; + } + + /** + * @return HTTP method of the request. + */ + @JsonProperty("filterOps.httpMethod") + public Optional getFilterOpsHttpMethod() { + return filterOpsHttpMethod; + } + + /** + * @return HTTP URI of the request. + */ + @JsonProperty("filterOps.httpURI") + public Optional getFilterOpsHttpUri() { + return filterOpsHttpUri; + } + + /** + * @return Fully-qualified field by which to sort results. Field names should be in camel case (for example, "capitalization.camelCase"). + */ + @JsonProperty("sortOps.sortBy") + public Optional getSortOpsSortBy() { + return sortOpsSortBy; + } + + /** + * @return Ascending or descending ordering of results. + */ + @JsonProperty("sortOps.orderBy") + public Optional getSortOpsOrderBy() { + return sortOpsOrderBy; + } + + /** + * @return Timestamp provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank. + */ + @JsonProperty("afterOps.timestamp") + public Optional getAfterOpsTimestamp() { + return afterOpsTimestamp; + } + + /** + * @return Change ID provided in the previous audit response's nextOps attribute. An alternate way to manage response pagination. Can't be used with sortOps or offset. For the first request in a series of audit requests, leave blank. + */ + @JsonProperty("afterOps.changeID") + public Optional getAfterOpsChangeId() { + return afterOpsChangeId; + } + + /** + * @return Number of results to return. + */ + @JsonProperty("limit") + public Optional getLimit() { + return limit; + } + + /** + * @return Record position at which to start returning results. + */ + @JsonProperty("offset") + public Optional getOffset() { + return offset; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof AuditServiceListAuditEventsRequest + && equalTo((AuditServiceListAuditEventsRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(AuditServiceListAuditEventsRequest other) { + return filterOpsContextChangeId.equals(other.filterOpsContextChangeId) + && filterOpsContextRequestId.equals(other.filterOpsContextRequestId) + && filterOpsContextTraceId.equals(other.filterOpsContextTraceId) + && filterOpsContextSessionId.equals(other.filterOpsContextSessionId) + && filterOpsContextActor.equals(other.filterOpsContextActor) + && filterOpsContextActorType.equals(other.filterOpsContextActorType) + && filterOpsContextAccessType.equals(other.filterOpsContextAccessType) + && filterOpsContextIpAddress.equals(other.filterOpsContextIpAddress) + && filterOpsContextOrigin.equals(other.filterOpsContextOrigin) + && filterOpsContextAuthMode.equals(other.filterOpsContextAuthMode) + && filterOpsContextJwtId.equals(other.filterOpsContextJwtId) + && filterOpsContextBearerTokenContextId.equals(other.filterOpsContextBearerTokenContextId) + && filterOpsParentAccountId.equals(other.filterOpsParentAccountId) + && filterOpsAccountId.equals(other.filterOpsAccountId) + && filterOpsWorkspaceId.equals(other.filterOpsWorkspaceId) + && filterOpsVaultId.equals(other.filterOpsVaultId) + && filterOpsResourceIDs.equals(other.filterOpsResourceIDs) + && filterOpsActionType.equals(other.filterOpsActionType) + && filterOpsResourceType.equals(other.filterOpsResourceType) + && filterOpsTags.equals(other.filterOpsTags) + && filterOpsResponseCode.equals(other.filterOpsResponseCode) + && filterOpsStartTime.equals(other.filterOpsStartTime) + && filterOpsEndTime.equals(other.filterOpsEndTime) + && filterOpsApiName.equals(other.filterOpsApiName) + && filterOpsResponseMessage.equals(other.filterOpsResponseMessage) + && filterOpsHttpMethod.equals(other.filterOpsHttpMethod) + && filterOpsHttpUri.equals(other.filterOpsHttpUri) + && sortOpsSortBy.equals(other.sortOpsSortBy) + && sortOpsOrderBy.equals(other.sortOpsOrderBy) + && afterOpsTimestamp.equals(other.afterOpsTimestamp) + && afterOpsChangeId.equals(other.afterOpsChangeId) + && limit.equals(other.limit) + && offset.equals(other.offset); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash( + this.filterOpsContextChangeId, + this.filterOpsContextRequestId, + this.filterOpsContextTraceId, + this.filterOpsContextSessionId, + this.filterOpsContextActor, + this.filterOpsContextActorType, + this.filterOpsContextAccessType, + this.filterOpsContextIpAddress, + this.filterOpsContextOrigin, + this.filterOpsContextAuthMode, + this.filterOpsContextJwtId, + this.filterOpsContextBearerTokenContextId, + this.filterOpsParentAccountId, + this.filterOpsAccountId, + this.filterOpsWorkspaceId, + this.filterOpsVaultId, + this.filterOpsResourceIDs, + this.filterOpsActionType, + this.filterOpsResourceType, + this.filterOpsTags, + this.filterOpsResponseCode, + this.filterOpsStartTime, + this.filterOpsEndTime, + this.filterOpsApiName, + this.filterOpsResponseMessage, + this.filterOpsHttpMethod, + this.filterOpsHttpUri, + this.sortOpsSortBy, + this.sortOpsOrderBy, + this.afterOpsTimestamp, + this.afterOpsChangeId, + this.limit, + this.offset); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static FilterOpsAccountIdStage builder() { + return new Builder(); + } + + public interface FilterOpsAccountIdStage { + /** + * Resources with the specified account ID. + */ + _FinalStage filterOpsAccountId(@NotNull String filterOpsAccountId); + + Builder from(AuditServiceListAuditEventsRequest other); + } + + public interface _FinalStage { + AuditServiceListAuditEventsRequest build(); + + /** + *

ID for the audit event.

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

ID for the request that caused the event.

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

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

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

ID for the session in which the request was sent.

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

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

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

Type of member who sent the request.

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

Type of access for the request.

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

IP Address of the client that made the request.

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

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

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

Authentication mode the actor used.

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

ID of the JWT token.

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

Embedded User Context.

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

Resources with the specified parent account ID.

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

Resources with the specified workspace ID.

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

Resources with the specified vault ID.

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

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

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

Events with the specified action type.

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

Resources with the specified type.

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

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

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

HTTP response code of the request.

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

Start timestamp for the query, in SQL format.

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

End timestamp for the query, in SQL format.

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

Name of the API called in the request.

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

Response message of the request.

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

HTTP method of the request.

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

HTTP URI of the request.

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

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

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

Ascending or descending ordering of results.

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

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

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

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

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

Number of results to return.

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

Record position at which to start returning results.

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

Resources with the specified account ID.

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

Record position at which to start returning results.

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

Record position at which to start returning results.

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

Number of results to return.

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

Number of results to return.

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

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

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

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

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

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

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

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

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

Ascending or descending ordering of results.

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

Ascending or descending ordering of results.

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

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

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

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

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

HTTP URI of the request.

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

HTTP URI of the request.

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

HTTP method of the request.

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

HTTP method of the request.

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

Response message of the request.

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

Response message of the request.

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

Name of the API called in the request.

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

Name of the API called in the request.

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

End timestamp for the query, in SQL format.

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

End timestamp for the query, in SQL format.

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

Start timestamp for the query, in SQL format.

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

Start timestamp for the query, in SQL format.

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

HTTP response code of the request.

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

HTTP response code of the request.

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

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

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

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

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

Resources with the specified type.

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

Resources with the specified type.

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

Events with the specified action type.

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

Events with the specified action type.

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

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

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

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

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

Resources with the specified vault ID.

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

Resources with the specified vault ID.

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

Resources with the specified workspace ID.

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

Resources with the specified workspace ID.

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

Resources with the specified parent account ID.

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

Resources with the specified parent account ID.

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

Embedded User Context.

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

Embedded User Context.

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

ID of the JWT token.

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

ID of the JWT token.

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

Authentication mode the actor used.

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

Authentication mode the actor used.

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

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

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

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

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

IP Address of the client that made the request.

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

IP Address of the client that made the request.

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

Type of access for the request.

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

Type of access for the request.

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

Type of member who sent the request.

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

Type of member who sent the request.

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

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

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

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

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

ID for the session in which the request was sent.

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

ID for the session in which the request was sent.

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

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

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

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

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

ID for the request that caused the event.

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

ID for the request that caused the event.

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

ID for the audit event.

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

ID for the audit event.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Subject token.

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

Subject token type.

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

Token use type. Either delegation or impersonation.

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

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

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

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

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

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

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

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

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

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

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

Token use type. Either delegation or impersonation.

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

Token use type. Either delegation or impersonation.

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

Subject token type.

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

Subject token type.

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

Subject token.

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

Subject token.

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

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

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

BIN of the card.

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

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

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

If true, includes processed audio file in the response.

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

Type of transcription to output.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Type of transcription to output.

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

Type of transcription to output.

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

If true, includes processed audio file in the response.

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

If true, includes processed audio file in the response.

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

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

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

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

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

If true, includes processed image in the output.

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

If true, includes OCR text output in the response.

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

Method to mask the entities in the image.

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

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

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

Method to mask the entities in the image.

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

Method to mask the entities in the image.

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

If true, includes OCR text output in the response.

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

If true, includes OCR text output in the response.

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

If true, includes processed image in the output.

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

If true, includes processed image in the output.

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

Pixel density at which to process the PDF file.

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

Max resolution at which to process the PDF file.

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

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

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

Max resolution at which to process the PDF file.

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

Max resolution at which to process the PDF file.

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

Pixel density at which to process the PDF file.

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

Pixel density at which to process the PDF file.

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

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

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

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

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

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

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

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

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

ID of the vault.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("vault_id") + public _FinalStage vaultId(@NotNull String vaultId) { + this.vaultId = Objects.requireNonNull(vaultId, "vaultId must not be null"); + return this; + } + + @java.lang.Override + public GetRunRequest build() { + return new GetRunRequest(vaultId, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/files/requests/ReidentifyFileRequest.java b/src/main/java/com/skyflow/generated/rest/resources/files/requests/ReidentifyFileRequest.java new file mode 100644 index 00000000..4afb0146 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/files/requests/ReidentifyFileRequest.java @@ -0,0 +1,183 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.files.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.resources.files.types.ReidentifyFileRequestFile; +import com.skyflow.generated.rest.resources.files.types.ReidentifyFileRequestFormat; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyFileRequest.Builder.class) +public final class ReidentifyFileRequest { + private final String vaultId; + + private final ReidentifyFileRequestFile file; + + private final Optional format; + + private final Map additionalProperties; + + private ReidentifyFileRequest( + String vaultId, + ReidentifyFileRequestFile file, + Optional format, + Map additionalProperties) { + this.vaultId = vaultId; + this.file = file; + this.format = format; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("vault_id") + public String getVaultId() { + return vaultId; + } + + /** + * @return File to re-identify. Files are specified as Base64-encoded data or an EFS path. + */ + @JsonProperty("file") + public ReidentifyFileRequestFile getFile() { + return file; + } + + /** + * @return Mapping of preferred data formatting options to entity types. Returned values are dependent on the configuration of the vault storing the data and the permissions of the user or account making the request. + */ + @JsonProperty("format") + public Optional getFormat() { + return format; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyFileRequest && equalTo((ReidentifyFileRequest) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyFileRequest other) { + return vaultId.equals(other.vaultId) && file.equals(other.file) && format.equals(other.format); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.vaultId, this.file, this.format); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static VaultIdStage builder() { + return new Builder(); + } + + public interface VaultIdStage { + FileStage vaultId(@NotNull String vaultId); + + Builder from(ReidentifyFileRequest other); + } + + public interface FileStage { + /** + * File to re-identify. Files are specified as Base64-encoded data or an EFS path. + */ + _FinalStage file(@NotNull ReidentifyFileRequestFile file); + } + + public interface _FinalStage { + ReidentifyFileRequest build(); + + /** + *

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

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

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

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

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

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

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

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

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

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

Data format of the file.

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

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

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

Data format of the file.

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

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

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

Data format of the file.

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

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

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

Data format of the file.

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

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

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

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

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

Data format of the file.

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

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

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

Data format of the file.

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

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

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

Data format of the file.

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

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

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

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

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

Data format of the file.

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

Entity types to fully redact.

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

Entity types to mask.

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

Entity types to return in plaintext.

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

Check for toxicity in the text.

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

List of topics to deny.

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

Text to check against guardrails.

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

List of topics to deny.

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

List of topics to deny.

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

Check for toxicity in the text.

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

Check for toxicity in the text.

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

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

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

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

+ */ + @JsonSetter(value = "columnName", nulls = Nulls.SKIP) + public Builder columnName(Optional columnName) { + this.columnName = columnName; + return this; + } + + public Builder columnName(String columnName) { + this.columnName = Optional.ofNullable(columnName); + return this; + } + + public FileServiceUploadFileRequest build() { + return new FileServiceUploadFileRequest(columnName, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBatchOperationBody.java b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBatchOperationBody.java new file mode 100644 index 00000000..33b92483 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/resources/records/requests/RecordServiceBatchOperationBody.java @@ -0,0 +1,160 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.resources.records.requests; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import com.skyflow.generated.rest.types.V1BatchRecord; +import com.skyflow.generated.rest.types.V1Byot; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = RecordServiceBatchOperationBody.Builder.class) +public final class RecordServiceBatchOperationBody { + private final Optional> records; + + private final Optional continueOnError; + + private final Optional byot; + + private final Map additionalProperties; + + private RecordServiceBatchOperationBody( + Optional> records, + Optional continueOnError, + Optional byot, + Map additionalProperties) { + this.records = records; + this.continueOnError = continueOnError; + this.byot = byot; + this.additionalProperties = additionalProperties; + } + + /** + * @return Record operations to perform. + */ + @JsonProperty("records") + public Optional> getRecords() { + return records; + } + + /** + * @return Continue performing operations on partial errors. + */ + @JsonProperty("continueOnError") + public Optional getContinueOnError() { + return continueOnError; + } + + @JsonProperty("byot") + public Optional getByot() { + return byot; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof RecordServiceBatchOperationBody && equalTo((RecordServiceBatchOperationBody) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(RecordServiceBatchOperationBody other) { + return records.equals(other.records) + && continueOnError.equals(other.continueOnError) + && byot.equals(other.byot); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.records, this.continueOnError, this.byot); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional> records = Optional.empty(); + + private Optional continueOnError = Optional.empty(); + + private Optional byot = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(RecordServiceBatchOperationBody other) { + records(other.getRecords()); + continueOnError(other.getContinueOnError()); + byot(other.getByot()); + return this; + } + + /** + *

Record operations to perform.

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

Continue performing operations on partial errors.

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

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

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

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

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

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

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

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

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

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

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

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

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

Record position at which to start receiving data.

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

Number of record to return. Maximum 25.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Record values and tokens.

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

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

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

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

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

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

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

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

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

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

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

If true, returns metadata about the uploaded file.

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

Name of the table to upload the file to.

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

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

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

If true, returns metadata about the uploaded file.

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

If true, returns metadata about the uploaded file.

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

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

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

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

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

String to de-identify.

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

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

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

String to re-identify.

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

ID of the vault where the entities are stored.

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

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

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

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

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

Entity types to fully redact.

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

Entity types to mask.

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

Entity types to return in plaintext.

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

Detokenization details.

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

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

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

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

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

Tokenization details.

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

ID for the audit event.

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

ID for the request that caused the event.

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

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

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

ID for the session in which the request was sent.

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

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

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

IP Address of the client that made the request.

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

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

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

ID of the JWT token.

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

Embedded User Context.

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

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

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

The http URI that is used.

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

http method used.

+ */ + @JsonSetter(value = "method", nulls = Nulls.SKIP) + public Builder method(Optional method) { + this.method = method; + return this; + } + + public Builder method(String method) { + this.method = Optional.ofNullable(method); + return this; + } + + public AuditEventHttpInfo build() { + return new AuditEventHttpInfo(uri, method, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/BatchRecordMethod.java b/src/main/java/com/skyflow/generated/rest/types/BatchRecordMethod.java new file mode 100644 index 00000000..c50f618d --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/BatchRecordMethod.java @@ -0,0 +1,30 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum BatchRecordMethod { + NONE("NONE"), + + POST("POST"), + + PUT("PUT"), + + GET("GET"), + + DELETE("DELETE"); + + private final String value; + + BatchRecordMethod(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/CheckGuardrailsResponse.java b/src/main/java/com/skyflow/generated/rest/types/CheckGuardrailsResponse.java new file mode 100644 index 00000000..324cd1e6 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/CheckGuardrailsResponse.java @@ -0,0 +1,193 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = CheckGuardrailsResponse.Builder.class) +public final class CheckGuardrailsResponse { + private final Optional text; + + private final Optional toxicity; + + private final Optional deniedTopics; + + private final Optional validation; + + private final Map additionalProperties; + + private CheckGuardrailsResponse( + Optional text, + Optional toxicity, + Optional deniedTopics, + Optional validation, + Map additionalProperties) { + this.text = text; + this.toxicity = toxicity; + this.deniedTopics = deniedTopics; + this.validation = validation; + this.additionalProperties = additionalProperties; + } + + /** + * @return Text that was checked against guardrails. + */ + @JsonProperty("text") + public Optional getText() { + return text; + } + + /** + * @return Whether the text is toxic. + */ + @JsonProperty("toxicity") + public Optional getToxicity() { + return toxicity; + } + + /** + * @return Whether any denied topics were found. + */ + @JsonProperty("denied_topics") + public Optional getDeniedTopics() { + return deniedTopics; + } + + /** + * @return Validation result. + */ + @JsonProperty("validation") + public Optional getValidation() { + return validation; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof CheckGuardrailsResponse && equalTo((CheckGuardrailsResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(CheckGuardrailsResponse other) { + return text.equals(other.text) + && toxicity.equals(other.toxicity) + && deniedTopics.equals(other.deniedTopics) + && validation.equals(other.validation); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.text, this.toxicity, this.deniedTopics, this.validation); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional text = Optional.empty(); + + private Optional toxicity = Optional.empty(); + + private Optional deniedTopics = Optional.empty(); + + private Optional validation = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(CheckGuardrailsResponse other) { + text(other.getText()); + toxicity(other.getToxicity()); + deniedTopics(other.getDeniedTopics()); + validation(other.getValidation()); + return this; + } + + /** + *

Text that was checked against guardrails.

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

Whether the text is toxic.

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

Whether any denied topics were found.

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

Validation result.

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

URL or base64-encoded data of the output.

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

Type of the processed file.

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

Extension of the processed file.

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

Status URL for the detect run.

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

How the input file was specified.

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

Number of words in the processed text.

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

Number of characters in the processed text.

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

Size of the processed text in kilobytes (KB).

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

Duration of the processed audio in seconds.

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

Number of pages in the processed PDF.

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

Number of slides in the processed presentation.

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

Status of the detect run.

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

How the output file is specified.

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

Status details about the detect run.

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

Number of slides in the processed presentation.

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

Number of slides in the processed presentation.

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

Number of pages in the processed PDF.

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

Number of pages in the processed PDF.

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

Duration of the processed audio in seconds.

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

Duration of the processed audio in seconds.

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

Size of the processed text in kilobytes (KB).

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

Size of the processed text in kilobytes (KB).

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

Number of characters in the processed text.

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

Number of characters in the processed text.

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

Number of words in the processed text.

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

Number of words in the processed text.

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

How the input file was specified.

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

How the input file was specified.

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

How the input file was specified.

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

Detected entities.

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

De-identified text.

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

Number of words from the input text.

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

Number of characters from the input text.

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

Detected entities.

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

Detected entities.

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

Detected entities.

+ */ + @java.lang.Override + @JsonSetter(value = "entities", nulls = Nulls.SKIP) + public _FinalStage entities(List entities) { + this.entities.clear(); + this.entities.addAll(entities); + return this; + } + + @java.lang.Override + public DeidentifyStringResponse build() { + return new DeidentifyStringResponse( + processedText, entities, wordCount, characterCount, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/DetectedEntity.java b/src/main/java/com/skyflow/generated/rest/types/DetectedEntity.java new file mode 100644 index 00000000..6de2200a --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/DetectedEntity.java @@ -0,0 +1,217 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = DetectedEntity.Builder.class) +public final class DetectedEntity { + private final Optional token; + + private final Optional value; + + private final Optional location; + + private final Optional entityType; + + private final Optional> entityScores; + + private final Map additionalProperties; + + private DetectedEntity( + Optional token, + Optional value, + Optional location, + Optional entityType, + Optional> entityScores, + Map additionalProperties) { + this.token = token; + this.value = value; + this.location = location; + this.entityType = entityType; + this.entityScores = entityScores; + this.additionalProperties = additionalProperties; + } + + /** + * @return Processed text of the entity. + */ + @JsonProperty("token") + public Optional getToken() { + return token; + } + + /** + * @return Original text of the entity. + */ + @JsonProperty("value") + public Optional getValue() { + return value; + } + + @JsonProperty("location") + public Optional getLocation() { + return location; + } + + /** + * @return Highest-rated label. + */ + @JsonProperty("entity_type") + public Optional getEntityType() { + return entityType; + } + + /** + * @return entity_scores and their scores. + */ + @JsonProperty("entity_scores") + public Optional> getEntityScores() { + return entityScores; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof DetectedEntity && equalTo((DetectedEntity) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(DetectedEntity other) { + return token.equals(other.token) + && value.equals(other.value) + && location.equals(other.location) + && entityType.equals(other.entityType) + && entityScores.equals(other.entityScores); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.token, this.value, this.location, this.entityType, this.entityScores); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional token = Optional.empty(); + + private Optional value = Optional.empty(); + + private Optional location = Optional.empty(); + + private Optional entityType = Optional.empty(); + + private Optional> entityScores = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(DetectedEntity other) { + token(other.getToken()); + value(other.getValue()); + location(other.getLocation()); + entityType(other.getEntityType()); + entityScores(other.getEntityScores()); + return this; + } + + /** + *

Processed text of the entity.

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

Original text of the entity.

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

Highest-rated label.

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

entity_scores and their scores.

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

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

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

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

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

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

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

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

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

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

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

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

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

HTTP status message.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("http_status") + public MessageStage httpStatus(@NotNull String httpStatus) { + this.httpStatus = Objects.requireNonNull(httpStatus, "httpStatus must not be null"); + return this; + } + + @java.lang.Override + @JsonSetter("message") + public _FinalStage message(@NotNull String message) { + this.message = Objects.requireNonNull(message, "message must not be null"); + return this; + } + + @java.lang.Override + public _FinalStage details(List> details) { + this.details = Optional.ofNullable(details); + return this; + } + + @java.lang.Override + @JsonSetter(value = "details", nulls = Nulls.SKIP) + public _FinalStage details(Optional>> details) { + this.details = details; + return this; + } + + @java.lang.Override + public ErrorResponseError build() { + return new ErrorResponseError(grpcCode, httpCode, httpStatus, message, details, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/GooglerpcStatus.java b/src/main/java/com/skyflow/generated/rest/types/GooglerpcStatus.java new file mode 100644 index 00000000..d0290573 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/GooglerpcStatus.java @@ -0,0 +1,144 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = GooglerpcStatus.Builder.class) +public final class GooglerpcStatus { + private final Optional code; + + private final Optional message; + + private final Optional> details; + + private final Map additionalProperties; + + private GooglerpcStatus( + Optional code, + Optional message, + Optional> details, + Map additionalProperties) { + this.code = code; + this.message = message; + this.details = details; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("code") + public Optional getCode() { + return code; + } + + @JsonProperty("message") + public Optional getMessage() { + return message; + } + + @JsonProperty("details") + public Optional> getDetails() { + return details; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof GooglerpcStatus && equalTo((GooglerpcStatus) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(GooglerpcStatus other) { + return code.equals(other.code) && message.equals(other.message) && details.equals(other.details); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.code, this.message, this.details); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional code = Optional.empty(); + + private Optional message = Optional.empty(); + + private Optional> details = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(GooglerpcStatus other) { + code(other.getCode()); + message(other.getMessage()); + details(other.getDetails()); + return this; + } + + @JsonSetter(value = "code", nulls = Nulls.SKIP) + public Builder code(Optional code) { + this.code = code; + return this; + } + + public Builder code(Integer code) { + this.code = Optional.ofNullable(code); + return this; + } + + @JsonSetter(value = "message", nulls = Nulls.SKIP) + public Builder message(Optional message) { + this.message = message; + return this; + } + + public Builder message(String message) { + this.message = Optional.ofNullable(message); + return this; + } + + @JsonSetter(value = "details", nulls = Nulls.SKIP) + public Builder details(Optional> details) { + this.details = details; + return this; + } + + public Builder details(List details) { + this.details = Optional.ofNullable(details); + return this; + } + + public GooglerpcStatus build() { + return new GooglerpcStatus(code, message, details, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/ProtobufAny.java b/src/main/java/com/skyflow/generated/rest/types/ProtobufAny.java new file mode 100644 index 00000000..37555aae --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ProtobufAny.java @@ -0,0 +1,95 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ProtobufAny.Builder.class) +public final class ProtobufAny { + private final Optional type; + + private final Map additionalProperties; + + private ProtobufAny(Optional type, Map additionalProperties) { + this.type = type; + this.additionalProperties = additionalProperties; + } + + @JsonProperty("@type") + public Optional getType() { + return type; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ProtobufAny && equalTo((ProtobufAny) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ProtobufAny other) { + return type.equals(other.type); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.type); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional type = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(ProtobufAny other) { + type(other.getType()); + return this; + } + + @JsonSetter(value = "@type", nulls = Nulls.SKIP) + public Builder type(Optional type) { + this.type = type; + return this; + } + + public Builder type(String type) { + this.type = Optional.ofNullable(type); + return this; + } + + public ProtobufAny build() { + return new ProtobufAny(type, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/RedactionEnumRedaction.java b/src/main/java/com/skyflow/generated/rest/types/RedactionEnumRedaction.java new file mode 100644 index 00000000..3e83052b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/RedactionEnumRedaction.java @@ -0,0 +1,28 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum RedactionEnumRedaction { + DEFAULT("DEFAULT"), + + REDACTED("REDACTED"), + + MASKED("MASKED"), + + PLAIN_TEXT("PLAIN_TEXT"); + + private final String value; + + RedactionEnumRedaction(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponse.java b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponse.java new file mode 100644 index 00000000..46804db0 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponse.java @@ -0,0 +1,170 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyFileResponse.Builder.class) +public final class ReidentifyFileResponse { + private final ReidentifyFileResponseStatus status; + + private final ReidentifyFileResponseOutputType outputType; + + private final ReidentifyFileResponseOutput output; + + private final Map additionalProperties; + + private ReidentifyFileResponse( + ReidentifyFileResponseStatus status, + ReidentifyFileResponseOutputType outputType, + ReidentifyFileResponseOutput output, + Map additionalProperties) { + this.status = status; + this.outputType = outputType; + this.output = output; + this.additionalProperties = additionalProperties; + } + + /** + * @return Status of the re-identify operation. + */ + @JsonProperty("status") + public ReidentifyFileResponseStatus getStatus() { + return status; + } + + /** + * @return Format of the output file. + */ + @JsonProperty("output_type") + public ReidentifyFileResponseOutputType getOutputType() { + return outputType; + } + + @JsonProperty("output") + public ReidentifyFileResponseOutput getOutput() { + return output; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyFileResponse && equalTo((ReidentifyFileResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyFileResponse other) { + return status.equals(other.status) && outputType.equals(other.outputType) && output.equals(other.output); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.status, this.outputType, this.output); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static StatusStage builder() { + return new Builder(); + } + + public interface StatusStage { + /** + * Status of the re-identify operation. + */ + OutputTypeStage status(@NotNull ReidentifyFileResponseStatus status); + + Builder from(ReidentifyFileResponse other); + } + + public interface OutputTypeStage { + /** + * Format of the output file. + */ + OutputStage outputType(@NotNull ReidentifyFileResponseOutputType outputType); + } + + public interface OutputStage { + _FinalStage output(@NotNull ReidentifyFileResponseOutput output); + } + + public interface _FinalStage { + ReidentifyFileResponse build(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder implements StatusStage, OutputTypeStage, OutputStage, _FinalStage { + private ReidentifyFileResponseStatus status; + + private ReidentifyFileResponseOutputType outputType; + + private ReidentifyFileResponseOutput output; + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + @java.lang.Override + public Builder from(ReidentifyFileResponse other) { + status(other.getStatus()); + outputType(other.getOutputType()); + output(other.getOutput()); + return this; + } + + /** + * Status of the re-identify operation.

Status of the re-identify operation.

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

Format of the output file.

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

Re-identified file content in base64 format.

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

Extension of the processed file.

+ * @return Reference to {@code this} so that method calls can be chained together. + */ + @java.lang.Override + @JsonSetter("processed_file_extension") + public _FinalStage processedFileExtension(@NotNull String processedFileExtension) { + this.processedFileExtension = + Objects.requireNonNull(processedFileExtension, "processedFileExtension must not be null"); + return this; + } + + @java.lang.Override + public ReidentifyFileResponseOutput build() { + return new ReidentifyFileResponseOutput(processedFile, processedFileExtension, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseOutputType.java b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseOutputType.java new file mode 100644 index 00000000..167cb387 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseOutputType.java @@ -0,0 +1,24 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum ReidentifyFileResponseOutputType { + BASE_64("BASE64"), + + UNKNOWN("UNKNOWN"); + + private final String value; + + ReidentifyFileResponseOutputType(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseStatus.java b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseStatus.java new file mode 100644 index 00000000..7b56adcf --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ReidentifyFileResponseStatus.java @@ -0,0 +1,28 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum ReidentifyFileResponseStatus { + FAILED("FAILED"), + + IN_PROGRESS("IN_PROGRESS"), + + SUCCESS("SUCCESS"), + + UNKNOWN("UNKNOWN"); + + private final String value; + + ReidentifyFileResponseStatus(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/ReidentifyStringResponse.java b/src/main/java/com/skyflow/generated/rest/types/ReidentifyStringResponse.java new file mode 100644 index 00000000..ba305e63 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/ReidentifyStringResponse.java @@ -0,0 +1,101 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = ReidentifyStringResponse.Builder.class) +public final class ReidentifyStringResponse { + private final Optional text; + + private final Map additionalProperties; + + private ReidentifyStringResponse(Optional text, Map additionalProperties) { + this.text = text; + this.additionalProperties = additionalProperties; + } + + /** + * @return Re-identified text. + */ + @JsonProperty("text") + public Optional getText() { + return text; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof ReidentifyStringResponse && equalTo((ReidentifyStringResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(ReidentifyStringResponse other) { + return text.equals(other.text); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.text); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional text = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(ReidentifyStringResponse other) { + text(other.getText()); + return this; + } + + /** + *

Re-identified text.

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

Entity types to replace with vault tokens.

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

Entity types to replace with entity tokens with unique counters.

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

Entity types to replace with entity tokens.

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

Entity types to replace with entity tokens with unique counters.

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

Entity types to replace with entity tokens.

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

Shift dates by a specified number of days.

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

Maximum number of days to shift the date by.

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

Minimum number of days to shift the date by.

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

Entity types to shift dates for.

+ */ + @JsonSetter(value = "entity_types", nulls = Nulls.SKIP) + public Builder entityTypes(Optional> entityTypes) { + this.entityTypes = entityTypes; + return this; + } + + public Builder entityTypes(List entityTypes) { + this.entityTypes = Optional.ofNullable(entityTypes); + return this; + } + + public TransformationsShiftDates build() { + return new TransformationsShiftDates(maxDays, minDays, entityTypes, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/TransformationsShiftDatesEntityTypesItem.java b/src/main/java/com/skyflow/generated/rest/types/TransformationsShiftDatesEntityTypesItem.java new file mode 100644 index 00000000..148cea23 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/TransformationsShiftDatesEntityTypesItem.java @@ -0,0 +1,26 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum TransformationsShiftDatesEntityTypesItem { + DATE("date"), + + DATE_INTERVAL("date_interval"), + + DOB("dob"); + + private final String value; + + TransformationsShiftDatesEntityTypesItem(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/UploadFileV2Response.java b/src/main/java/com/skyflow/generated/rest/types/UploadFileV2Response.java new file mode 100644 index 00000000..85f98bd1 --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/UploadFileV2Response.java @@ -0,0 +1,124 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = UploadFileV2Response.Builder.class) +public final class UploadFileV2Response { + private final Optional skyflowId; + + private final Optional fileMetadata; + + private final Map additionalProperties; + + private UploadFileV2Response( + Optional skyflowId, Optional fileMetadata, Map additionalProperties) { + this.skyflowId = skyflowId; + this.fileMetadata = fileMetadata; + this.additionalProperties = additionalProperties; + } + + /** + * @return Skyflow ID of the record the file was uploaded to. + */ + @JsonProperty("skyflowID") + public Optional getSkyflowId() { + return skyflowId; + } + + @JsonProperty("fileMetadata") + public Optional getFileMetadata() { + return fileMetadata; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof UploadFileV2Response && equalTo((UploadFileV2Response) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(UploadFileV2Response other) { + return skyflowId.equals(other.skyflowId) && fileMetadata.equals(other.fileMetadata); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.skyflowId, this.fileMetadata); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional skyflowId = Optional.empty(); + + private Optional fileMetadata = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(UploadFileV2Response other) { + skyflowId(other.getSkyflowId()); + fileMetadata(other.getFileMetadata()); + return this; + } + + /** + *

Skyflow ID of the record the file was uploaded to.

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

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

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

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

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

The status of the overall operation.

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

The status message for the overall operation.

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

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

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

Events matching the query.

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

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

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

ID of the account that made the request.

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

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

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

API name.

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

The workspaceID (if any) of the request.

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

The vaultID (if any) of the request.

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

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

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

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

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

ID of the vault.

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

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

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

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

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

Name of the table to perform the operation on.

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

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

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

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

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

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

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

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

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

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

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

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

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

Card metadata associated with the specified BIN.

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

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

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

The specified records.

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

BIN of the card.

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

Name of the card issuer bank.

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

Country code of the card.

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

Currency of the card.

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

Type of the card.

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

Category of the card.

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

Scheme of the card.

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

Last four digits of the card number.

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

Expiry date of the card.

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

ID of the record.

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

If true, the file was deleted.

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

ID of the deleted record.

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

If true, the record was deleted.

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

Token that identifies the record to detokenize.

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

Token of the record.

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

Data corresponding to the token.

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

Error if token isn't found.

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

Records corresponding to the specified tokens.

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

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

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

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

+ */ + @JsonSetter(value = "tokens", nulls = Nulls.SKIP) + public Builder tokens(Optional> tokens) { + this.tokens = tokens; + return this; + } + + public Builder tokens(Map tokens) { + this.tokens = Optional.ofNullable(tokens); + return this; + } + + public V1FieldRecords build() { + return new V1FieldRecords(fields, tokens, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1FileAvScanStatus.java b/src/main/java/com/skyflow/generated/rest/types/V1FileAvScanStatus.java new file mode 100644 index 00000000..afe545fe --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1FileAvScanStatus.java @@ -0,0 +1,38 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonValue; + +public enum V1FileAvScanStatus { + SCAN_NONE("SCAN_NONE"), + + SCAN_CLEAN("SCAN_CLEAN"), + + SCAN_INFECTED("SCAN_INFECTED"), + + SCAN_DELETED("SCAN_DELETED"), + + SCAN_ERROR("SCAN_ERROR"), + + SCAN_PENDING("SCAN_PENDING"), + + SCAN_UNSCANNABLE("SCAN_UNSCANNABLE"), + + SCAN_FILE_NOT_FOUND("SCAN_FILE_NOT_FOUND"), + + SCAN_INVALID("SCAN_INVALID"); + + private final String value; + + V1FileAvScanStatus(String value) { + this.value = value; + } + + @JsonValue + @java.lang.Override + public String toString() { + return this.value; + } +} diff --git a/src/main/java/com/skyflow/generated/rest/types/V1GetAuthTokenResponse.java b/src/main/java/com/skyflow/generated/rest/types/V1GetAuthTokenResponse.java new file mode 100644 index 00000000..9b6be70b --- /dev/null +++ b/src/main/java/com/skyflow/generated/rest/types/V1GetAuthTokenResponse.java @@ -0,0 +1,130 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ +package com.skyflow.generated.rest.types; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.skyflow.generated.rest.core.ObjectMappers; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +@JsonInclude(JsonInclude.Include.NON_ABSENT) +@JsonDeserialize(builder = V1GetAuthTokenResponse.Builder.class) +public final class V1GetAuthTokenResponse { + private final Optional accessToken; + + private final Optional tokenType; + + private final Map additionalProperties; + + private V1GetAuthTokenResponse( + Optional accessToken, Optional tokenType, Map additionalProperties) { + this.accessToken = accessToken; + this.tokenType = tokenType; + this.additionalProperties = additionalProperties; + } + + /** + * @return AccessToken. + */ + @JsonProperty("accessToken") + public Optional getAccessToken() { + return accessToken; + } + + /** + * @return TokenType : Bearer. + */ + @JsonProperty("tokenType") + public Optional getTokenType() { + return tokenType; + } + + @java.lang.Override + public boolean equals(Object other) { + if (this == other) return true; + return other instanceof V1GetAuthTokenResponse && equalTo((V1GetAuthTokenResponse) other); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + private boolean equalTo(V1GetAuthTokenResponse other) { + return accessToken.equals(other.accessToken) && tokenType.equals(other.tokenType); + } + + @java.lang.Override + public int hashCode() { + return Objects.hash(this.accessToken, this.tokenType); + } + + @java.lang.Override + public String toString() { + return ObjectMappers.stringify(this); + } + + public static Builder builder() { + return new Builder(); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class Builder { + private Optional accessToken = Optional.empty(); + + private Optional tokenType = Optional.empty(); + + @JsonAnySetter + private Map additionalProperties = new HashMap<>(); + + private Builder() {} + + public Builder from(V1GetAuthTokenResponse other) { + accessToken(other.getAccessToken()); + tokenType(other.getTokenType()); + return this; + } + + /** + *

AccessToken.

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

TokenType : Bearer.

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

Records returned by the query.

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

Identifiers for the inserted records.

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

ID of the inserted record.

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

Tokens for the record.

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

Existing value to return a token for.

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

Name of the column group that the value belongs to.

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

Token corresponding to a value.

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

Tokens corresponding to the specified values.

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

ID of the updated record.

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

Tokens for the record.

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

Name of the column that stores the card number.

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

Name of the column that stores the card number suffix.

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

Name of the column that stores the expiry date.

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

ID of the vault that stores card details.

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

Name of the table that stores card details.

+ */ + @JsonSetter(value = "table_name", nulls = Nulls.SKIP) + public Builder tableName(Optional tableName) { + this.tableName = tableName; + return this; + } + + public Builder tableName(String tableName) { + this.tableName = Optional.ofNullable(tableName); + return this; + } + + @JsonSetter(value = "mapping", nulls = Nulls.SKIP) + public Builder mapping(Optional mapping) { + this.mapping = mapping; + return this; + } + + public Builder mapping(V1VaultFieldMapping mapping) { + this.mapping = Optional.ofNullable(mapping); + return this; + } + + public V1VaultSchemaConfig build() { + return new V1VaultSchemaConfig(id, tableName, mapping, additionalProperties); + } + } +} diff --git a/src/main/java/com/skyflow/logs/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..eb5ea742 100644 --- a/src/main/java/com/skyflow/logs/ErrorLogs.java +++ b/src/main/java/com/skyflow/logs/ErrorLogs.java @@ -1,62 +1,141 @@ -/* - 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_TOKEN_MODE_DISABLE("Invalid %s1 request. Tokens are not allowed when tokenMode is DISABLE."), + TOKENS_REQUIRED_WITH_TOKEN_MODE("Invalid %s1 request. Tokens are required when tokenMode is %s2."), + EMPTY_TOKENS("Invalid %s1 request. Tokens can not be empty."), + EMPTY_OR_NULL_VALUE_IN_TOKENS("Invalid %s1 request. Value can not be null or empty in tokens for key \"%s2\"."), + EMPTY_OR_NULL_KEY_IN_TOKENS("Invalid %s1 request. Key can not be null or empty in tokens."), + INSUFFICIENT_TOKENS_PASSED_FOR_TOKEN_MODE_ENABLE_STRICT("Invalid %s1 request. For tokenMode as ENABLE_STRICT, tokens should be passed for all fields."), + MISMATCH_OF_FIELDS_AND_TOKENS("Invalid %s1 request. Keys for values and tokens are not matching."), + INSERT_RECORDS_REJECTED("Insert request resulted in failure."), + DETOKENIZE_DATA_REQUIRED("Invalid %s1 request. Detokenize data is required."), + EMPTY_DETOKENIZE_DATA("Invalid %s1 request. Detokenize data can not be empty."), + EMPTY_OR_NULL_TOKEN_IN_DETOKENIZE_DATA("Invalid %s1 request. Token can not be null or empty in detokenize data at index %s2."), + REDACTION_IS_REQUIRED("Invalid %s1 request. Redaction is required."), + DETOKENIZE_REQUEST_REJECTED("Detokenize request resulted in failure."), + IDS_IS_REQUIRED("Invalid %s1 request. Ids are required."), + 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."), + + // File upload interface + COLUMN_NAME_IS_REQUIRED_FILE_UPLOAD("Invalid %s1 request. Column name is required."), + EMPTY_COLUMN_NAME_FILE_UPLOAD("Invalid %s1 request. Column name can not be empty."), + FILE_IS_REQUIRED("Invalid %s1 request. File is required."), + EMPTY_FILE("Invalid %s1 request. File can not be empty."), + INVALID_FILE_TYPE("Invalid %s1 request. File should be of type java.io.File"), + MISSING_FILE_SOURCE_IN_UPLOAD_FILE("Invalid %s1 request. Provide exactly one of filePath, base64, or fileObject."), + UPLOAD_FILE_REQUEST_REJECTED("Upload file request resulted in failure."), + + + // detect interface + INVALID_TEXT_IN_DEIDENTIFY("Invalid %s1 request. The text field is required and must be a non-empty string. Specify a valid text."), + DEIDENTIFY_TEXT_REQUEST_REJECTED("DeIdentify text request resulted in failure."), + INVALID_TEXT_IN_REIDENTIFY("Invalid %s1 request. The text field is required and must be a non-empty string. Specify a valid text."), + REIDENTIFY_TEXT_REQUEST_REJECTED("ReIdentify text request resulted in failure."), + DEIDENTIFY_FILE_REQUEST_REJECTED("DeIdentify file request resulted in failure."), + GET_DETECT_RUN_REQUEST_REJECTED("Get detect run request resulted in failure."), + INVALID_NULL_FILE_IN_DEIDENTIFY_FILE("Invalid %s1 request. The file field is required and must not be null. Specify a valid file."), + FILE_NOT_FOUND_TO_DEIDENTIFY("Invalid %s1 request. The file field is required and must not be empty. Specify a valid file."), + FILE_NOT_READABLE_TO_DEIDENTIFY("Invalid %s1 request. The file is not readable. Please check the file permissions or path."), + INVALID_PIXEL_DENSITY_TO_DEIDENTIFY_FILE("Invalid %s1 request. Pixel density must be a positive integer greater than 0. Specify a valid pixel density."), + INVALID_MAX_RESOLUTION("Invalid %s1 request. Max resolution must be a positive integer greater than 0. Specify a valid max resolution."), + INVALID_BLEEP_TO_DEIDENTIFY_AUDIO("Invalid %s1 request. Specify a valid bleep as AudioBleep"), + OUTPUT_DIRECTORY_NOT_FOUND("Invalid %s1 request. The output directory does not exist. Please specify a valid output directory."), + INVALID_PERMISSIONS_FOR_OUTPUT_DIRECTORY("Invalid %s1 request. The output directory is not writable. Please check the permissions or specify a valid output directory."), + EMPTY_FILE_AND_FILE_PATH_IN_DEIDENTIFY_FILE("Invalid %s1 request. The file and file path fields are both empty. Specify a valid file object or file path."), + ; private final String log; diff --git a/src/main/java/com/skyflow/logs/InfoLogs.java b/src/main/java/com/skyflow/logs/InfoLogs.java index 33728a3a..f71fc416 100644 --- a/src/main/java/com/skyflow/logs/InfoLogs.java +++ b/src/main/java/com/skyflow/logs/InfoLogs.java @@ -1,39 +1,110 @@ -/* - 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."), + DETECT_CONTROLLER_INITIALIZED("Initialized detect controller with vault ID %s1."), + CONNECTION_CONTROLLER_INITIALIZED("Initialized connection controller with connection ID %s1."), + LOGGER_SETUP_DONE("Set up logger."), + CURRENT_LOG_LEVEL("Current log level is %s1."), + + // 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."), + + // File upload interface + FILE_UPLOAD_TRIGGERED("File upload method triggered."), + VALIDATING_FILE_UPLOAD_REQUEST("Validating file upload request."), + FILE_UPLOAD_REQUEST_RESOLVED("File upload request resolved."), + FILE_UPLOAD_SUCCESS("File uploaded successfully."), + + // Invoke connection interface + INVOKE_CONNECTION_TRIGGERED("Invoke connection method triggered."), + VALIDATING_INVOKE_CONNECTION_REQUEST("Validating invoke connection request."), + INVOKE_CONNECTION_REQUEST_RESOLVED("Invoke connection request resolved."), + + // detect + VALIDATE_DEIDENTIFY_TEXT_REQUEST("Validating deidentify text request."), + DEIDENTIFY_TEXT_SUCCESS("Text data de-identified."), + DEIDENTIFY_TEXT_TRIGGERED("DeIdentify text method triggered."), + DEIDENTIFY_TEXT_REQUEST_RESOLVED("DeIdentify text request resolved."), + VALIDATE_REIDENTIFY_TEXT_REQUEST("Validating reidentify text request."), + REIDENTIFY_TEXT_TRIGGERED("ReIdentify text method triggered."), + REIDENTIFY_TEXT_REQUEST_RESOLVED("ReIdentify text request resolved."), + DEIDENTIFY_FILE_TRIGGERED("DeIdentify file method triggered."), + VALIDATE_DEIDENTIFY_FILE_REQUEST("Validating deidentify file request."), + DEIDENTIFY_FILE_REQUEST_RESOLVED("DeIdentify file request resolved."), + DEIDENTIFY_FILE_SUCCESS("File deidentified successfully."), + GET_DETECT_RUN_TRIGGERED("Get detect run method triggered."), + VALIDATE_GET_DETECT_RUN_REQUEST("Validating get detect run request."), + REIDENTIFY_TEXT_SUCCESS("Text data re-identified."), + ; + + private final String log; 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..23d09ab8 100644 --- a/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java +++ b/src/main/java/com/skyflow/serviceaccount/util/BearerToken.java @@ -1,40 +1,39 @@ -/* - 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.*; 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.ApiClientBuilder; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.resources.authentication.AuthenticationClient; +import com.skyflow.generated.rest.resources.authentication.requests.V1GetAuthTokenRequest; +import com.skyflow.generated.rest.types.V1GetAuthTokenResponse; import com.skyflow.logs.ErrorLogs; import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.Constants; +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 Gson gson = new GsonBuilder().serializeNulls().create(); + private static final ApiClientBuilder apiClientBuilder = new ApiClientBuilder(); private final File credentialsFile; private final String credentialsString; private final String ctx; - - private final String[] roles; - + private final ArrayList roles; private final String credentialsType; private BearerToken(BearerTokenBuilder builder) { @@ -45,167 +44,111 @@ 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) { + 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()); + apiClientBuilder.url(basePath); + ApiClient apiClient = apiClientBuilder.token("token").build(); + AuthenticationClient authenticationApi = apiClient.authentication(); - Map headers = new HashMap<>(); - headers.put(Constants.SDK_METRICS_HEADER_KEY, Helpers.getMetrics().toJSONString()); + V1GetAuthTokenRequest._FinalStage authTokenBuilder = V1GetAuthTokenRequest.builder().grantType(Constants.GRANT_TYPE).assertion(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); + authTokenBuilder.scope(scopedRoles); } - - String response = HttpUtility.sendRequest("POST", new URL(tokenURI), parameters, headers); - - responseToken = new ObjectMapper().readValue(response, ResponseToken.class); - - } catch (IOException e) { - LogUtil.printErrorLog(ErrorLogs.UnableToReadResponse.getLog()); - throw new SkyflowException(ErrorCode.UnableToReadResponse, e); + return authenticationApi.authenticationServiceGetAuthToken(authTokenBuilder.build()); + } catch (MalformedURLException e) { + LogUtil.printErrorLog(ErrorLogs.INVALID_TOKEN_URI.getLog()); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidTokenUri.getMessage()); + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.BEARER_TOKEN_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); } - - 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 +160,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 +169,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().get(); + } else if (this.credentialsString != null && Objects.equals(this.credentialsType, "STRING")) { + response = generateBearerTokenFromCredentialString(this.credentialsString, this.ctx, this.roles); + accessToken = response.getAccessToken().get(); + } + 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..7c9f4674 100644 --- a/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java +++ b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokenResponse.java @@ -1,20 +1,29 @@ -/* - Copyright (c) 2022 Skyflow, Inc. -*/ package com.skyflow.serviceaccount.util; +import com.google.gson.Gson; +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 token; + private final String signedToken; + + public SignedDataTokenResponse(String token, String signedToken) { + this.token = token; + this.signedToken = new StringBuilder(prefix).append(signedToken).toString(); + } - public SignedDataTokenResponse(String dataToken, String signedDataToken) { - this.dataToken = dataToken; - this.signedDataToken = signedDataToken; + public String getToken() { + return token; + } + + public String getSignedToken() { + return signedToken; } @Override public String toString() { - return "{" + "dataToken: " + dataToken + "," + "signedDataToken: " + signedDataToken + "}"; - + Gson gson = new Gson(); + return gson.toJson(this); } } diff --git a/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java b/src/main/java/com/skyflow/serviceaccount/util/SignedDataTokens.java index d31c5b85..ecdfa89f 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) { + 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..f12e6a48 --- /dev/null +++ b/src/main/java/com/skyflow/utils/Constants.java @@ -0,0 +1,31 @@ +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; + public static final String SDK_METRIC_NAME_VERSION = "sdk_name_version"; + public static final String SDK_METRIC_NAME_VERSION_PREFIX = "skyflow-java@"; + public static final String SDK_METRIC_CLIENT_DEVICE_MODEL = "sdk_client_device_model"; + public static final String SDK_METRIC_CLIENT_OS_DETAILS = "sdk_client_os_details"; + public static final String SDK_METRIC_RUNTIME_DETAILS = "sdk_runtime_details"; + public static final String SDK_METRIC_RUNTIME_DETAILS_PREFIX = "Java@"; + public static final String SDK_AUTH_HEADER_KEY = "x-skyflow-authorization"; + public static final String SDK_METRICS_HEADER_KEY = "sky-metadata"; + public static final String REQUEST_ID_HEADER_KEY = "x-request-id"; + public static final String PROCESSED_FILE_NAME_PREFIX = "processed-"; + public static final String ERROR_FROM_CLIENT_HEADER_KEY = "error-from-client"; + public static final String DEIDENTIFIED_FILE_PREFIX = "deidentified"; +} 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..b8e9283b --- /dev/null +++ b/src/main/java/com/skyflow/utils/HttpUtility.java @@ -0,0 +1,165 @@ +package com.skyflow.utils; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +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.List; +import java.util.Map; +import java.util.Objects; + +public final class HttpUtility { + + private static final String LINE_FEED = "\r\n"; + 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.isEmpty()) { + for (Map.Entry entry : headers.entrySet()) + connection.setRequestProperty(entry.getKey(), entry.getValue()); + + // append dynamic boundary if content-type is multipart/form-data + if (headers.containsKey("content-type")) { + if (Objects.equals(headers.get("content-type"), "multipart/form-data")) { + connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary); + } + } + } + if (params != null && !params.isEmpty()) { + 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 httpCode = connection.getResponseCode(); + String requestID = connection.getHeaderField("x-request-id"); + HttpUtility.requestID = requestID.split(",")[0]; + Map> responseHeaders = connection.getHeaderFields(); + Reader streamReader; + if (httpCode > 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 (httpCode > 299) { + throw new SkyflowException(httpCode, new Throwable(), responseHeaders, response.toString()); + } + } 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<>(); + Map jsonMap = json.asMap(); + for (String key : jsonMap.keySet()) { + JsonElement currentValue = jsonMap.get(key); + String currentKey = !rootKey.isEmpty() ? rootKey + '[' + key + ']' : rootKey + key; + if (currentValue.isJsonObject()) { + currentMap.putAll(convertJsonToMap((JsonObject) currentValue, currentKey)); + } else { + currentMap.put(currentKey, currentValue.getAsString()); + } + } + 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; + } + + 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..cc8d572a --- /dev/null +++ b/src/main/java/com/skyflow/utils/Utils.java @@ -0,0 +1,202 @@ +package com.skyflow.utils; + +import com.google.gson.JsonObject; +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.logs.InfoLogs; +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; + } + + 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; + } + + public static JsonObject getMetrics() { + JsonObject details = new JsonObject(); + String sdkVersion = Constants.SDK_VERSION; + String deviceModel; + String osDetails; + String javaVersion; + // Retrieve device model + try { + deviceModel = System.getProperty("os.name"); + if (deviceModel == null) throw new Exception(); + } catch (Exception e) { + LogUtil.printInfoLog(parameterizedString( + InfoLogs.UNABLE_TO_GENERATE_SDK_METRIC.getLog(), + Constants.SDK_METRIC_CLIENT_DEVICE_MODEL + )); + deviceModel = ""; + } + + // Retrieve OS details + try { + osDetails = System.getProperty("os.version"); + if (osDetails == null) throw new Exception(); + } catch (Exception e) { + LogUtil.printInfoLog(parameterizedString( + InfoLogs.UNABLE_TO_GENERATE_SDK_METRIC.getLog(), + Constants.SDK_METRIC_CLIENT_OS_DETAILS + )); + osDetails = ""; + } + + // Retrieve Java version details + try { + javaVersion = System.getProperty("java.version"); + if (javaVersion == null) throw new Exception(); + } catch (Exception e) { + LogUtil.printInfoLog(parameterizedString( + InfoLogs.UNABLE_TO_GENERATE_SDK_METRIC.getLog(), + Constants.SDK_METRIC_RUNTIME_DETAILS + )); + javaVersion = ""; + } + details.addProperty(Constants.SDK_METRIC_NAME_VERSION, Constants.SDK_METRIC_NAME_VERSION_PREFIX + sdkVersion); + details.addProperty(Constants.SDK_METRIC_CLIENT_DEVICE_MODEL, deviceModel); + details.addProperty(Constants.SDK_METRIC_RUNTIME_DETAILS, Constants.SDK_METRIC_RUNTIME_DETAILS_PREFIX + javaVersion); + details.addProperty(Constants.SDK_METRIC_CLIENT_OS_DETAILS, osDetails); + return details; + } + + 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; + } +} 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..0372749a --- /dev/null +++ b/src/main/java/com/skyflow/utils/validations/Validations.java @@ -0,0 +1,982 @@ +package com.skyflow.utils.validations; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.skyflow.config.ConnectionConfig; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.InterfaceName; +import com.skyflow.enums.RedactionType; +import com.skyflow.enums.TokenMode; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +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.detect.*; +import com.skyflow.vault.tokens.ColumnValue; +import com.skyflow.vault.tokens.DetokenizeData; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.TokenizeRequest; + +import java.io.File; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Validations { + private 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) { + Gson gson = new Gson(); + JsonObject bodyObject = gson.toJsonTree(requestBody).getAsJsonObject(); + if (bodyObject.isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_REQUEST_BODY.getLog(), InterfaceName.INVOKE_CONNECTION.getName())); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestBody.getMessage()); + } + } + } + + 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 detokenizeData = detokenizeRequest.getDetokenizeData(); + if (detokenizeData == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.DETOKENIZE_DATA_REQUIRED.getLog(), InterfaceName.DETOKENIZE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidDetokenizeData.getMessage()); + } else if (detokenizeData.isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_DETOKENIZE_DATA.getLog(), InterfaceName.DETOKENIZE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyDetokenizeData.getMessage()); + } else { + for (int index = 0; index < detokenizeData.size(); index++) { + String token = detokenizeData.get(index).getToken(); + if (token == null || token.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_TOKEN_IN_DETOKENIZE_DATA.getLog(), + InterfaceName.DETOKENIZE.getName(), Integer.toString(index) + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTokenInDetokenizeData.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(); + TokenMode tokenMode = insertRequest.getTokenMode(); + + 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 (tokenMode) { + case DISABLE: + if (tokens != null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.TOKENS_NOT_ALLOWED_WITH_TOKEN_MODE_DISABLE.getLog(), InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TokensPassedForTokenModeDisable.getMessage()); + } + break; + case ENABLE: + if (tokens == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.TOKENS_REQUIRED_WITH_TOKEN_MODE.getLog(), + InterfaceName.INSERT.getName(), TokenMode.ENABLE.toString() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + Utils.parameterizedString(ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE.toString()) + ); + } + validateTokensForInsertRequest(tokens, values, tokenMode); + break; + case ENABLE_STRICT: + if (tokens == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.TOKENS_REQUIRED_WITH_TOKEN_MODE.getLog(), + InterfaceName.INSERT.getName(), TokenMode.ENABLE_STRICT.toString() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + Utils.parameterizedString(ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE_STRICT.toString()) + ); + } else if (tokens.size() != values.size()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_TOKEN_MODE_ENABLE_STRICT.getLog(), + InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.InsufficientTokensPassedForTokenModeEnableStrict.getMessage() + ); + } + validateTokensForInsertRequest(tokens, values, tokenMode); + 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 (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(); + TokenMode tokenMode = updateRequest.getTokenMode(); + + 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 (tokenMode) { + case DISABLE: + if (tokens != null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.TOKENS_NOT_ALLOWED_WITH_TOKEN_MODE_DISABLE.getLog(), InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.TokensPassedForTokenModeDisable.getMessage()); + } + break; + case ENABLE: + if (tokens == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.TOKENS_REQUIRED_WITH_TOKEN_MODE.getLog(), + InterfaceName.UPDATE.getName(), TokenMode.ENABLE.toString() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( + ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE.toString())); + } + validateTokensMapWithTokenStrict(tokens, data); + break; + case ENABLE_STRICT: + if (tokens == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.TOKENS_REQUIRED_WITH_TOKEN_MODE.getLog(), + InterfaceName.UPDATE.getName(), TokenMode.ENABLE_STRICT.toString() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), Utils.parameterizedString( + ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE_STRICT.toString())); + } else if (tokens.size() != (data.size() - 1)) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_TOKEN_MODE_ENABLE_STRICT.getLog(), + InterfaceName.UPDATE.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.InsufficientTokensPassedForTokenModeEnableStrict.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 == null || 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()); + } + } + } + } + + public static void validateFileUploadRequest(FileUploadRequest fileUploadRequest) throws SkyflowException { + if (fileUploadRequest == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_REQUEST_BODY.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestBody.getMessage()); + } + + String table = fileUploadRequest.getTable(); + if (table == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.TABLE_IS_REQUIRED.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.TableKeyError.getMessage()); + } else if (table.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_TABLE_NAME.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyTable.getMessage()); + } + + String skyflowId = fileUploadRequest.getSkyflowId(); + if (skyflowId == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.SKYFLOW_ID_IS_REQUIRED.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.SkyflowIdKeyError.getMessage()); + } else if (skyflowId.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_SKYFLOW_ID.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptySkyflowId.getMessage()); + } + + String columnName = fileUploadRequest.getColumnName(); + if (columnName == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.COLUMN_NAME_IS_REQUIRED_FILE_UPLOAD.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.ColumnNameKeyErrorFileUpload.getMessage()); + } else if (columnName.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_COLUMN_NAME.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyColumnName.getMessage()); + } + + String filePath = fileUploadRequest.getFilePath(); + String base64 = fileUploadRequest.getBase64(); + File fileObject = fileUploadRequest.getFileObject(); + String fileName = fileUploadRequest.getFileName(); + + // Check if at least one (path, base64, fileObject) is provided + if (isNullOrEmpty(filePath) && isNullOrEmpty(base64) && fileObject == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.MISSING_FILE_SOURCE_IN_UPLOAD_FILE.getLog(), InterfaceName.FILE_UPLOAD.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.MissingFileSourceInUploadFileRequest.getMessage()); + } + + // Check filePath + if (!isNullOrEmpty(filePath)) { + File f = new File(filePath); + if (!f.exists() || !f.isFile()) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidFilePath.getMessage()); + } + } + + // Check base64 + if (!isNullOrEmpty(base64)) { + if (isNullOrEmpty(fileName)) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FileNameMustBeProvidedWithFileObject.getMessage()); + } + // Validate if Base64 is actually valid + try { + java.util.Base64.getDecoder().decode(base64); + } catch (IllegalArgumentException e) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidBase64.getMessage()); + } + } + + // Check fileObject + if (fileObject != null) { + if (!fileObject.exists() || !fileObject.isFile()) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidFileObject.getMessage()); + } + } + } + + private static boolean isNullOrEmpty(String str) { + return str == null || str.trim().isEmpty(); + } + + public static void validateDeidentifyTextRequest(DeidentifyTextRequest deidentifyTextRequest) throws SkyflowException { + // Validate required fields + String deidentifyText = deidentifyTextRequest.getText(); + if (deidentifyText == null || deidentifyText.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_TEXT_IN_DEIDENTIFY.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidTextInDeIdentify.getMessage()); + } + } + + public static void validateReidentifyTextRequest(ReidentifyTextRequest reidentifyTextRequest) throws SkyflowException { + // Validate required fields + String reidentifyText = reidentifyTextRequest.getText(); + if (reidentifyText == null || reidentifyText.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_TEXT_IN_REIDENTIFY.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidTextInReIdentify.getMessage()); + } + } + + private static boolean isInvalidURL(String configURL) { + try { + URL url = new URL(configURL); + if (!url.getProtocol().equals("https")) throw new Exception(); + } catch (Exception e) { + return true; + } + return false; + } + + private static void validateTokensForInsertRequest( + ArrayList> tokens, + ArrayList> values, + TokenMode 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 == TokenMode.ENABLE_STRICT) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INSUFFICIENT_TOKENS_PASSED_FOR_TOKEN_MODE_ENABLE_STRICT.getLog(), + InterfaceName.INSERT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), + ErrorMessage.InsufficientTokensPassedForTokenModeEnableStrict.getMessage() + ); + } + validateTokensMapWithTokenStrict(tokensMap, valuesMap, InterfaceName.INSERT.getName()); + } + } + + private static void validateTokensMapWithTokenStrict( + HashMap tokensMap, HashMap valuesMap + ) throws SkyflowException { + validateTokensMapWithTokenStrict(tokensMap, valuesMap, InterfaceName.UPDATE.getName()); + } + + private static void validateTokensMapWithTokenStrict( + HashMap tokensMap, HashMap valuesMap, String interfaceName + ) throws SkyflowException { + for (String key : tokensMap.keySet()) { + if (key == null || key.trim().isEmpty()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_OR_NULL_KEY_IN_TOKENS.getLog(), interfaceName + )); + 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 + )); + 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, key + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyValueInTokens.getMessage()); + } + } + } + } + + public static void validateDeidentifyFileRequest(DeidentifyFileRequest request) throws SkyflowException { + if (request == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_REQUEST_BODY.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestBody.getMessage()); + } + + TokenFormat tokenFormat = request.getTokenFormat(); + if (tokenFormat != null && tokenFormat.getVaultToken() != null && !tokenFormat.getVaultToken().isEmpty()) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.VaultTokenFormatIsNotAllowedForFiles.getMessage()); + } + + File file = request.getFileInput().getFile(); + String filePath = request.getFileInput().getFilePath(); + + if (file == null && filePath == null) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.EMPTY_FILE_AND_FILE_PATH_IN_DEIDENTIFY_FILE.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyFileAndFilePathInDeIdentifyFile.getMessage()); + } + + if (filePath != null && file != null) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.BothFileAndFilePathProvided.getMessage()); + } + + if (filePath != null && filePath.trim().isEmpty()){ + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidFilePath.getMessage()); + } + + if (file != null && (!file.exists() || !file.isFile())) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.FILE_NOT_FOUND_TO_DEIDENTIFY.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FileNotFoundToDeidentify.getMessage()); + } + if (file != null && !file.canRead()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.FILE_NOT_READABLE_TO_DEIDENTIFY.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FileNotReadableToDeidentify.getMessage()); + } + + + // Validate pixelDensity and maxResolution + if (request.getPixelDensity() != null && request.getPixelDensity().doubleValue() <= 0) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_PIXEL_DENSITY_TO_DEIDENTIFY_FILE.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidPixelDensityToDeidentifyFile.getMessage()); + } + if (request.getMaxResolution() != null && request.getMaxResolution().doubleValue() <= 0) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_MAX_RESOLUTION.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidMaxResolution.getMessage()); + } + + // Validate AudioBleep + if (request.getBleep() != null) { + if (request.getBleep().getFrequency() == null || request.getBleep().getFrequency() <= 0) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_BLEEP_TO_DEIDENTIFY_AUDIO.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); + } + if (request.getBleep().getStartPadding() == null || request.getBleep().getStartPadding() < 0) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); + } + if (request.getBleep().getStopPadding() == null || request.getBleep().getStopPadding() < 0) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidRequestBody.getMessage()); + } + } + + // Validate outputDirectory if provided + if (request.getOutputDirectory() != null) { + File outDir = new File(request.getOutputDirectory()); + if (!outDir.exists() || !outDir.isDirectory()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.OUTPUT_DIRECTORY_NOT_FOUND.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.OutputDirectoryNotFound.getMessage()); + } + if (!outDir.canWrite()) { + LogUtil.printErrorLog(Utils.parameterizedString( + ErrorLogs.INVALID_PERMISSIONS_FOR_OUTPUT_DIRECTORY.getLog(), InterfaceName.DETECT.getName() + )); + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidPermission.getMessage()); + } + } + + // Validate waitTime if provided + if (request.getWaitTime() != null && request.getWaitTime() <= 0) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidWaitTime.getMessage()); + } + if(request.getWaitTime() > 64) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.WaitTimeExceedsLimit.getMessage()); + } + } + + public static void validateGetDetectRunRequest(GetDetectRunRequest request) throws SkyflowException { + if (request == null) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.EmptyRequestBody.getMessage()); + } + + String runId = request.getRunId(); + if (runId == null || runId.trim().isEmpty()) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.InvalidOrEmptyRunId.getMessage()); + } + } +} diff --git a/src/main/java/com/skyflow/vault/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..ea71cd0a --- /dev/null +++ b/src/main/java/com/skyflow/vault/connection/InvokeConnectionRequest.java @@ -0,0 +1,82 @@ +package com.skyflow.vault.connection; + +import com.skyflow.enums.RequestMethod; + +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 getMethod() { + return builder.method; + } + + 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 method; + private Map pathParams; + private Map queryParams; + private Map requestHeaders; + private Object requestBody; + + private InvokeConnectionRequestBuilder() { + this.method = RequestMethod.POST; + this.requestBody = new Object(); + } + + public InvokeConnectionRequestBuilder method(RequestMethod method) { + this.method = method == null ? RequestMethod.POST : method; + 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..1a81eca0 --- /dev/null +++ b/src/main/java/com/skyflow/vault/connection/InvokeConnectionResponse.java @@ -0,0 +1,37 @@ +package com.skyflow.vault.connection; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.util.ArrayList; +import java.util.HashMap; + +public class InvokeConnectionResponse { + private final Object data; + private final HashMap metadata; + private final ArrayList> errors; + + public InvokeConnectionResponse(Object data, HashMap metadata, ArrayList> errors) { + this.data = data; + this.metadata = metadata; + this.errors = errors; + } + + public Object getData() { + return data; + } + + public HashMap getMetadata() { + return metadata; + } + + public ArrayList> getErrors() { + return errors; + } + + @Override + public String toString() { + Gson gson = new Gson().newBuilder().serializeNulls().create(); + return gson.toJson(this); + } +} diff --git a/src/main/java/com/skyflow/vault/controller/AuditController.java b/src/main/java/com/skyflow/vault/controller/AuditController.java new file mode 100644 index 00000000..2faa04a6 --- /dev/null +++ b/src/main/java/com/skyflow/vault/controller/AuditController.java @@ -0,0 +1,18 @@ +package com.skyflow.vault.controller; + +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.vault.audit.ListEventRequest; +import com.skyflow.vault.audit.ListEventResponse; + +public class AuditController { + + public AuditController(ApiClient 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..4eb7a1c8 --- /dev/null +++ b/src/main/java/com/skyflow/vault/controller/BinLookupController.java @@ -0,0 +1,16 @@ +package com.skyflow.vault.controller; + +import com.skyflow.generated.rest.ApiClient; +import com.skyflow.vault.bin.GetBinRequest; +import com.skyflow.vault.bin.GetBinResponse; + +public class BinLookupController { + + public BinLookupController(ApiClient 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..4a9334d4 --- /dev/null +++ b/src/main/java/com/skyflow/vault/controller/ConnectionController.java @@ -0,0 +1,91 @@ +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.Constants; +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 final 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) { + headers = Utils.constructConnectionHeadersMap(invokeConnectionRequest.getRequestHeaders()); + } + if (!headers.containsKey(Constants.SDK_AUTH_HEADER_KEY)) { + headers.put(Constants.SDK_AUTH_HEADER_KEY, token == null ? apiKey : token); + } + headers.put(Constants.SDK_METRICS_HEADER_KEY, Utils.getMetrics().toString()); + + RequestMethod requestMethod = invokeConnectionRequest.getMethod(); + 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); + JsonObject data = JsonParser.parseString(response).getAsJsonObject(); + HashMap metadata = new HashMap<>(); + metadata.put("requestId", HttpUtility.getRequestID()); + connectionResponse = new InvokeConnectionResponse(data, metadata, null); + LogUtil.printInfoLog(InfoLogs.INVOKE_CONNECTION_REQUEST_RESOLVED.getLog()); + } catch (IOException e) { + LogUtil.printErrorLog(ErrorLogs.INVOKE_CONNECTION_REQUEST_REJECTED.getLog()); + 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..c92e6b2c --- /dev/null +++ b/src/main/java/com/skyflow/vault/controller/DetectController.java @@ -0,0 +1,433 @@ +package com.skyflow.vault.controller; + +import com.google.gson.*; +import com.skyflow.VaultClient; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.DeidentifyFileStatus; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.core.ApiClientApiException; +import com.skyflow.generated.rest.resources.files.requests.*; +import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; +import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; +import com.skyflow.generated.rest.types.DeidentifyStatusResponseOutputType; +import com.skyflow.generated.rest.types.*; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.Constants; +import com.skyflow.utils.logger.LogUtil; +import com.skyflow.utils.validations.Validations; +import com.skyflow.vault.detect.*; +import com.skyflow.vault.detect.DeidentifyFileRequest; +import com.skyflow.vault.detect.DeidentifyFileResponse; +import com.skyflow.vault.detect.DeidentifyTextRequest; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.*; + +public final class DetectController extends VaultClient { + Gson gson = new GsonBuilder() + .registerTypeAdapter(Optional.class, (JsonSerializer>) (src, typeOfSrc, context) -> + src.map(context::serialize).orElse(null)) + .serializeNulls() + .create(); + + public DetectController(VaultConfig vaultConfig, Credentials credentials) { + super(vaultConfig, credentials); + } + + public DeidentifyTextResponse deidentifyText(DeidentifyTextRequest deidentifyTextRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_TEXT_TRIGGERED.getLog()); + DeidentifyStringResponse deidentifyStringResponse = null; + DeidentifyTextResponse deidentifyTextResponse = null; + try { + // Validate the request + LogUtil.printInfoLog(InfoLogs.VALIDATE_DEIDENTIFY_TEXT_REQUEST.getLog()); + Validations.validateDeidentifyTextRequest(deidentifyTextRequest); + setBearerToken(); + + // Parse the request to DeidentifyStringRequest + String vaultId = super.getVaultConfig().getVaultId(); + DeidentifyStringRequest request = getDeidentifyStringRequest(deidentifyTextRequest, vaultId); + + // Call the API to de-identify the string + deidentifyStringResponse = super.getDetectTextApi().deidentifyString(request); + + // Parse the response to DeIdentifyTextResponse + deidentifyTextResponse = getDeIdentifyTextResponse(deidentifyStringResponse); + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_TEXT_REQUEST_RESOLVED.getLog()); + } catch (ApiClientApiException ex) { + String bodyString = extractBodyAsString(ex); + LogUtil.printErrorLog(ErrorLogs.DEIDENTIFY_TEXT_REQUEST_REJECTED.getLog()); + throw new SkyflowException(ex.statusCode(), ex, ex.headers(), bodyString); + } + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_TEXT_SUCCESS.getLog()); + return deidentifyTextResponse; + } + + public ReidentifyTextResponse reidentifyText(ReidentifyTextRequest reidentifyTextRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.REIDENTIFY_TEXT_TRIGGERED.getLog()); + ReidentifyTextResponse reidentifyTextResponse = null; + try { + // Validate the request + LogUtil.printInfoLog(InfoLogs.VALIDATE_REIDENTIFY_TEXT_REQUEST.getLog()); + Validations.validateReidentifyTextRequest(reidentifyTextRequest); + setBearerToken(); + // Parse the request to ReidentifyTextRequest + String vaultId = super.getVaultConfig().getVaultId(); + ReidentifyStringRequest request = getReidentifyStringRequest(reidentifyTextRequest, vaultId); + + // Call the API to re-identify the string + ReidentifyStringResponse reidentifyStringResponse = super.getDetectTextApi().reidentifyString(request); + + // Parse the response to ReidentifyTextResponse + reidentifyTextResponse = new ReidentifyTextResponse(reidentifyStringResponse.getText().orElse(null)); + LogUtil.printInfoLog(InfoLogs.REIDENTIFY_TEXT_REQUEST_RESOLVED.getLog()); + } catch (ApiClientApiException ex) { + String bodyString = extractBodyAsString(ex); + LogUtil.printErrorLog(ErrorLogs.REIDENTIFY_TEXT_REQUEST_REJECTED.getLog()); + throw new SkyflowException(ex.statusCode(), ex, ex.headers(), bodyString); + } + LogUtil.printInfoLog(InfoLogs.REIDENTIFY_TEXT_SUCCESS.getLog()); + return reidentifyTextResponse; + } + + public DeidentifyFileResponse deidentifyFile(DeidentifyFileRequest request) throws SkyflowException { + DeidentifyFileResponse response; + LogUtil.printInfoLog(InfoLogs.DEIDENTIFY_FILE_TRIGGERED.getLog()); + try { + LogUtil.printInfoLog(InfoLogs.VALIDATE_DEIDENTIFY_FILE_REQUEST.getLog()); + Validations.validateDeidentifyFileRequest(request); + setBearerToken(); + + String vaultId = super.getVaultConfig().getVaultId(); + + File file; + if (request.getFileInput().getFilePath() != null) { + file = new File(request.getFileInput().getFilePath()); + } else { + file = request.getFileInput().getFile(); + } + String fileName = file.getName(); + String fileExtension = getFileExtension(fileName); + String base64Content; + + try { + base64Content = encodeFileToBase64(file); + } catch (IOException ioe) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FailedToEncodeFile.getMessage()); + } + + + com.skyflow.generated.rest.types.DeidentifyFileResponse apiResponse = processFileByType(fileExtension, base64Content, request, vaultId); + try { + response = pollForResults(apiResponse.getRunId(), request.getWaitTime()); + } catch (Exception ex) { + throw new SkyflowException(ErrorCode.SERVER_ERROR.getCode(), ErrorMessage.PollingForResultsFailed.getMessage()); + } + + if (DeidentifyFileStatus.SUCCESS.value().equalsIgnoreCase(response.getStatus())) { + String base64File = response.getFileBase64(); + response.getEntities().get(0).getFile(); + if (base64File != null) { + byte[] decodedBytes = Base64.getDecoder().decode(base64File); + String outputDir = request.getOutputDirectory(); + String outputFileName = Constants.PROCESSED_FILE_NAME_PREFIX + fileName.substring(0, fileName.lastIndexOf('.')) + "."+response.getExtension(); + File outputFile; + if (outputDir != null && !outputDir.isEmpty()) { + outputFile = new File(outputDir, outputFileName); + } else { + outputFile = new File(outputFileName); + } + try { + java.nio.file.Files.write(outputFile.toPath(), decodedBytes); + } catch (IOException ioe) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FailedtoSaveProcessedFile.getMessage()); + } + + } + + List entities = response.getEntities(); + if (entities != null && !entities.isEmpty()) { + FileEntityInfo entityInfo = entities.get(0); + String entityBase64 = entityInfo.getFile(); + String outputDir = request.getOutputDirectory(); + if (entityBase64 != null) { + byte[] entityDecodedBytes = Base64.getDecoder().decode(entityBase64); + String entityFileName = Constants.PROCESSED_FILE_NAME_PREFIX + fileName.substring(0, fileName.lastIndexOf('.')) + ".json"; + File entityFile; + if (outputDir != null && !outputDir.isEmpty()) { + entityFile = new File(outputDir, entityFileName); + } else { + entityFile = new File(entityFileName); + } + try { + java.nio.file.Files.write(entityFile.toPath(), entityDecodedBytes); + } catch (IOException ioe) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FailedtoSaveProcessedFile.getMessage()); + } + } + } + } + } catch (ApiClientApiException e) { + String bodyString = extractBodyAsString(e); + LogUtil.printErrorLog(ErrorLogs.DEIDENTIFY_FILE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } + return response; + } + + private String getFileExtension(String fileName) { + return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); + } + + private String encodeFileToBase64(File file) throws IOException { + byte[] fileContent = Files.readAllBytes(file.toPath()); + return Base64.getEncoder().encodeToString(fileContent); + } + + private DeidentifyFileResponse pollForResults(String runId, Integer maxWaitTime) throws Exception { + int currentWaitTime = 1; + maxWaitTime = maxWaitTime == null ? 64 : maxWaitTime; + + DeidentifyStatusResponse response = null; + + while (true) { + try { + GetRunRequest getRunRequest = GetRunRequest.builder() + .vaultId(super.getVaultConfig().getVaultId()) + .build(); + response = super.getDetectFileAPi() + .getRun(runId, getRunRequest); + + DeidentifyStatusResponseStatus status = response.getStatus(); + + if (DeidentifyFileStatus.IN_PROGRESS.value().equalsIgnoreCase(String.valueOf(status))) { + if (currentWaitTime >= maxWaitTime) { + return new DeidentifyFileResponse(runId, DeidentifyFileStatus.IN_PROGRESS.value()); + } + + int nextWaitTime = currentWaitTime * 2; + int waitTime; + + if (nextWaitTime >= maxWaitTime) { + waitTime = maxWaitTime - currentWaitTime; + currentWaitTime = maxWaitTime; + } else { + waitTime = nextWaitTime; + currentWaitTime = nextWaitTime; + } + + Thread.sleep(waitTime * 1000); + + } else if (status == DeidentifyStatusResponseStatus.SUCCESS || + status == DeidentifyStatusResponseStatus.FAILED) { + return parseDeidentifyFileResponse(response, runId, status.toString()); + } + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.GET_DETECT_RUN_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } + } + + } + + private static synchronized DeidentifyFileResponse parseDeidentifyFileResponse(DeidentifyStatusResponse response, + String runId, String status) throws SkyflowException { + DeidentifyFileOutput firstOutput = getFirstOutput(response); + + if (firstOutput == null) { + return new DeidentifyFileResponse( + null, + null, + response.getOutputType().name(), + null, + null, + null, + response.getSize().orElse(null), + response.getDuration().orElse(null), + response.getPages().orElse(null), + response.getSlides().orElse(null), + getEntities(response), + runId, + response.getStatus().name() + ); + } + + Object wordCharObj = response.getAdditionalProperties().get("word_character_count"); + Integer wordCount = null; + Integer charCount = null; + + if (wordCharObj instanceof Map) { + Map wordCharMap = (Map) wordCharObj; + Object wc = wordCharMap.get("word_count"); + Object cc = wordCharMap.get("character_count"); + if (wc instanceof Number) { + wordCount = ((Number) wc).intValue(); + } + if (cc instanceof Number) { + charCount = ((Number) cc).intValue(); + } + } + + File processedFileObject = null; + FileInfo fileInfo = null; + Optional processedFileBase64 = Optional.of(firstOutput).flatMap(DeidentifyFileOutput::getProcessedFile); + Optional processedFileExtension = Optional.of(firstOutput).flatMap(DeidentifyFileOutput::getProcessedFileExtension); + if (processedFileBase64.isPresent() && processedFileExtension.isPresent()) { + try { + byte[] decodedBytes = Base64.getDecoder().decode(processedFileBase64.get()); + String suffix = "." + processedFileExtension.get(); + String fileName = Constants.DEIDENTIFIED_FILE_PREFIX + suffix; + processedFileObject = new File(System.getProperty("java.io.tmpdir"), fileName); + Files.write(processedFileObject.toPath(), decodedBytes); + fileInfo = new FileInfo(processedFileObject); + processedFileObject.deleteOnExit(); + } catch (IOException ioe) { + throw new SkyflowException(ErrorCode.INVALID_INPUT.getCode(), ErrorMessage.FailedToEncodeFile.getMessage()); + } + } + + String processedFileType = firstOutput.getProcessedFileType() + .map(Object::toString) + .orElse(DeidentifyStatusResponseOutputType.UNKNOWN.toString()); + + String fileExtension = firstOutput.getProcessedFileExtension() + .orElse(DeidentifyStatusResponseOutputType.UNKNOWN.toString()); + + return new DeidentifyFileResponse( + fileInfo, + firstOutput.getProcessedFile().orElse(null), + processedFileType, + fileExtension, + wordCount, + charCount, + response.getSize().orElse(null), + response.getDuration().orElse(null), + response.getPages().orElse(null), + response.getSlides().orElse(null), + getEntities(response), + runId, + status + ); + } + + private static synchronized DeidentifyFileOutput getFirstOutput(DeidentifyStatusResponse response) { + List outputs = response.getOutput(); + return outputs != null && !outputs.isEmpty() ? outputs.get(0) : null; + } + + private static synchronized List getEntities(DeidentifyStatusResponse response) { + List entities = new ArrayList<>(); + + List outputs = response.getOutput(); + DeidentifyFileOutput deidentifyFileOutput = outputs != null && !outputs.isEmpty() ? outputs.get(1) : null; + + if (deidentifyFileOutput != null) { + entities.add(new FileEntityInfo( + deidentifyFileOutput.getProcessedFile().orElse(null), + deidentifyFileOutput.getProcessedFileType().orElse(null), + deidentifyFileOutput.getProcessedFileExtension().orElse(null) + )); + } + + return entities; + } + + private String extractBodyAsString(ApiClientApiException e) { + return e.statusCode() == 500 + ? e.body().toString() + : gson.toJson(e.body()); + } + + + private com.skyflow.generated.rest.types.DeidentifyFileResponse processFileByType(String fileExtension, String base64Content, DeidentifyFileRequest request, String vaultId) throws SkyflowException { + switch (fileExtension.toLowerCase()) { + case "txt": + com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest textFileRequest = + super.getDeidentifyTextFileRequest(request, vaultId, base64Content); + return super.getDetectFileAPi().deidentifyText(textFileRequest); + + case "mp3": + case "wav": + DeidentifyAudioRequest audioRequest = + super.getDeidentifyAudioRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifyAudio(audioRequest); + + case "pdf": + DeidentifyPdfRequest pdfRequest = + super.getDeidentifyPdfRequest(request, vaultId, base64Content); + + return super.getDetectFileAPi().deidentifyPdf(pdfRequest); + + case "jpg": + case "jpeg": + case "png": + case "bmp": + case "tif": + case "tiff": + DeidentifyImageRequest imageRequest = + super.getDeidentifyImageRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifyImage(imageRequest); + + case "ppt": + case "pptx": + DeidentifyPresentationRequest presentationRequest = + super.getDeidentifyPresentationRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifyPresentation(presentationRequest); + + case "csv": + case "xls": + case "xlsx": + DeidentifySpreadsheetRequest spreadsheetRequest = + super.getDeidentifySpreadsheetRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifySpreadsheet(spreadsheetRequest); + + case "doc": + case "docx": + DeidentifyDocumentRequest documentRequest = + super.getDeidentifyDocumentRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifyDocument(documentRequest); + + case "json": + case "xml": + DeidentifyStructuredTextRequest structuredTextRequest = + super.getDeidentifyStructuredTextRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifyStructuredText(structuredTextRequest); + + default: + com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest genericFileRequest = + super.getDeidentifyGenericFileRequest(request, vaultId, base64Content, fileExtension); + return super.getDetectFileAPi().deidentifyFile(genericFileRequest); + } + } + + public DeidentifyFileResponse getDetectRun(GetDetectRunRequest request) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.GET_DETECT_RUN_TRIGGERED.getLog()); + try { + LogUtil.printInfoLog(InfoLogs.VALIDATE_GET_DETECT_RUN_REQUEST.getLog()); + Validations.validateGetDetectRunRequest(request); + setBearerToken(); + String runId = request.getRunId(); + String vaultId = super.getVaultConfig().getVaultId(); + + GetRunRequest getRunRequest = + GetRunRequest.builder() + .vaultId(vaultId) + .build(); + + com.skyflow.generated.rest.types.DeidentifyStatusResponse apiResponse = + super.getDetectFileAPi().getRun(runId, getRunRequest); + + return parseDeidentifyFileResponse(apiResponse, runId, apiResponse.getStatus().toString()); + } catch (ApiClientApiException e) { + String bodyString = extractBodyAsString(e); + LogUtil.printErrorLog(ErrorLogs.GET_DETECT_RUN_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } + } +} diff --git a/src/main/java/com/skyflow/vault/controller/VaultController.java b/src/main/java/com/skyflow/vault/controller/VaultController.java new file mode 100644 index 00000000..3493227c --- /dev/null +++ b/src/main/java/com/skyflow/vault/controller/VaultController.java @@ -0,0 +1,401 @@ +package com.skyflow.vault.controller; + +import com.google.gson.*; +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.core.ApiClientApiException; +import com.skyflow.generated.rest.core.ApiClientHttpResponse; +import com.skyflow.generated.rest.resources.query.requests.QueryServiceExecuteQueryBody; +import com.skyflow.generated.rest.resources.records.requests.*; +import com.skyflow.generated.rest.resources.records.types.RecordServiceBulkGetRecordRequestOrderBy; +import com.skyflow.generated.rest.resources.records.types.RecordServiceBulkGetRecordRequestRedaction; +import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; +import com.skyflow.generated.rest.types.*; +import com.skyflow.logs.ErrorLogs; +import com.skyflow.logs.InfoLogs; +import com.skyflow.utils.Constants; +import com.skyflow.utils.logger.LogUtil; +import com.skyflow.utils.validations.Validations; +import com.skyflow.vault.data.*; +import com.skyflow.vault.tokens.*; + +import java.io.File; +import java.io.IOException; +import java.util.*; + +public final class VaultController extends VaultClient { + private static final Gson gson = new GsonBuilder().serializeNulls().create(); + + public VaultController(VaultConfig vaultConfig, Credentials credentials) { + super(vaultConfig, credentials); + } + + private static synchronized HashMap getFormattedBatchInsertRecord(Object record, Integer requestIndex) { + HashMap insertRecord = new HashMap<>(); + String jsonString = gson.toJson(record); + JsonObject bodyObject = JsonParser.parseString(jsonString).getAsJsonObject().get("Body").getAsJsonObject(); + JsonArray records = bodyObject.getAsJsonArray("records"); + JsonPrimitive error = bodyObject.getAsJsonPrimitive("error"); + + if (records != null) { + for (JsonElement recordElement : records) { + JsonObject recordObject = recordElement.getAsJsonObject(); + insertRecord.put("skyflowId", recordObject.get("skyflow_id").getAsString()); + JsonElement tokensElement = recordObject.get("tokens"); + if (tokensElement != null) { + insertRecord.putAll(tokensElement.getAsJsonObject().asMap()); + } + } + } + + if (error != null) { + insertRecord.put("error", error.getAsString()); + } + insertRecord.put("requestIndex", requestIndex); + return insertRecord; + } + + private static synchronized HashMap getFormattedBulkInsertRecord(V1RecordMetaProperties record) { + HashMap insertRecord = new HashMap<>(); + if (record.getSkyflowId().isPresent()) { + insertRecord.put("skyflowId", record.getSkyflowId().get()); + } + + if (record.getTokens().isPresent()) { + Map tokensMap = record.getTokens().get(); + insertRecord.putAll(tokensMap); + } + return insertRecord; + } + + private static synchronized HashMap getFormattedGetRecord(V1FieldRecords record) { + HashMap getRecord = new HashMap<>(); + + Optional> fieldsOpt = record.getFields(); + Optional> tokensOpt = record.getTokens(); + + if (fieldsOpt.isPresent()) { + getRecord.putAll(fieldsOpt.get()); + } else if (tokensOpt.isPresent()) { + getRecord.putAll(tokensOpt.get()); + } + return getRecord; + } + + private static synchronized HashMap getFormattedUpdateRecord(V1UpdateRecordResponse record) { + HashMap updateTokens = new HashMap<>(); + + record.getSkyflowId().ifPresent(skyflowId -> updateTokens.put("skyflowId", skyflowId)); + + record.getTokens().ifPresent(tokensMap -> updateTokens.putAll(tokensMap)); + + return updateTokens; + } + + private static synchronized HashMap getFormattedQueryRecord(V1FieldRecords record) { + HashMap queryRecord = new HashMap<>(); + Optional> fieldsOpt = record.getFields(); + if (fieldsOpt.isPresent()) { + queryRecord.putAll(fieldsOpt.get()); + } + return queryRecord; + } + + public InsertResponse insert(InsertRequest insertRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.INSERT_TRIGGERED.getLog()); + V1InsertRecordResponse bulkInsertResult = null; + ApiClientHttpResponse 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().withRawResponse().recordServiceBatchOperation(super.getVaultConfig().getVaultId(), insertBody); + LogUtil.printInfoLog(InfoLogs.INSERT_REQUEST_RESOLVED.getLog()); + Optional>> records = batchInsertResult.body().getResponses(); + + if (records.isPresent()) { + List> recordList = records.get(); + + for (Integer index = (Integer) 0; index < recordList.size(); index++) { + Map record = recordList.get(index); + HashMap insertRecord = getFormattedBatchInsertRecord(record, index); + + if (insertRecord.containsKey("skyflowId")) { + insertedFields.add(insertRecord); + } else { + insertRecord.put("requestId", batchInsertResult.headers().get("x-request-id").get(0)); + insertRecord.put("httpCode", 400); + 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()); + Optional> records = bulkInsertResult.getRecords(); + if (records.isPresent()) { + for (V1RecordMetaProperties record : records.get()) { + HashMap insertRecord = getFormattedBulkInsertRecord(record); + insertedFields.add(insertRecord); + } + } + } + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.INSERT_RECORDS_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } + LogUtil.printInfoLog(InfoLogs.INSERT_SUCCESS.getLog()); + if (insertedFields.isEmpty()) { + return new InsertResponse(null, errorFields.isEmpty() ? null : errorFields); + } + if (errorFields.isEmpty()) { + return new InsertResponse(insertedFields.isEmpty() ? null : insertedFields, null); + } + return new InsertResponse(insertedFields, errorFields); + } + + public DetokenizeResponse detokenize(DetokenizeRequest detokenizeRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.DETOKENIZE_TRIGGERED.getLog()); + ApiClientHttpResponse 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().withRawResponse().recordServiceDetokenize(super.getVaultConfig().getVaultId(), payload); + LogUtil.printInfoLog(InfoLogs.DETOKENIZE_REQUEST_RESOLVED.getLog()); + Map> responseHeaders = result.headers(); + String requestId = responseHeaders.get(Constants.REQUEST_ID_HEADER_KEY).get(0); + Optional> records = result.body().getRecords(); + + if (records.isPresent()) { + List recordList = records.get(); + + for (V1DetokenizeRecordResponse record : recordList) { + if (record.getError().isPresent()) { + DetokenizeRecordResponse recordResponse = new DetokenizeRecordResponse(record, requestId); + errorRecords.add(recordResponse); + } else { + DetokenizeRecordResponse recordResponse = new DetokenizeRecordResponse(record); + detokenizedFields.add(recordResponse); + } + } + } + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.DETOKENIZE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } + + if (!errorRecords.isEmpty()) { + LogUtil.printInfoLog(InfoLogs.DETOKENIZE_PARTIAL_SUCCESS.getLog()); + } else { + LogUtil.printInfoLog(InfoLogs.DETOKENIZE_SUCCESS.getLog()); + } + if (detokenizedFields.isEmpty()) { + return new DetokenizeResponse(null, errorRecords.isEmpty() ? null : errorRecords); + } + if (errorRecords.isEmpty()) { + return new DetokenizeResponse(detokenizedFields, null); + } + return new DetokenizeResponse(detokenizedFields, errorRecords); + } + + 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(); + RecordServiceBulkGetRecordRequest recordServiceBulkGetRecordRequest = RecordServiceBulkGetRecordRequest.builder() + .skyflowIds(getRequest.getIds()) + .redaction(redactionType != null ? RecordServiceBulkGetRecordRequestRedaction.valueOf(redactionType.toString()) : null) + .tokenization(getRequest.getReturnTokens()) + .offset(getRequest.getOffset()) + .limit(getRequest.getLimit()) + .downloadUrl(getRequest.getDownloadURL()) + .columnName(getRequest.getColumnName()) + .columnValues(getRequest.getColumnValues()) + .fields(getRequest.getFields()) + .orderBy(RecordServiceBulkGetRecordRequestOrderBy.valueOf(getRequest.getOrderBy())) + .build(); + + + result = super.getRecordsApi().recordServiceBulkGetRecord( + super.getVaultConfig().getVaultId(), + getRequest.getTable(), + recordServiceBulkGetRecordRequest + ); + LogUtil.printInfoLog(InfoLogs.GET_REQUEST_RESOLVED.getLog()); + List records = result.getRecords().get(); + if (records != null) { + for (V1FieldRecords record : records) { + data.add(getFormattedGetRecord(record)); + } + } + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.GET_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } + LogUtil.printInfoLog(InfoLogs.GET_SUCCESS.getLog()); + return new GetResponse(data, null); + } + + 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().remove("skyflow_id").toString(), + updateBody + ); + LogUtil.printInfoLog(InfoLogs.UPDATE_REQUEST_RESOLVED.getLog()); + skyflowId = String.valueOf(result.getSkyflowId()); + tokensMap = getFormattedUpdateRecord(result); + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.UPDATE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } + 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 = RecordServiceBulkDeleteRecordBody.builder().skyflowIds(deleteRequest.getIds()) + .build(); + + result = super.getRecordsApi().recordServiceBulkDeleteRecord( + super.getVaultConfig().getVaultId(), deleteRequest.getTable(), deleteBody); + LogUtil.printInfoLog(InfoLogs.DELETE_REQUEST_RESOLVED.getLog()); + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.DELETE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } + LogUtil.printInfoLog(InfoLogs.DELETE_SUCCESS.getLog()); + return new DeleteResponse(result.getRecordIdResponse().get()); + } + + 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(), QueryServiceExecuteQueryBody.builder().query(queryRequest.getQuery()).build()); + LogUtil.printInfoLog(InfoLogs.QUERY_REQUEST_RESOLVED.getLog()); + if (result.getRecords().isPresent()) { + List records = result.getRecords().get(); // Extract the List from Optional + for (V1FieldRecords record : records) { + fields.add(getFormattedQueryRecord(record)); + } + } + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.QUERY_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } + 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().isPresent() && !result.getRecords().get().isEmpty()) { + for (V1TokenizeRecordResponse response : result.getRecords().get()) { + if (response.getToken().isPresent()) { + list.add(response.getToken().get()); + } + } + } + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.TOKENIZE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } + LogUtil.printInfoLog(InfoLogs.TOKENIZE_SUCCESS.getLog()); + return new TokenizeResponse(list); + } + + public FileUploadResponse uploadFile(FileUploadRequest fileUploadRequest) throws SkyflowException { + LogUtil.printInfoLog(InfoLogs.FILE_UPLOAD_TRIGGERED.getLog()); + FileUploadResponse fileUploadResponse = null; + + try { + LogUtil.printInfoLog(InfoLogs.VALIDATING_FILE_UPLOAD_REQUEST.getLog()); + Validations.validateFileUploadRequest(fileUploadRequest); + setBearerToken(); + File file = super.getFileForFileUpload(fileUploadRequest); + + UploadFileV2Request uploadFileV2Request = UploadFileV2Request.builder() + .tableName(fileUploadRequest.getTable()) + .columnName(fileUploadRequest.getColumnName()) + .skyflowId(fileUploadRequest.getSkyflowId()) + .returnFileMetadata(false) + .build(); + + UploadFileV2Response uploadFileV2Response = super.getRecordsApi().uploadFileV2(super.getVaultConfig().getVaultId(), file, uploadFileV2Request); + + fileUploadResponse = new FileUploadResponse( + uploadFileV2Response.getSkyflowId().orElse(null), + null + ); + + } catch (ApiClientApiException e) { + String bodyString = gson.toJson(e.body()); + LogUtil.printErrorLog(ErrorLogs.UPLOAD_FILE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.statusCode(), e, e.headers(), bodyString); + } catch (IOException e) { + LogUtil.printErrorLog(ErrorLogs.UPLOAD_FILE_REQUEST_REJECTED.getLog()); + throw new SkyflowException(e.getMessage(), e); + } + LogUtil.printInfoLog(InfoLogs.FILE_UPLOAD_SUCCESS.getLog()); + return fileUploadResponse; + } +} diff --git a/src/main/java/com/skyflow/vault/data/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..f34d219a --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/DeleteResponse.java @@ -0,0 +1,27 @@ +package com.skyflow.vault.data; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import java.util.List; + +public class DeleteResponse { + private final List deletedIds; + + public DeleteResponse(List deletedIds) { + this.deletedIds = deletedIds; + } + + public List getDeletedIds() { + return deletedIds; + } + + @Override + public String toString() { + Gson gson = new Gson(); + JsonObject responseObject = JsonParser.parseString(gson.toJson(this)).getAsJsonObject(); + responseObject.add("errors", null); + return responseObject.toString(); + } +} diff --git a/src/main/java/com/skyflow/vault/data/FileUploadRequest.java b/src/main/java/com/skyflow/vault/data/FileUploadRequest.java new file mode 100644 index 00000000..1d6ba6be --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/FileUploadRequest.java @@ -0,0 +1,97 @@ +package com.skyflow.vault.data; + +import java.io.File; + +public class FileUploadRequest { + + private final FileUploadRequest.FileUploadRequestBuilder builder; + + private FileUploadRequest(FileUploadRequest.FileUploadRequestBuilder builder) { + this.builder = builder; + } + + public static FileUploadRequest.FileUploadRequestBuilder builder() { + return new FileUploadRequest.FileUploadRequestBuilder(); + } + + public String getTable() { + return this.builder.table; + } + + public String getSkyflowId() { + return this.builder.skyflowId; + } + + public String getColumnName() { + return this.builder.columnName; + } + + public String getFilePath() { + return this.builder.filePath; + } + + public String getBase64() { + return this.builder.base64; + } + + public File getFileObject() { + return this.builder.fileObject; + } + + public String getFileName() { + return this.builder.fileName; + } + + public static final class FileUploadRequestBuilder { + + private String table; + private String skyflowId; + private String columnName; + private String filePath; + private String base64; + private File fileObject; + private String fileName; + + private FileUploadRequestBuilder() { + } + + public FileUploadRequest.FileUploadRequestBuilder table(String table) { + this.table = table; + return this; + } + + public FileUploadRequest.FileUploadRequestBuilder skyflowId(String skyflowId) { + this.skyflowId = skyflowId; + return this; + } + + public FileUploadRequest.FileUploadRequestBuilder columnName(String columnName) { + this.columnName = columnName; + return this; + } + + public FileUploadRequest.FileUploadRequestBuilder filePath(String filePath) { + this.filePath = filePath; + return this; + } + + public FileUploadRequest.FileUploadRequestBuilder base64(String base64) { + this.base64 = base64; + return this; + } + + public FileUploadRequest.FileUploadRequestBuilder fileObject(File fileObject) { + this.fileObject = fileObject; + return this; + } + + public FileUploadRequest.FileUploadRequestBuilder fileName(String fileName) { + this.fileName = fileName; + return this; + } + + public FileUploadRequest build() { + return new FileUploadRequest(this); + } + } +} diff --git a/src/main/java/com/skyflow/vault/data/FileUploadResponse.java b/src/main/java/com/skyflow/vault/data/FileUploadResponse.java new file mode 100644 index 00000000..9e4557a3 --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/FileUploadResponse.java @@ -0,0 +1,31 @@ +package com.skyflow.vault.data; + +import com.google.gson.Gson; + +import java.util.ArrayList; +import java.util.HashMap; + +public class FileUploadResponse { + private final String skyflowId; + private final ArrayList> errors; + + public FileUploadResponse(String skyflowId, ArrayList> errors) { + this.skyflowId = skyflowId; + this.errors = errors; + } + + public String getSkyflowId() { + return skyflowId; + } + + public ArrayList> getErrors() { + return errors; + } + + @Override + public String toString() { + Gson gson = new Gson().newBuilder().serializeNulls().create(); + return gson.toJson(this); + } + +} diff --git a/src/main/java/com/skyflow/vault/data/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..34a01303 --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/GetResponse.java @@ -0,0 +1,30 @@ +package com.skyflow.vault.data; + +import com.google.gson.Gson; + +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() { + Gson gson = new Gson().newBuilder().serializeNulls().create(); + return gson.toJson(this); + } +} 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..54093467 --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/InsertRequest.java @@ -0,0 +1,111 @@ +package com.skyflow.vault.data; + +import com.skyflow.enums.TokenMode; + +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 getContinueOnError() { + return this.builder.continueOnError; + } + + public TokenMode getTokenMode() { + return this.builder.tokenMode; + } + + 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 continueOnError; + private TokenMode tokenMode; + + private InsertRequestBuilder() { + this.returnTokens = false; + this.continueOnError = false; + this.tokenMode = TokenMode.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 continueOnError(Boolean continueOnError) { + this.continueOnError = continueOnError != null && continueOnError; + return this; + } + + public InsertRequestBuilder tokenMode(TokenMode tokenMode) { + this.tokenMode = tokenMode == null ? TokenMode.DISABLE : tokenMode; + 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..3d311525 --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/InsertResponse.java @@ -0,0 +1,30 @@ +package com.skyflow.vault.data; + +import com.google.gson.Gson; + +import java.util.ArrayList; +import java.util.HashMap; + +public class InsertResponse { + private final ArrayList> insertedFields; + private final ArrayList> errors; + + public InsertResponse(ArrayList> insertedFields, ArrayList> errors) { + this.insertedFields = insertedFields; + this.errors = errors; + } + + public ArrayList> getInsertedFields() { + return insertedFields; + } + + public ArrayList> getErrors() { + return errors; + } + + @Override + public String toString() { + Gson gson = new Gson().newBuilder().serializeNulls().create(); + return gson.toJson(this); + } +} diff --git a/src/main/java/com/skyflow/vault/data/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..7a1bca51 --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/QueryResponse.java @@ -0,0 +1,32 @@ +package com.skyflow.vault.data; + +import com.google.gson.*; + +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() { + Gson gson = new GsonBuilder().serializeNulls().create(); + JsonObject responseObject = gson.toJsonTree(this).getAsJsonObject(); + JsonArray fieldsArray = responseObject.get("fields").getAsJsonArray(); + for (JsonElement fieldElement : fieldsArray) { + fieldElement.getAsJsonObject().add("tokenizedData", new JsonObject()); + } + responseObject.add("errors", null); + responseObject.remove("tokenizedData"); + return responseObject.toString(); + } +} diff --git a/src/main/java/com/skyflow/vault/data/UpdateRequest.java b/src/main/java/com/skyflow/vault/data/UpdateRequest.java new file mode 100644 index 00000000..94789121 --- /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.TokenMode; + +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 TokenMode getTokenMode() { + return this.builder.tokenMode; + } + + public static final class UpdateRequestBuilder { + private String table; + private Boolean returnTokens; + private HashMap data; + private HashMap tokens; + private TokenMode tokenMode; + + private UpdateRequestBuilder() { + this.returnTokens = false; + this.tokenMode = TokenMode.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 tokenMode(TokenMode tokenStrict) { + this.tokenMode = tokenStrict == null ? TokenMode.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..068b29be --- /dev/null +++ b/src/main/java/com/skyflow/vault/data/UpdateResponse.java @@ -0,0 +1,40 @@ +package com.skyflow.vault.data; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import java.util.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() { + Gson gson = new Gson(); + JsonObject responseObject = JsonParser.parseString(gson.toJson(this)).getAsJsonObject(); + JsonObject tokensObject = responseObject.remove("tokens").getAsJsonObject(); + for (String key : tokensObject.keySet()) { + responseObject.add(key, tokensObject.get(key)); + } + JsonObject finalResponseObject = new JsonObject(); + finalResponseObject.add("updatedField", responseObject); + finalResponseObject.add("errors", null); + return finalResponseObject.toString(); + } +} diff --git a/src/main/java/com/skyflow/vault/detect/AudioBleep.java b/src/main/java/com/skyflow/vault/detect/AudioBleep.java new file mode 100644 index 00000000..1a75f93b --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/AudioBleep.java @@ -0,0 +1,64 @@ +package com.skyflow.vault.detect; + +public class AudioBleep { + private final AudioBleepBuilder builder; + + private AudioBleep(AudioBleepBuilder builder) { + this.builder = builder; + } + + public static AudioBleepBuilder builder() { + return new AudioBleepBuilder(); + } + + public Double getGain() { + return this.builder.gain; + } + + public Double getFrequency() { + return this.builder.frequency; + } + + public Double getStartPadding() { + return this.builder.startPadding; + } + + public Double getStopPadding() { + return this.builder.stopPadding; + } + + public static final class AudioBleepBuilder { + private Double gain; + private Double frequency; + private Double startPadding; + private Double stopPadding; + + private AudioBleepBuilder() { + // Default constructor + } + + public AudioBleepBuilder gain(Double gain) { + this.gain = gain; + return this; + } + + public AudioBleepBuilder frequency(Double frequency) { + this.frequency = frequency; + return this; + } + + public AudioBleepBuilder startPadding(Double startPadding) { + this.startPadding = startPadding; + return this; + } + + public AudioBleepBuilder stopPadding(Double stopPadding) { + this.stopPadding = stopPadding; + return this; + } + + public AudioBleep build() { + return new AudioBleep(this); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/DateTransformation.java b/src/main/java/com/skyflow/vault/detect/DateTransformation.java new file mode 100644 index 00000000..819927d2 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/DateTransformation.java @@ -0,0 +1,30 @@ +package com.skyflow.vault.detect; + + +import com.skyflow.enums.DetectEntities; + +import java.util.List; + +public class DateTransformation { + private final int max; + private final int min; + private final List entities; + + public DateTransformation(int max, int min, List entities) { + this.max = max; + this.min = min; + this.entities = entities; + } + + public int getMax() { + return max; + } + + public int getMin() { + return min; + } + + public List getEntities() { + return entities; + } +} diff --git a/src/main/java/com/skyflow/vault/detect/DeidentifyFileRequest.java b/src/main/java/com/skyflow/vault/detect/DeidentifyFileRequest.java new file mode 100644 index 00000000..3ebc450e --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/DeidentifyFileRequest.java @@ -0,0 +1,192 @@ +package com.skyflow.vault.detect; + +import com.skyflow.enums.DetectEntities; +import com.skyflow.enums.DetectOutputTranscriptions; +import com.skyflow.enums.MaskingMethod; +import java.util.List; + +public class DeidentifyFileRequest { + private final DeidentifyFileRequestBuilder builder; + + private DeidentifyFileRequest(DeidentifyFileRequestBuilder builder) { + this.builder = builder; + } + + public static DeidentifyFileRequestBuilder builder() { + return new DeidentifyFileRequestBuilder(); + } + + public FileInput getFileInput() { + return this.builder.fileInput; + } + + public List getEntities() { + return this.builder.entities; + } + + public List getAllowRegexList() { + return this.builder.allowRegexList; + } + + public List getRestrictRegexList() { + return this.builder.restrictRegexList; + } + + public TokenFormat getTokenFormat() { + return this.builder.tokenFormat; + } + + public Transformations getTransformations() { + return this.builder.transformations; + } + + public Boolean getOutputProcessedImage() { + return this.builder.outputProcessedImage; + } + + public Boolean getOutputOcrText() { + return this.builder.outputOcrText; + } + + public MaskingMethod getMaskingMethod() { + return this.builder.maskingMethod; + } + + public Number getPixelDensity() { + return this.builder.pixelDensity; + } + + public Number getMaxResolution() { + return this.builder.maxResolution; + } + + public Boolean getOutputProcessedAudio() { + return this.builder.outputProcessedAudio; + } + + public DetectOutputTranscriptions getOutputTranscription() { + return this.builder.outputTranscription; + } + + public AudioBleep getBleep() { + return this.builder.bleep; + } + + public String getOutputDirectory() { + return this.builder.outputDirectory; + } + + public Integer getWaitTime() { + return this.builder.waitTime; + } + + public static final class DeidentifyFileRequestBuilder { + private List entities; + private List allowRegexList; + private List restrictRegexList; + private TokenFormat tokenFormat; + private Transformations transformations; + private Boolean outputProcessedImage; + private Boolean outputOcrText; + private MaskingMethod maskingMethod; + private Number pixelDensity; + private Number maxResolution; + private Boolean outputProcessedAudio; + private DetectOutputTranscriptions outputTranscription; + private AudioBleep bleep; + private FileInput fileInput; + private String outputDirectory; + private Integer waitTime; + + private DeidentifyFileRequestBuilder() { + // Set default values + this.outputProcessedImage = false; + this.outputOcrText = false; + this.outputProcessedAudio = false; + } + + public DeidentifyFileRequestBuilder file(FileInput fileInput) { + this.fileInput = fileInput; + return this; + } + + public DeidentifyFileRequestBuilder entities(List entities) { + this.entities = entities; + return this; + } + + public DeidentifyFileRequestBuilder allowRegexList(List allowRegexList) { + this.allowRegexList = allowRegexList; + return this; + } + + public DeidentifyFileRequestBuilder restrictRegexList(List restrictRegexList) { + this.restrictRegexList = restrictRegexList; + return this; + } + + public DeidentifyFileRequestBuilder tokenFormat(TokenFormat tokenFormat) { + this.tokenFormat = tokenFormat; + return this; + } + + public DeidentifyFileRequestBuilder transformations(Transformations transformations) { + this.transformations = transformations; + return this; + } + + public DeidentifyFileRequestBuilder outputProcessedImage(Boolean outputProcessedImage) { + this.outputProcessedImage = outputProcessedImage != null ? outputProcessedImage : false; + return this; + } + + public DeidentifyFileRequestBuilder outputOcrText(Boolean outputOcrText) { + this.outputOcrText = outputOcrText != null ? outputOcrText : false; + return this; + } + + public DeidentifyFileRequestBuilder maskingMethod(MaskingMethod maskingMethod) { + this.maskingMethod = maskingMethod; + return this; + } + + public DeidentifyFileRequestBuilder pixelDensity(Number pixelDensity) { + this.pixelDensity = pixelDensity; + return this; + } + + public DeidentifyFileRequestBuilder maxResolution(Number maxResolution) { + this.maxResolution = maxResolution; + return this; + } + + public DeidentifyFileRequestBuilder outputProcessedAudio(Boolean outputProcessedAudio) { + this.outputProcessedAudio = outputProcessedAudio != null ? outputProcessedAudio : false; + return this; + } + + public DeidentifyFileRequestBuilder outputTranscription(DetectOutputTranscriptions outputTranscription) { + this.outputTranscription = outputTranscription; + return this; + } + + public DeidentifyFileRequestBuilder bleep(AudioBleep bleep) { + this.bleep = bleep; + return this; + } + + public DeidentifyFileRequestBuilder outputDirectory(String outputDirectory) { + this.outputDirectory = outputDirectory; + return this; + } + + public DeidentifyFileRequestBuilder waitTime(Integer waitTime) { + this.waitTime = waitTime; + return this; + } + + public DeidentifyFileRequest build() { + return new DeidentifyFileRequest(this); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java b/src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java new file mode 100644 index 00000000..66590f8e --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/DeidentifyFileResponse.java @@ -0,0 +1,106 @@ +package com.skyflow.vault.detect; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.io.File; +import java.util.List; + +public class DeidentifyFileResponse { + private final FileInfo file; + private final String fileBase64; + private final String type; + private final String extension; + private final Integer wordCount; + private final Integer charCount; + private final Double sizeInKb; + private final Double durationInSeconds; + private final Integer pageCount; + private final Integer slideCount; + private final List entities; + private final String runId; + private final String status; + + + public DeidentifyFileResponse(FileInfo file, String fileBase64, String type, String extension, + Integer wordCount, Integer charCount, Double sizeInKb, + Double durationInSeconds, Integer pageCount, Integer slideCount, + List entities, String runId, String status) { + this.file = file; + this.fileBase64 = fileBase64; + this.type = type; + this.extension = extension; + this.wordCount = wordCount; + this.charCount = charCount; + this.sizeInKb = sizeInKb; + this.durationInSeconds = durationInSeconds; + this.pageCount = pageCount; + this.slideCount = slideCount; + this.entities = entities; + this.runId = runId; + this.status = status; + } + + public DeidentifyFileResponse(String runId, String status) { + this(null, null, null, null, null, null, null, null, null, null, null, runId, status); + } + + public FileInfo getFile() { + return file; + } + + public String getFileBase64(){ + return fileBase64; + } + + public String getType() { + return type; + } + + public String getExtension() { + return extension; + } + + public Integer getWordCount() { + return wordCount; + } + + public Integer getCharCount() { + return charCount; + } + + public Double getSizeInKb() { + return sizeInKb; + } + + public Double getDurationInSeconds() { + return durationInSeconds; + } + + public Integer getPageCount() { + return pageCount; + } + + public Integer getSlideCount() { + return slideCount; + } + + public List getEntities() { + return entities; + } + + public String getRunId() { + return runId; + } + + public String getStatus() { + return status; + } + + @Override + public String toString() { + Gson gson = new GsonBuilder().serializeNulls().create(); + return gson.toJson(this); + } + +} diff --git a/src/main/java/com/skyflow/vault/detect/DeidentifyTextRequest.java b/src/main/java/com/skyflow/vault/detect/DeidentifyTextRequest.java new file mode 100644 index 00000000..5f57e3a9 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/DeidentifyTextRequest.java @@ -0,0 +1,88 @@ +package com.skyflow.vault.detect; + + +import com.skyflow.enums.DetectEntities; + +import java.util.List; + +public class DeidentifyTextRequest { + private final DeidentifyTextRequestBuilder builder; + + private DeidentifyTextRequest(DeidentifyTextRequestBuilder builder) { + this.builder = builder; + } + + public static DeidentifyTextRequestBuilder builder() { + return new DeidentifyTextRequestBuilder(); + } + + public String getText() { + return this.builder.text; + } + + public List getEntities() { + return this.builder.entities; + } + + public List getAllowRegexList() { + return this.builder.allowRegexList; + } + + public List getRestrictRegexList() { + return this.builder.restrictRegexList; + } + + public TokenFormat getTokenFormat() { + return this.builder.tokenFormat; + } + + public Transformations getTransformations() { + return this.builder.transformations; + } + + public static final class DeidentifyTextRequestBuilder { + private String text; + private List entities; + private List allowRegexList; + private List restrictRegexList; + private TokenFormat tokenFormat; + private Transformations transformations; + + private DeidentifyTextRequestBuilder() { + } + + public DeidentifyTextRequestBuilder text(String text) { + this.text = text; + return this; + } + + public DeidentifyTextRequestBuilder entities(List entities) { + this.entities = entities; + return this; + } + + public DeidentifyTextRequestBuilder allowRegexList(List allowRegexList) { + this.allowRegexList = allowRegexList; + return this; + } + + public DeidentifyTextRequestBuilder restrictRegexList(List restrictRegexList) { + this.restrictRegexList = restrictRegexList; + return this; + } + + public DeidentifyTextRequestBuilder tokenFormat(TokenFormat tokenFormat) { + this.tokenFormat = tokenFormat; + return this; + } + + public DeidentifyTextRequestBuilder transformations(Transformations transformations) { + this.transformations = transformations; + return this; + } + + public DeidentifyTextRequest build() { + return new DeidentifyTextRequest(this); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/DeidentifyTextResponse.java b/src/main/java/com/skyflow/vault/detect/DeidentifyTextResponse.java new file mode 100644 index 00000000..6b6118e0 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/DeidentifyTextResponse.java @@ -0,0 +1,44 @@ +package com.skyflow.vault.detect; + + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.util.List; + +public class DeidentifyTextResponse { + private final String processedText; + private final List entities; + private final int wordCount; + private final int charCount; + + public DeidentifyTextResponse(String processedText, List entities, int wordCount, int charCount) { + this.processedText = processedText; + this.entities = entities; + this.wordCount = wordCount; + this.charCount = charCount; + } + + public String getProcessedText() { + return processedText; + } + + public List getEntities() { + return entities; + } + + public int getWordCount() { + return wordCount; + } + + public int getCharCount() { + return charCount; + } + + @Override + public String toString() { + Gson gson = new GsonBuilder().serializeNulls().create(); + return gson.toJson(this); + } + +} diff --git a/src/main/java/com/skyflow/vault/detect/EntityInfo.java b/src/main/java/com/skyflow/vault/detect/EntityInfo.java new file mode 100644 index 00000000..4a84acf9 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/EntityInfo.java @@ -0,0 +1,46 @@ +package com.skyflow.vault.detect; + + +import java.util.Map; + +public class EntityInfo { + private final String token; + private final String value; + private final TextIndex textIndex; + private final TextIndex processedIndex; + private final String entity; + private final Map scores; + + public EntityInfo(String token, String value, TextIndex textIndex, TextIndex processedIndex, String entity, java.util.Map scores) { + this.token = token; + this.value = value; + this.textIndex = textIndex; + this.processedIndex = processedIndex; + this.entity = entity; + this.scores = scores; + } + + public String getToken() { + return token; + } + + public String getValue() { + return value; + } + + public TextIndex getTextIndex() { + return textIndex; + } + + public TextIndex getProcessedIndex() { + return processedIndex; + } + + public String getEntity() { + return entity; + } + + public Map getScores() { + return scores; + } +} diff --git a/src/main/java/com/skyflow/vault/detect/FileEntityInfo.java b/src/main/java/com/skyflow/vault/detect/FileEntityInfo.java new file mode 100644 index 00000000..e177a99a --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/FileEntityInfo.java @@ -0,0 +1,19 @@ +package com.skyflow.vault.detect; + +import com.skyflow.generated.rest.types.DeidentifyFileOutputProcessedFileType; + +public class FileEntityInfo { + private final String file; + private final String type; + private final String extension; + + public FileEntityInfo(String file, DeidentifyFileOutputProcessedFileType type, String extension) { + this.file = file; + this.type = String.valueOf(type); + this.extension = extension; + } + + public String getFile() { return file; } + public String getType() { return type; } + public String getExtension() { return extension; } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/FileInfo.java b/src/main/java/com/skyflow/vault/detect/FileInfo.java new file mode 100644 index 00000000..2f13c4f2 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/FileInfo.java @@ -0,0 +1,33 @@ +package com.skyflow.vault.detect; + +import java.io.File; + +public class FileInfo { + private String name; + private long size; + private String type; + private long lastModified; + + public FileInfo(File file) { + this.name = file.getName(); + this.size = file.length(); + this.type = ""; + this.lastModified = file.lastModified(); + } + + public String getName() { + return name; + } + + public long getSize() { + return size; + } + + public String getType() { + return type; + } + + public long getLastModified() { + return lastModified; + } +} diff --git a/src/main/java/com/skyflow/vault/detect/FileInput.java b/src/main/java/com/skyflow/vault/detect/FileInput.java new file mode 100644 index 00000000..3ff1a77e --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/FileInput.java @@ -0,0 +1,46 @@ +package com.skyflow.vault.detect; + +import java.io.File; + +public class FileInput { + private final FileInputBuilder builder; + + private FileInput(FileInputBuilder builder) { + this.builder = builder; + } + + public static FileInputBuilder builder() { + return new FileInputBuilder(); + } + + public File getFile() { + return this.builder.file; + } + + public String getFilePath() { + return this.builder.filePath; + } + + public static final class FileInputBuilder { + private File file; + private String filePath; + + private FileInputBuilder() { + // Default constructor + } + + public FileInputBuilder file(File file) { + this.file = file; + return this; + } + + public FileInputBuilder filePath(String filePath) { + this.filePath = filePath; + return this; + } + + public FileInput build() { + return new FileInput(this); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/GetDetectRunRequest.java b/src/main/java/com/skyflow/vault/detect/GetDetectRunRequest.java new file mode 100644 index 00000000..cebec9f2 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/GetDetectRunRequest.java @@ -0,0 +1,33 @@ +package com.skyflow.vault.detect; + +public class GetDetectRunRequest { + private final String runId; + + private GetDetectRunRequest(GetDetectRunRequestBuilder builder) { + this.runId = builder.runId; + } + + public static GetDetectRunRequestBuilder builder() { + return new GetDetectRunRequestBuilder(); + } + + public String getRunId() { + return this.runId; + } + + public static final class GetDetectRunRequestBuilder { + private String runId; + + private GetDetectRunRequestBuilder() { + } + + public GetDetectRunRequestBuilder runId(String runId) { + this.runId = runId; + return this; + } + + public GetDetectRunRequest build() { + return new GetDetectRunRequest(this); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/ReidentifyTextRequest.java b/src/main/java/com/skyflow/vault/detect/ReidentifyTextRequest.java new file mode 100644 index 00000000..cc0e216a --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/ReidentifyTextRequest.java @@ -0,0 +1,68 @@ +package com.skyflow.vault.detect; + + +import com.skyflow.enums.DetectEntities; + +import java.util.List; + +public class ReidentifyTextRequest { + private final ReidentifyTextRequestBuilder builder; + + private ReidentifyTextRequest(ReidentifyTextRequestBuilder builder) { + this.builder = builder; + } + + public static ReidentifyTextRequestBuilder builder() { + return new ReidentifyTextRequestBuilder(); + } + + public String getText() { + return this.builder.text; + } + + public List getRedactedEntities() { + return this.builder.redactedEntities; + } + + public List getMaskedEntities() { + return this.builder.maskedEntities; + } + + public List getPlainTextEntities() { + return this.builder.plainTextEntities; + } + + public static final class ReidentifyTextRequestBuilder { + private String text; + private List redactedEntities; + private List maskedEntities; + private List plainTextEntities; + + private ReidentifyTextRequestBuilder() { + } + + public ReidentifyTextRequestBuilder text(String text) { + this.text = text; + return this; + } + + public ReidentifyTextRequestBuilder redactedEntities(List redactedEntities) { + this.redactedEntities = redactedEntities; + return this; + } + + public ReidentifyTextRequestBuilder maskedEntities(List maskedEntities) { + this.maskedEntities = maskedEntities; + return this; + } + + public ReidentifyTextRequestBuilder plainTextEntities(List plainTextEntities) { + this.plainTextEntities = plainTextEntities; + return this; + } + + public ReidentifyTextRequest build() { + return new ReidentifyTextRequest(this); + } + } +} diff --git a/src/main/java/com/skyflow/vault/detect/ReidentifyTextResponse.java b/src/main/java/com/skyflow/vault/detect/ReidentifyTextResponse.java new file mode 100644 index 00000000..3a517968 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/ReidentifyTextResponse.java @@ -0,0 +1,23 @@ +package com.skyflow.vault.detect; + + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class ReidentifyTextResponse { + private final String processedText; + + public ReidentifyTextResponse(String processedText) { + this.processedText = processedText; + } + + public String getProcessedText() { + return processedText; + } + + @Override + public String toString() { + Gson gson = new GsonBuilder().serializeNulls().create(); + return gson.toJson(this); + } +} diff --git a/src/main/java/com/skyflow/vault/detect/TextIndex.java b/src/main/java/com/skyflow/vault/detect/TextIndex.java new file mode 100644 index 00000000..6fe99c1d --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/TextIndex.java @@ -0,0 +1,29 @@ +package com.skyflow.vault.detect; + + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class TextIndex { + private final Integer start; + private final Integer end; + + public TextIndex(Integer start, Integer end) { + this.start = start; + this.end = end; + } + + public int getStart() { + return start; + } + + public int getEnd() { + return end; + } + + @Override + public String toString() { + Gson gson = new GsonBuilder().serializeNulls().create(); + return gson.toJson(this); + } +} diff --git a/src/main/java/com/skyflow/vault/detect/TokenFormat.java b/src/main/java/com/skyflow/vault/detect/TokenFormat.java new file mode 100644 index 00000000..8809d0a3 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/TokenFormat.java @@ -0,0 +1,71 @@ +package com.skyflow.vault.detect; + + +import com.skyflow.enums.DetectEntities; +import com.skyflow.enums.TokenType; + +import java.util.List; + + +public class TokenFormat { + private final TokenFormatBuilder builder; + + private TokenFormat(TokenFormatBuilder builder) { + this.builder = builder; + } + + public static TokenFormatBuilder builder() { + return new TokenFormatBuilder(); + } + + public TokenType getDefault() { + return this.builder.defaultType; + } + + public List getVaultToken() { + return this.builder.vaultToken; + } + + public List getEntityUniqueCounter() { + return this.builder.entityUniqueCounter; + } + + public List getEntityOnly() { + return this.builder.entityOnly; + } + + public static final class TokenFormatBuilder { + private TokenType defaultType; + private List vaultToken; + private List entityUniqueCounter; + private List entityOnly; + + private TokenFormatBuilder() { + this.defaultType = TokenType.ENTITY_UNIQUE_COUNTER; + } + + public TokenFormatBuilder defaultType(TokenType defaultType) { + this.defaultType = defaultType != null ? defaultType : TokenType.ENTITY_UNIQUE_COUNTER; + return this; + } + + public TokenFormatBuilder vaultToken(List vaultToken) { + this.vaultToken = vaultToken; + return this; + } + + public TokenFormatBuilder entityUniqueCounter(List entityUniqueCounter) { + this.entityUniqueCounter = entityUniqueCounter; + return this; + } + + public TokenFormatBuilder entityOnly(List entityOnly) { + this.entityOnly = entityOnly; + return this; + } + + public TokenFormat build() { + return new TokenFormat(this); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/skyflow/vault/detect/Transformations.java b/src/main/java/com/skyflow/vault/detect/Transformations.java new file mode 100644 index 00000000..2e219101 --- /dev/null +++ b/src/main/java/com/skyflow/vault/detect/Transformations.java @@ -0,0 +1,14 @@ +package com.skyflow.vault.detect; + + +public class Transformations { + private final DateTransformation shiftDates; + + public Transformations(DateTransformation shiftDates) { + this.shiftDates = shiftDates; + } + + public DateTransformation getShiftDates() { + return shiftDates; + } +} diff --git a/src/main/java/com/skyflow/vault/tokens/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/DetokenizeData.java b/src/main/java/com/skyflow/vault/tokens/DetokenizeData.java new file mode 100644 index 00000000..0e1b6b63 --- /dev/null +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeData.java @@ -0,0 +1,26 @@ +package com.skyflow.vault.tokens; + +import com.skyflow.enums.RedactionType; + +public class DetokenizeData { + private final String token; + private final RedactionType redactionType; + + public DetokenizeData(String token) { + this.token = token; + this.redactionType = RedactionType.DEFAULT; + } + + public DetokenizeData(String token, RedactionType redactionType) { + this.token = token; + this.redactionType = redactionType == null ? RedactionType.DEFAULT : redactionType; + } + + public String getToken() { + return this.token; + } + + public RedactionType getRedactionType() { + return this.redactionType; + } +} 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..7d2ae73c --- /dev/null +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeRecordResponse.java @@ -0,0 +1,54 @@ +package com.skyflow.vault.tokens; + + +import com.skyflow.generated.rest.types.V1DetokenizeRecordResponse; + +public class DetokenizeRecordResponse { + private final String token; + private final String value; + private final String type; + private final String error; + private final String requestId; + + public DetokenizeRecordResponse(V1DetokenizeRecordResponse record) { + this(record, null); + } + + public DetokenizeRecordResponse(V1DetokenizeRecordResponse record, String requestId) { + this.token = record.getToken().orElse(null); + + this.value = record.getValue() + .filter(val -> val != null && !val.toString().isEmpty()) + .orElse(null); + + this.type = record.getValueType() + .map(Enum::toString) + .filter(val -> !"NONE".equals(val)) + .orElse(null); + + this.error = record.getError().orElse(null); + + this.requestId = requestId; + } + + + public String getError() { + return error; + } + + public String getToken() { + return token; + } + + public String getValue() { + return value; + } + + public String getType() { + return type; + } + + public String getRequestId() { + return requestId; + } +} \ 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..186a18d2 --- /dev/null +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeRequest.java @@ -0,0 +1,57 @@ +package com.skyflow.vault.tokens; + +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 getDetokenizeData() { + return this.builder.detokenizeData; + } + + public Boolean getContinueOnError() { + return this.builder.continueOnError; + } + + public Boolean getDownloadURL() { + return this.builder.downloadURL; + } + + public static final class DetokenizeRequestBuilder { + private ArrayList detokenizeData; + private Boolean continueOnError; + private Boolean downloadURL; + + private DetokenizeRequestBuilder() { + this.continueOnError = false; + this.downloadURL = false; + } + + public DetokenizeRequestBuilder detokenizeData(ArrayList detokenizeData) { + this.detokenizeData = detokenizeData; + return this; + } + + public DetokenizeRequestBuilder continueOnError(Boolean continueOnError) { + this.continueOnError = continueOnError != null && continueOnError; + return this; + } + + public DetokenizeRequestBuilder downloadURL(Boolean downloadURL) { + this.downloadURL = downloadURL; + 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..bd1d7cde --- /dev/null +++ b/src/main/java/com/skyflow/vault/tokens/DetokenizeResponse.java @@ -0,0 +1,54 @@ +package com.skyflow.vault.tokens; + +import com.google.gson.ExclusionStrategy; +import com.google.gson.FieldAttributes; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.util.ArrayList; + +public class DetokenizeResponse { + private final ArrayList detokenizedFields; + private final ArrayList errors; + + public DetokenizeResponse(ArrayList detokenizedFields, ArrayList errors) { + this.detokenizedFields = detokenizedFields; + this.errors = errors; + } + + public ArrayList getDetokenizedFields() { + return detokenizedFields; + } + + public ArrayList getErrors() { + return errors; + } + + @Override + public String toString() { + Gson gson = new GsonBuilder() + .serializeNulls() + .registerTypeAdapter( + DetokenizeRecordResponse.class, + (com.google.gson.JsonSerializer) (src, typeOfSrc, context) -> { + com.google.gson.JsonObject obj = new com.google.gson.JsonObject(); + obj.addProperty("token", src.getToken()); + if (src.getValue() != null) { + obj.addProperty("value", src.getValue()); + } + if (src.getType() != null) { + obj.addProperty("type", src.getType()); + } + if (src.getError() != null) { + obj.add("error", context.serialize(src.getError())); + } + if (src.getRequestId() != null) { + obj.addProperty("requestId", src.getRequestId()); + } + return obj; + } + ) + .create(); + return gson.toJson(this); + } +} diff --git a/src/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..d8d8072b --- /dev/null +++ b/src/main/java/com/skyflow/vault/tokens/TokenizeResponse.java @@ -0,0 +1,33 @@ +package com.skyflow.vault.tokens; + +import com.google.gson.*; + +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() { + Gson gson = new Gson(); + JsonObject responseObject = JsonParser.parseString(gson.toJson(this)).getAsJsonObject(); + JsonArray tokensArray = responseObject.remove("tokens").getAsJsonArray(); + JsonArray newTokensArray = new JsonArray(); + for (JsonElement token : tokensArray) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("token", token.getAsString()); + newTokensArray.add(jsonObject); + } + responseObject.add("tokens", newTokensArray); + responseObject.add("errors", null); + return responseObject.toString(); + } +} diff --git a/src/test/java/com/skyflow/ConnectionClientTests.java b/src/test/java/com/skyflow/ConnectionClientTests.java new file mode 100644 index 00000000..4a69120c --- /dev/null +++ b/src/test/java/com/skyflow/ConnectionClientTests.java @@ -0,0 +1,95 @@ +package com.skyflow; + +import com.skyflow.config.ConnectionConfig; +import com.skyflow.config.Credentials; +import io.github.cdimascio.dotenv.Dotenv; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ConnectionClientTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static ConnectionClient connectionClient; + private static String connectionID = null; + private static String connectionURL = null; + private static String apiKey = null; + private static ConnectionConfig connectionConfig; + + @BeforeClass + public static void setup() { + connectionID = "connection123"; + connectionURL = "https://test.connection.url"; + apiKey = "sky-ab123-abcd1234cdef1234abcd4321cdef4321"; + + Credentials credentials = new Credentials(); + credentials.setApiKey(apiKey); + + connectionConfig = new ConnectionConfig(); + connectionConfig.setConnectionId(connectionID); + connectionConfig.setConnectionUrl(connectionURL); + connectionClient = new ConnectionClient(connectionConfig, credentials); + } + + @Test + public void getConnectionConfig() { + try { + ConnectionConfig config = connectionClient.getConnectionConfig(); + Assert.assertEquals(connectionID, config.getConnectionId()); + Assert.assertEquals(connectionURL, config.getConnectionUrl()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testSetBearerToken() { + try { + Dotenv dotenv = Dotenv.load(); + String bearerToken = dotenv.get("TEST_REUSABLE_TOKEN"); + Credentials credentials = new Credentials(); + credentials.setToken(bearerToken); + connectionConfig.setCredentials(credentials); + connectionClient.updateConnectionConfig(connectionConfig); + + // regular scenario + connectionClient.setBearerToken(); + + // re-use scenario + connectionClient.setBearerToken(); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testSetBearerTokenWithApiKey() { + try { + Credentials credentials = new Credentials(); + credentials.setApiKey(apiKey); + connectionConfig.setCredentials(null); + connectionClient.updateConnectionConfig(connectionConfig); + connectionClient.setCommonCredentials(credentials); + + // regular scenario + connectionClient.setBearerToken(); + + // re-use scenario + connectionClient.setBearerToken(); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testSetBearerTokenWithEnvCredentials() { + try { + connectionConfig.setCredentials(null); + connectionClient.updateConnectionConfig(connectionConfig); + connectionClient.setCommonCredentials(null); + Assert.assertNull(connectionClient.getConnectionConfig().getCredentials()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/SkyflowTests.java b/src/test/java/com/skyflow/SkyflowTests.java new file mode 100644 index 00000000..0b44c0b4 --- /dev/null +++ b/src/test/java/com/skyflow/SkyflowTests.java @@ -0,0 +1,569 @@ +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); + + 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 testGettingAlreadyRemovedVaultFromEmptyConfigs() { + try { + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.vault(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testGettingAlreadyRemovedVaultFromNonEmptyConfigs() { + try { + VaultConfig primaryConfig = new VaultConfig(); + primaryConfig.setVaultId(vaultID); + primaryConfig.setClusterId(clusterID); + primaryConfig.setEnv(Env.SANDBOX); + + VaultConfig secondaryConfig = new VaultConfig(); + secondaryConfig.setVaultId(vaultID + "123"); + secondaryConfig.setClusterId(clusterID); + secondaryConfig.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().addVaultConfig(primaryConfig).addVaultConfig(secondaryConfig).build(); + skyflowClient.removeVaultConfig(vaultID); + skyflowClient.vault(vaultID); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + + @Test + public void testAddingInvalidConnectionConfigInSkyflowBuilder() { + 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); + } + } + + @Test + public void testVaultMethodWithNoConfig() { + try { + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.vault(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testVaultMethodWithValidConfig() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().addVaultConfig(config).build(); + Assert.assertNotNull(skyflowClient.vault()); + Assert.assertNotNull(skyflowClient.vault(vaultID)); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testVaultMethodWithInvalidVaultId() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().addVaultConfig(config).build(); + skyflowClient.vault("invalid_vault_id"); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testConnectionMethodWithNoConfig() { + try { + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.connection(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.ConnectionIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testConnectionMethodWithValidConfig() { + try { + ConnectionConfig config = new ConnectionConfig(); + config.setConnectionId(connectionID); + config.setConnectionUrl(connectionURL); + Skyflow skyflowClient = Skyflow.builder().addConnectionConfig(config).build(); + Assert.assertNotNull(skyflowClient.connection()); + Assert.assertNotNull(skyflowClient.connection(connectionID)); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testConnectionMethodWithInvalidConnectionId() { + try { + ConnectionConfig config = new ConnectionConfig(); + config.setConnectionId(connectionID); + config.setConnectionUrl(connectionURL); + Skyflow skyflowClient = Skyflow.builder().addConnectionConfig(config).build(); + skyflowClient.connection("invalid_connection_id"); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.ConnectionIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testDetectMethodWithNoConfig() { + try { + Skyflow skyflowClient = Skyflow.builder().build(); + skyflowClient.detect(); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } + + @Test + public void testDetectMethodWithValidConfig() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().addVaultConfig(config).build(); + Assert.assertNotNull(skyflowClient.detect()); + Assert.assertNotNull(skyflowClient.detect(vaultID)); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testDetectMethodWithInvalidVaultId() { + try { + VaultConfig config = new VaultConfig(); + config.setVaultId(vaultID); + config.setClusterId(clusterID); + config.setEnv(Env.SANDBOX); + Skyflow skyflowClient = Skyflow.builder().addVaultConfig(config).build(); + skyflowClient.detect("invalid_vault_id"); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.VaultIdNotInConfigList.getMessage(), e.getMessage()); + } + } +} diff --git a/src/test/java/com/skyflow/VaultClientTests.java b/src/test/java/com/skyflow/VaultClientTests.java new file mode 100644 index 00000000..1ebb1b23 --- /dev/null +++ b/src/test/java/com/skyflow/VaultClientTests.java @@ -0,0 +1,933 @@ +package com.skyflow; + +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.*; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.resources.files.FilesClient; +import com.skyflow.generated.rest.resources.files.requests.*; +import com.skyflow.generated.rest.resources.query.QueryClient; +import com.skyflow.generated.rest.resources.records.RecordsClient; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceBatchOperationBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceInsertRecordBody; +import com.skyflow.generated.rest.resources.records.requests.RecordServiceUpdateRecordBody; +import com.skyflow.generated.rest.resources.strings.StringsClient; +import com.skyflow.generated.rest.resources.strings.requests.DeidentifyStringRequest; +import com.skyflow.generated.rest.resources.strings.requests.ReidentifyStringRequest; +import com.skyflow.generated.rest.resources.tokens.TokensClient; +import com.skyflow.generated.rest.resources.tokens.requests.V1DetokenizePayload; +import com.skyflow.generated.rest.resources.tokens.requests.V1TokenizePayload; +import com.skyflow.generated.rest.types.DeidentifyStringResponse; +import com.skyflow.generated.rest.types.DetectedEntity; +import com.skyflow.generated.rest.types.EntityLocation; +import com.skyflow.generated.rest.types.V1Byot; +import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.UpdateRequest; +import com.skyflow.vault.detect.*; +import com.skyflow.vault.detect.DeidentifyFileRequest; +import com.skyflow.vault.detect.DeidentifyTextRequest; +import com.skyflow.vault.tokens.ColumnValue; +import com.skyflow.vault.tokens.DetokenizeData; +import com.skyflow.vault.tokens.DetokenizeRequest; +import com.skyflow.vault.tokens.TokenizeRequest; +import io.github.cdimascio.dotenv.Dotenv; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.util.*; + +public class VaultClientTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static VaultClient vaultClient; + private static String vaultID = null; + private static String clusterID = null; + private static String token = null; + private static String table = null; + private static String value = null; + private static String columnGroup = null; + private static String apiKey = "sky-ab123-abcd1234cdef1234abcd4321cdef4321"; + private static ArrayList detokenizeData = null; + private static ArrayList> insertValues = null; + private static ArrayList> insertTokens = null; + private static HashMap valueMap = null; + private static HashMap tokenMap = null; + private static VaultConfig vaultConfig; + + @BeforeClass + public static void setup() throws SkyflowException { + vaultID = "vault123"; + clusterID = "cluster123"; + token = "test_token"; + detokenizeData = new ArrayList<>(); + table = "test_table"; + value = "test_value"; + columnGroup = "test_column_group"; + apiKey = null; + insertValues = new ArrayList<>(); + insertTokens = new ArrayList<>(); + valueMap = new HashMap<>(); + tokenMap = new HashMap<>(); + + vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.PROD); + + Credentials credentials = new Credentials(); + credentials.setApiKey("sky-ab123-abcd1234cdef1234abcd4321cdef4321"); + vaultConfig.setCredentials(credentials); + vaultClient = new VaultClient(vaultConfig, credentials); + vaultClient.setBearerToken(); + } + + @Test + public void testVaultClientGetRecordsAPI() { + try { + RecordsClient recordsClient = vaultClient.getRecordsApi(); + Assert.assertNotNull(recordsClient); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(INVALID_EXCEPTION_THROWN + e.getMessage()); + } + } + + @Test + public void testVaultClientDetectAPI() { + try { + FilesClient filesClient = vaultClient.getDetectFileAPi(); + Assert.assertNotNull(filesClient); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(INVALID_EXCEPTION_THROWN + e.getMessage()); + } + } + + @Test + public void testVaultClientDetectTextAPI() { + try { + StringsClient stringsClient = vaultClient.getDetectTextApi(); + Assert.assertNotNull(stringsClient); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(INVALID_EXCEPTION_THROWN + e.getMessage()); + } + } + + @Test + public void testVaultClientGetTokensAPI() { + try { + TokensClient tokensClient = vaultClient.getTokensApi(); + Assert.assertNotNull(tokensClient); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testVaultClientGetQueryAPI() { + try { + QueryClient queryClient = vaultClient.getQueryApi(); + Assert.assertNotNull(queryClient); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testVaultClientGetVaultConfig() { + try { + VaultConfig config = vaultClient.getVaultConfig(); + Assert.assertNotNull(config); + Assert.assertEquals(vaultID, config.getVaultId()); + Assert.assertEquals(clusterID, config.getClusterId()); + Assert.assertEquals(Env.PROD, config.getEnv()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetDetokenizePayload() { + try { + DetokenizeData detokenizeDataRecord1 = new DetokenizeData(token); + DetokenizeData detokenizeDataRecord2 = new DetokenizeData(token); + detokenizeData.add(detokenizeDataRecord1); + detokenizeData.add(detokenizeDataRecord2); + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .detokenizeData(detokenizeData) + .downloadURL(true) + .continueOnError(false) + .build(); + V1DetokenizePayload payload = vaultClient.getDetokenizePayload(detokenizeRequest); + Assert.assertFalse(payload.getContinueOnError().get()); + Assert.assertTrue(payload.getDownloadUrl().get()); + Assert.assertEquals(2, payload.getDetokenizationParameters().get().size()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetBulkInsertRequestBody() { + try { + valueMap.clear(); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.clear(); + tokenMap.put("test_column_1", "test_token_1"); + insertValues.clear(); + insertValues.add(valueMap); + insertValues.add(valueMap); + insertTokens.clear(); + insertTokens.add(tokenMap); + InsertRequest insertRequest1 = InsertRequest.builder() + .table(table) + .values(insertValues) + .tokens(insertTokens) + .tokenMode(TokenMode.ENABLE) + .returnTokens(true) + .build(); + RecordServiceInsertRecordBody body1 = vaultClient.getBulkInsertRequestBody(insertRequest1); + Assert.assertTrue(body1.getTokenization().get()); + Assert.assertEquals(V1Byot.ENABLE, body1.getByot().get()); + Assert.assertEquals(2, body1.getRecords().get().size()); + + InsertRequest insertRequest2 = InsertRequest.builder() + .table(table) + .values(insertValues) + .build(); + RecordServiceInsertRecordBody body2 = vaultClient.getBulkInsertRequestBody(insertRequest2); + Assert.assertEquals(2, body2.getRecords().get().size()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetBatchInsertRequestBody() { + try { + valueMap.clear(); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.clear(); + tokenMap.put("test_column_1", "test_token_1"); + insertValues.clear(); + insertValues.add(valueMap); + insertValues.add(valueMap); + insertTokens.clear(); + insertTokens.add(tokenMap); + InsertRequest insertRequest1 = InsertRequest.builder() + .table(table) + .values(insertValues) + .tokens(insertTokens) + .tokenMode(TokenMode.ENABLE) + .returnTokens(false) + .build(); + RecordServiceBatchOperationBody body1 = vaultClient.getBatchInsertRequestBody(insertRequest1); + Assert.assertTrue(body1.getContinueOnError().get()); + Assert.assertEquals(2, body1.getRecords().get().size()); + + InsertRequest insertRequest2 = InsertRequest.builder().table(table).values(insertValues).build(); + RecordServiceBatchOperationBody body2 = vaultClient.getBatchInsertRequestBody(insertRequest2); + Assert.assertEquals(2, body2.getRecords().get().size()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetUpdateRequestBodyWithTokens() { + try { + valueMap.clear(); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.clear(); + tokenMap.put("test_column_1", "test_token_1"); + UpdateRequest updateRequest = UpdateRequest.builder() + .table(table) + .data(valueMap) + .tokens(tokenMap) + .returnTokens(true) + .build(); + RecordServiceUpdateRecordBody body = vaultClient.getUpdateRequestBody(updateRequest); + Assert.assertTrue(body.getTokenization().get()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetUpdateRequestBodyWithoutTokens() { + try { + valueMap.clear(); + valueMap.put("test_column_1", "test_value_1"); + valueMap.put("test_column_2", "test_value_2"); + tokenMap.clear(); + tokenMap.put("test_column_1", "test_token_1"); + UpdateRequest updateRequest = UpdateRequest.builder() + .table(table) + .data(valueMap) + .returnTokens(false) + .build(); + RecordServiceUpdateRecordBody body = vaultClient.getUpdateRequestBody(updateRequest); + Assert.assertFalse(body.getTokenization().get()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetTokenizePayload() { + try { + ColumnValue columnValue = ColumnValue.builder().value(value).columnGroup(columnGroup).build(); + List columnValues = new ArrayList<>(); + columnValues.add(columnValue); + TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); + V1TokenizePayload payload = vaultClient.getTokenizePayload(tokenizeRequest); + Assert.assertEquals(1, payload.getTokenizationParameters().get().size()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testSetBearerToken() { + try { + Credentials credentials = new Credentials(); + credentials.setApiKey("sky-ab123-abcd1234cdef1234abcd4321cdef4321"); + vaultConfig.setCredentials(credentials); + vaultClient = new VaultClient(vaultConfig, credentials); + vaultClient.setBearerToken(); + + Assert.assertNotNull(vaultClient.getTokensApi()); + + vaultClient.setBearerToken(); + Assert.assertNotNull(vaultClient.getTokensApi()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN + ": " + e.getMessage()); + } + } + + @Test + public void testSetBearerTokenWithApiKey() { + try { + Credentials credentials = new Credentials(); + credentials.setApiKey("sky-ab123-abcd1234cdef1234abcd4321cdef4321"); // Use a non-null dummy API key + vaultConfig.setCredentials(credentials); + vaultClient.updateVaultConfig(); + vaultClient.setCommonCredentials(credentials); + + // regular scenario + vaultClient.setBearerToken(); + + // re-use scenario + vaultClient.setBearerToken(); + + // If no exception is thrown, the test passes + Assert.assertTrue(true); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN + ": " + e.getMessage()); + } + } + + @Test + public void testSetBearerTokenWithEnvCredentials() { + try { + Dotenv dotenv = Dotenv.load(); + vaultConfig.setCredentials(null); + vaultClient.updateVaultConfig(); + vaultClient.setCommonCredentials(null); + vaultClient.setBearerToken(); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + Assert.assertNull(vaultClient.getVaultConfig().getCredentials()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetDeIdentifyTextResponse() { + List entities = new ArrayList<>(); + EntityLocation location = EntityLocation.builder() + .startIndex(2) + .endIndex(10) + .startIndexProcessed(3) + .endIndexProcessed(8) + .build(); + + DetectedEntity detectedEntity = DetectedEntity.builder() + .token("token123") + .value("value123") + .location(location) + .build(); + entities.add(detectedEntity); + + DeidentifyStringResponse response = DeidentifyStringResponse.builder() + .processedText("processed text") + .wordCount(2) + .characterCount(13) + .entities(entities) + .build(); + + + DeidentifyTextResponse result = vaultClient.getDeIdentifyTextResponse(response); + + Assert.assertNotNull(result); + Assert.assertEquals("processed text", result.getProcessedText()); + Assert.assertEquals(2, result.getWordCount()); + Assert.assertEquals(13, result.getCharCount()); + Assert.assertNotNull(result.getEntities()); + Assert.assertEquals(1, result.getEntities().size()); + Assert.assertEquals("token123", result.getEntities().get(0).getToken()); + Assert.assertEquals("value123", result.getEntities().get(0).getValue()); + Assert.assertEquals(2, result.getEntities().get(0).getTextIndex().getStart()); + Assert.assertEquals(10, result.getEntities().get(0).getTextIndex().getEnd()); + Assert.assertEquals(3, result.getEntities().get(0).getProcessedIndex().getStart()); + Assert.assertEquals(8, result.getEntities().get(0).getProcessedIndex().getEnd()); + } + + @Test + public void testGetDeidentifyStringRequest() { + + List detectEntitiesList = new ArrayList<>(); + detectEntitiesList.add(DetectEntities.NAME); + + List vaultTokenList = new ArrayList<>(); + vaultTokenList.add(DetectEntities.SSN); + + + List entityOnlyList = new ArrayList<>(); + entityOnlyList.add(DetectEntities.DOB); + + List entityUniqueCounterList = new ArrayList<>(); + entityUniqueCounterList.add(DetectEntities.NAME); + + + List restrictRegexList = new ArrayList<>(); + restrictRegexList.add("([0-9]{3}-[0-9]{2}-[0-9]{4})"); + + TokenFormat tokenFormat = TokenFormat.builder() + .vaultToken(vaultTokenList) + .entityOnly(entityOnlyList) + .entityUniqueCounter(entityUniqueCounterList) + .build(); + + + List detectEntitiesTransformationList = new ArrayList<>(); + detectEntitiesTransformationList.add(DetectEntities.DOB); + detectEntitiesTransformationList.add(DetectEntities.DATE); + + DateTransformation dateTransformation = new DateTransformation(20, 5, detectEntitiesTransformationList); + Transformations transformations = new Transformations(dateTransformation); + + + DeidentifyTextRequest req = DeidentifyTextRequest.builder() + .text("Sensitive data to deidentify, like Name: Joy SSN 123-45-6789 and DOB 01-01-2000.") + .entities(detectEntitiesList) + .restrictRegexList(restrictRegexList) + .tokenFormat(tokenFormat) + .transformations(transformations) + .build(); + + } + + @Test + public void testDeidentifyFileRequestBuilderAndGetters() { + File file = new File("testfile.txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + DetectEntities entity = DetectEntities.NAME; + String allowRegex = "^[A-Za-z]+$"; + String restrictRegex = "\\d+"; + TokenFormat tokenFormat = TokenFormat.builder().vaultToken(Collections.singletonList(entity)).build(); + Boolean outputProcessedImage = true; + Boolean outputOcrText = true; + MaskingMethod maskingMethod = MaskingMethod.BLACKBOX; + Double pixelDensity = 300.0; + Double maxResolution = 1024.0; + Boolean outputProcessedAudio = false; + DetectOutputTranscriptions outputTranscription = DetectOutputTranscriptions.TRANSCRIPTION; + AudioBleep bleep = AudioBleep.builder().gain(20.0).build(); + String outputDirectory = "/tmp"; + Integer waitTime = 10; + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(Arrays.asList(entity)) + .allowRegexList(Collections.singletonList(allowRegex)) + .restrictRegexList(Collections.singletonList(restrictRegex)) + .tokenFormat(tokenFormat) + .outputProcessedImage(outputProcessedImage) + .outputOcrText(outputOcrText) + .maskingMethod(maskingMethod) + .pixelDensity(pixelDensity) + .maxResolution(maxResolution) + .outputProcessedAudio(outputProcessedAudio) + .outputTranscription(outputTranscription) + .bleep(bleep) + .outputDirectory(outputDirectory) + .waitTime(waitTime) + .build(); + + Assert.assertEquals(file, request.getFileInput().getFile()); + Assert.assertEquals(1, request.getEntities().size()); + Assert.assertEquals(allowRegex, request.getAllowRegexList().get(0)); + Assert.assertEquals(restrictRegex, request.getRestrictRegexList().get(0)); + Assert.assertEquals(tokenFormat, request.getTokenFormat()); + Assert.assertEquals(outputProcessedImage, request.getOutputProcessedImage()); + Assert.assertEquals(outputOcrText, request.getOutputOcrText()); + Assert.assertEquals(maskingMethod, request.getMaskingMethod()); + Assert.assertEquals(pixelDensity, request.getPixelDensity()); + Assert.assertEquals(maxResolution, request.getMaxResolution()); + Assert.assertEquals(outputProcessedAudio, request.getOutputProcessedAudio()); + Assert.assertEquals(outputTranscription, request.getOutputTranscription()); + Assert.assertEquals(bleep, request.getBleep()); + Assert.assertEquals(outputDirectory, request.getOutputDirectory()); + Assert.assertEquals(waitTime, request.getWaitTime()); + } + + @Test + public void testDeidentifyFileRequestBuilderDefaults() { + DeidentifyFileRequest request = DeidentifyFileRequest.builder().build(); + Assert.assertNull(request.getEntities()); + Assert.assertNull(request.getAllowRegexList()); + Assert.assertNull(request.getRestrictRegexList()); + Assert.assertNull(request.getTokenFormat()); + Assert.assertNull(request.getTransformations()); + Assert.assertEquals(false, request.getOutputProcessedImage()); + Assert.assertEquals(false, request.getOutputOcrText()); + Assert.assertNull(request.getMaskingMethod()); + Assert.assertNull(request.getPixelDensity()); + Assert.assertNull(request.getMaxResolution()); + Assert.assertEquals(false, request.getOutputProcessedAudio()); + Assert.assertNull(request.getOutputTranscription()); + Assert.assertNull(request.getBleep()); + Assert.assertNull(request.getOutputDirectory()); + Assert.assertNull(request.getWaitTime()); + } + + @Test + public void testGetDeidentifyImageRequest() { + File file = new File("test.jpg"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME, DetectEntities.DOB); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .outputProcessedImage(true) + .outputOcrText(true) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String format = "jpg"; + + DeidentifyImageRequest imageRequest = vaultClient.getDeidentifyImageRequest(request, vaultId, base64Content, format); + + Assert.assertEquals(vaultId, imageRequest.getVaultId()); + Assert.assertEquals(base64Content, imageRequest.getFile().getBase64()); + Assert.assertEquals(format.toUpperCase(), imageRequest.getFile().getDataFormat().name()); + } + + @Test + public void testGetDeidentifyPresentationRequest() { + File file = new File("test.pptx"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String format = "pptx"; + + DeidentifyPresentationRequest presRequest = vaultClient.getDeidentifyPresentationRequest(request, vaultId, base64Content, format); + + Assert.assertEquals(vaultId, presRequest.getVaultId()); + Assert.assertEquals(base64Content, presRequest.getFile().getBase64()); + Assert.assertEquals(format.toUpperCase(), presRequest.getFile().getDataFormat().name()); + } + + @Test + public void testGetDeidentifySpreadsheetRequest() { + File file = new File("test.csv"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String format = "csv"; + + DeidentifySpreadsheetRequest spreadsheetRequest = vaultClient.getDeidentifySpreadsheetRequest(request, vaultId, base64Content, format); + + Assert.assertEquals(vaultId, spreadsheetRequest.getVaultId()); + Assert.assertEquals(base64Content, spreadsheetRequest.getFile().getBase64()); + Assert.assertEquals(format.toUpperCase(), spreadsheetRequest.getFile().getDataFormat().name()); + } + + @Test + public void testGetDeidentifyStructuredTextRequest() { + File file = new File("test.json"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String format = "json"; + + DeidentifyStructuredTextRequest structuredTextRequest = vaultClient.getDeidentifyStructuredTextRequest(request, vaultId, base64Content, format); + + Assert.assertEquals(vaultId, structuredTextRequest.getVaultId()); + Assert.assertEquals(base64Content, structuredTextRequest.getFile().getBase64()); + Assert.assertEquals(format.toUpperCase(), structuredTextRequest.getFile().getDataFormat().name()); + } + + @Test + public void testGetDeidentifyDocumentRequest() { + File file = new File("test.docx"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String format = "docx"; + + DeidentifyDocumentRequest documentRequest = vaultClient.getDeidentifyDocumentRequest(request, vaultId, base64Content, format); + + Assert.assertEquals(vaultId, documentRequest.getVaultId()); + Assert.assertEquals(base64Content, documentRequest.getFile().getBase64()); + Assert.assertEquals(format.toUpperCase(), documentRequest.getFile().getDataFormat().name()); + } + + @Test + public void testGetDeidentifyPdfRequest() { + File file = new File("test.pdf"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .pixelDensity(200) + .maxResolution(300) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + + DeidentifyPdfRequest pdfRequest = vaultClient.getDeidentifyPdfRequest(request, vaultId, base64Content); + + Assert.assertEquals(vaultId, pdfRequest.getVaultId()); + Assert.assertEquals(base64Content, pdfRequest.getFile().getBase64()); + } + + @Test + public void testGetDeidentifyAudioRequest() throws SkyflowException { + File file = new File("test.mp3"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + AudioBleep bleep = AudioBleep.builder().frequency(1000.0).gain(10.0).startPadding(1.0).stopPadding(1.0).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .bleep(bleep) + .outputProcessedAudio(true) + .outputTranscription(DetectOutputTranscriptions.PLAINTEXT_TRANSCRIPTION) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String dataFormat = "mp3"; + + DeidentifyAudioRequest audioRequest = vaultClient.getDeidentifyAudioRequest(request, vaultId, base64Content, dataFormat); + + Assert.assertEquals(vaultId, audioRequest.getVaultId()); + Assert.assertEquals(base64Content, audioRequest.getFile().getBase64()); + Assert.assertEquals(dataFormat, audioRequest.getFile().getDataFormat().toString()); + } + + @Test + public void testGetDeidentifyTextFileRequest() { + File file = new File("test.txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME, DetectEntities.DOB); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + + com.skyflow.generated.rest.resources.files.requests.DeidentifyTextRequest textRequest = + vaultClient.getDeidentifyTextFileRequest(request, vaultId, base64Content); + + Assert.assertEquals(vaultId, textRequest.getVaultId()); + Assert.assertEquals(base64Content, textRequest.getFile().getBase64()); + } + + @Test + public void testGetDeidentifyStringRequest_AllTokenFormatFields() throws Exception { + List entities = Arrays.asList(DetectEntities.DOB); + List vaultToken = Collections.singletonList(DetectEntities.SSN); + List entityOnly = Collections.singletonList(DetectEntities.DOB); + List entityUniqueCounter = Collections.singletonList(DetectEntities.NAME); + + TokenFormat tokenFormat = TokenFormat.builder() + .vaultToken(vaultToken) + .entityOnly(entityOnly) + .entityUniqueCounter(entityUniqueCounter) + .build(); + + List allowRegex = Collections.singletonList("a.*"); + List restrictRegex = Collections.singletonList("b.*"); + + DateTransformation dateTransformation = new DateTransformation(10, 5, entities); + Transformations transformations = new Transformations(dateTransformation); + + DeidentifyTextRequest req = DeidentifyTextRequest.builder() + .text("Sensitive data") + .entities(entities) + .allowRegexList(allowRegex) + .restrictRegexList(restrictRegex) + .tokenFormat(tokenFormat) + .transformations(transformations) + .build(); + + DeidentifyStringRequest result = vaultClient.getDeidentifyStringRequest(req, "vaultId"); + Assert.assertNotNull(result); + Assert.assertEquals("vaultId", result.getVaultId()); + Assert.assertEquals("Sensitive data", result.getText()); + Assert.assertTrue(result.getAllowRegex().isPresent()); + Assert.assertTrue(result.getRestrictRegex().isPresent()); + Assert.assertTrue(result.getTransformations().isPresent()); + } + + @Test + public void testGetDeidentifyStringRequest_NullTokenFormatAndEntities() throws Exception { + DeidentifyTextRequest req = DeidentifyTextRequest.builder() + .text("No entities or tokenFormat") + .build(); + + DeidentifyStringRequest result = vaultClient.getDeidentifyStringRequest(req, "vaultId"); + Assert.assertNotNull(result); + Assert.assertEquals("vaultId", result.getVaultId()); + Assert.assertEquals("No entities or tokenFormat", result.getText()); + } + + @Test + public void testGetReidentifyStringRequest_AllFields() throws Exception { + List masked = Arrays.asList(DetectEntities.NAME, DetectEntities.DOB); + List plaintext = Collections.singletonList(DetectEntities.SSN); + List redacted = Collections.singletonList(DetectEntities.DATE); + + ReidentifyTextRequest req = ReidentifyTextRequest.builder() + .text("Sensitive data") + .maskedEntities(masked) + .plainTextEntities(plaintext) + .redactedEntities(redacted) + .build(); + + ReidentifyStringRequest result = vaultClient.getReidentifyStringRequest(req, "vaultId"); + Assert.assertNotNull(result); + Assert.assertEquals("vaultId", result.getVaultId()); + Assert.assertEquals("Sensitive data", result.getText()); + Assert.assertNotNull(result.getFormat()); + } + + @Test + public void testGetReidentifyStringRequest_NullFields() throws Exception { + ReidentifyTextRequest req = ReidentifyTextRequest.builder() + .text("No entities") + .build(); + + ReidentifyStringRequest result = vaultClient.getReidentifyStringRequest(req, "vaultId"); + Assert.assertNotNull(result); + Assert.assertEquals("vaultId", result.getVaultId()); + Assert.assertEquals("No entities", result.getText()); + Assert.assertNotNull(result.getFormat()); + } + + @Test + public void testGetTransformations_NullInput() throws Exception { + // Should return null if input is null + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("getTransformations", Transformations.class); + method.setAccessible(true); + Object result = method.invoke(vaultClient, new Object[]{null}); + Assert.assertNull(result); + } + + @Test + public void testGetTransformations_NullShiftDates() throws Exception { + Transformations transformations = new Transformations(null); + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("getTransformations", Transformations.class); + method.setAccessible(true); + Object result = method.invoke(vaultClient, transformations); + Assert.assertNull(result); + } + + @Test + public void testGetTransformations_EmptyEntities() throws Exception { + DateTransformation dateTransformation = new DateTransformation(10, 5, new ArrayList<>()); + Transformations transformations = new Transformations(dateTransformation); + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("getTransformations", Transformations.class); + method.setAccessible(true); + Object result = method.invoke(vaultClient, transformations); + Assert.assertNotNull(result); + // Should have empty entityTypes list + com.skyflow.generated.rest.types.Transformations restTransform = (com.skyflow.generated.rest.types.Transformations) result; + Assert.assertTrue(restTransform.getShiftDates().get().getEntityTypes().get().isEmpty()); + } + + @Test + public void testGetTransformations_WithEntities() throws Exception { + List entities = Arrays.asList(DetectEntities.DOB, DetectEntities.DATE); + DateTransformation dateTransformation = new DateTransformation(20, 5, entities); + Transformations transformations = new Transformations(dateTransformation); + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("getTransformations", Transformations.class); + method.setAccessible(true); + Object result = method.invoke(vaultClient, transformations); + Assert.assertNotNull(result); + com.skyflow.generated.rest.types.Transformations restTransform = (com.skyflow.generated.rest.types.Transformations) result; + Assert.assertEquals(2, restTransform.getShiftDates().get().getEntityTypes().get().size()); + } + + @Test + public void testGetDeidentifyGenericFileRequest_AllFields() { + File file = new File("test.custom"); + FileInput fileInput = FileInput.builder().file(file).build(); + List entities = Arrays.asList(DetectEntities.NAME, DetectEntities.DOB); + TokenFormat tokenFormat = TokenFormat.builder().entityOnly(entities).build(); + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(entities) + .tokenFormat(tokenFormat) + .allowRegexList(Arrays.asList("a.*")) + .restrictRegexList(Arrays.asList("b.*")) + .build(); + + String vaultId = "vault123"; + String base64Content = "base64string"; + String fileExtension = "txt"; + + com.skyflow.generated.rest.resources.files.requests.DeidentifyFileRequest genericRequest = + vaultClient.getDeidentifyGenericFileRequest(request, vaultId, base64Content, fileExtension); + + Assert.assertEquals(vaultId, genericRequest.getVaultId()); + Assert.assertEquals(base64Content, genericRequest.getFile().getBase64()); + Assert.assertNotNull(genericRequest.getEntityTypes()); + Assert.assertNotNull(genericRequest.getTokenType()); + Assert.assertTrue(genericRequest.getAllowRegex().isPresent()); + Assert.assertTrue(genericRequest.getRestrictRegex().isPresent()); + } + + @Test + public void testMapAudioDataFormat_mp3() throws Exception { + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("mapAudioDataFormat", String.class); + method.setAccessible(true); + Object result = method.invoke(vaultClient, "mp3"); + Assert.assertEquals(com.skyflow.generated.rest.resources.files.types.DeidentifyAudioRequestFileDataFormat.MP_3, result); + } + + @Test + public void testMapAudioDataFormat_wav() throws Exception { + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("mapAudioDataFormat", String.class); + method.setAccessible(true); + Object result = method.invoke(vaultClient, "wav"); + Assert.assertEquals(com.skyflow.generated.rest.resources.files.types.DeidentifyAudioRequestFileDataFormat.WAV, result); + } + + @Test + public void testMapAudioDataFormat_invalid() throws Exception { + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("mapAudioDataFormat", String.class); + method.setAccessible(true); + try { + method.invoke(vaultClient, "ogg"); + Assert.fail("Should throw SkyflowException for invalid audio type"); + } catch (Exception e) { + Throwable cause = e.getCause(); + Assert.assertTrue(cause instanceof SkyflowException); + } + } + + @Test + public void testPrioritiseCredentials_VaultConfigCredentials() throws Exception { + Credentials creds = new Credentials(); + creds.setApiKey("test_api_key"); + vaultConfig.setCredentials(creds); + + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("prioritiseCredentials"); + method.setAccessible(true); + method.invoke(vaultClient); + + Assert.assertEquals(creds, getPrivateField(vaultClient, "finalCredentials")); + } + + @Test + public void testPrioritiseCredentials_CommonCredentials() throws Exception { + vaultConfig.setCredentials(null); + Credentials creds = new Credentials(); + creds.setApiKey("common_api_key"); + setPrivateField(vaultClient, "commonCredentials", creds); + + java.lang.reflect.Method method = VaultClient.class.getDeclaredMethod("prioritiseCredentials"); + method.setAccessible(true); + method.invoke(vaultClient); + + Assert.assertEquals(creds, getPrivateField(vaultClient, "finalCredentials")); + } + + // Helper methods for reflection field access + private Object getPrivateField(Object obj, String fieldName) throws Exception { + java.lang.reflect.Field field = obj.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + return field.get(obj); + } + + private void setPrivateField(Object obj, String fieldName, Object value) throws Exception { + java.lang.reflect.Field field = obj.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + field.set(obj, value); + } +} diff --git a/src/test/java/com/skyflow/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..00c16af6 --- /dev/null +++ b/src/test/java/com/skyflow/config/ConnectionConfigTests.java @@ -0,0 +1,129 @@ +package com.skyflow.config; + +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.BeforeClass; +import org.junit.Test; + +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() { + connectionID = "connection123"; + connectionURL = "https://connection.url.com"; + invalidConnectionURL = "http://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..ff9fcfda --- /dev/null +++ b/src/test/java/com/skyflow/config/CredentialsTests.java @@ -0,0 +1,269 @@ +package com.skyflow.config; + +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; + +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() { + 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 testNullRoleInRolesInCredentials() { + try { + Credentials credentials = new Credentials(); + credentials.setPath(path); + roles.add(role); + roles.add(null); + credentials.setRoles(roles); + Validations.validateCredentials(credentials); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyRoleInRoles.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyRoleInRolesInCredentials() { + try { + 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..b99f6c9b --- /dev/null +++ b/src/test/java/com/skyflow/config/VaultConfigTests.java @@ -0,0 +1,160 @@ +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.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +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() { + 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); + vaultConfig.setEnv(null); + 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/errors/SkyflowExceptionTest.java b/src/test/java/com/skyflow/errors/SkyflowExceptionTest.java new file mode 100644 index 00000000..e2a1d921 --- /dev/null +++ b/src/test/java/com/skyflow/errors/SkyflowExceptionTest.java @@ -0,0 +1,140 @@ +package com.skyflow.errors; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.*; + +public class SkyflowExceptionTest { + + @Test + public void testConstructorWithMessage() { + SkyflowException ex = new SkyflowException("Test message"); + Assert.assertEquals("Test message", ex.getMessage()); + Assert.assertNull(ex.getHttpStatus()); + Assert.assertNull(ex.getGrpcCode()); + } + + @Test + public void testConstructorWithThrowable() { + Throwable cause = new RuntimeException("Root cause"); + SkyflowException ex = new SkyflowException(cause); + Assert.assertEquals("Root cause", ex.getMessage()); + } + + @Test + public void testConstructorWithMessageAndCause() { + Throwable cause = new RuntimeException("Root cause"); + SkyflowException ex = new SkyflowException("Test message", cause); + Assert.assertEquals("Test message", ex.getMessage()); + } + + @Test + public void testConstructorWithCodeAndMessage() { + SkyflowException ex = new SkyflowException(400, "Bad Request"); + Assert.assertEquals(Integer.valueOf(400), Integer.valueOf(ex.getHttpCode())); + Assert.assertEquals("Bad Request", ex.getMessage()); + Assert.assertEquals("Bad Request", ex.toString().contains("Bad Request") ? "Bad Request" : null); + Assert.assertNotNull(ex.getDetails()); + Assert.assertEquals(0, ex.getDetails().size()); + } + + @Test + public void testToStringFormat() { + SkyflowException ex = new SkyflowException(404, "Not Found"); + String str = ex.toString(); + Assert.assertTrue(str.contains("httpCode: 404")); + Assert.assertTrue(str.contains("message: Not Found")); + } + + @Test + public void testConstructorWithJsonErrorBodyArrayDetailsNonEmpty() { + String json = "{\"error\":{\"message\":\"json error\",\"grpc_code\":7,\"http_status\":\"NOT_FOUND\",\"details\":[{\"info\":\"detail1\"}]}}"; + Map> headers = new HashMap<>(); + headers.put("x-request-id", Collections.singletonList("req-123")); + SkyflowException ex = new SkyflowException(404, new RuntimeException("fail"), headers, json); + Assert.assertEquals("json error", ex.getMessage()); + Assert.assertEquals(Integer.valueOf(7), ex.getGrpcCode()); + Assert.assertEquals("NOT_FOUND", ex.getHttpStatus()); + Assert.assertEquals("req-123", ex.getRequestId()); + Assert.assertNotNull(ex.getDetails()); + Assert.assertTrue(ex.getDetails().size() > 0); + } + + @Test + public void testConstructorWithJsonErrorBodyArrayDetailsEmpty() { + String json = "{\"error\":{\"message\":\"json error\",\"grpc_code\":7,\"http_status\":\"NOT_FOUND\",\"details\":[]}}"; + Map> headers = new HashMap<>(); + SkyflowException ex = new SkyflowException(404, new RuntimeException("fail"), headers, json); + Assert.assertEquals("json error", ex.getMessage()); + Assert.assertEquals(Integer.valueOf(7), ex.getGrpcCode()); + Assert.assertEquals("NOT_FOUND", ex.getHttpStatus()); + Assert.assertNotNull(ex.getDetails()); + Assert.assertEquals(0, ex.getDetails().size()); + } + + @Test + public void testConstructorWithNullErrorBody() { + Map> headers = new HashMap<>(); + SkyflowException ex = new SkyflowException(500, new RuntimeException("fail"), headers, null); + Assert.assertEquals("fail", ex.getMessage()); + Assert.assertNull(ex.getGrpcCode()); + } + + @Test + public void testGettersAndSetters() { + SkyflowException ex = new SkyflowException("msg"); + Assert.assertNull(ex.getRequestId()); + Assert.assertNull(ex.getDetails()); + Assert.assertNull(ex.getGrpcCode()); + Assert.assertNull(ex.getHttpStatus()); + } + + @Test + public void testSetDetailsWithErrorFromClientHeader() { + String json = "{\"error\":{\"message\":\"test error\",\"grpc_code\":13,\"details\":[]}}"; + Map> headers = new HashMap<>(); + headers.put("error-from-client", Collections.singletonList("client error")); + + SkyflowException ex = new SkyflowException(500, new RuntimeException("fail"), headers, json); + + Assert.assertNotNull(ex.getDetails()); + Assert.assertEquals(1, ex.getDetails().size()); + Assert.assertEquals("client error", ex.getDetails().get(0).getAsJsonObject().get("errorFromClient").getAsString()); + } + + @Test + public void testSetDetailsWithErrorFromClientHeaderAndNullDetails() { + String json = "{\"error\":{\"message\":\"test error\",\"grpc_code\":13}}"; + Map> headers = new HashMap<>(); + headers.put("error-from-client", Collections.singletonList("client error")); + + SkyflowException ex = new SkyflowException(500, new RuntimeException("fail"), headers, json); + + Assert.assertNotNull(ex.getDetails()); + Assert.assertEquals(1, ex.getDetails().size()); + Assert.assertEquals("client error", ex.getDetails().get(0).getAsJsonObject().get("errorFromClient").getAsString()); + } + + @Test + public void testSetDetailsWithNoErrorFromClientHeaderAndEmptyDetails() { + String json = "{\"error\":{\"message\":\"test error\",\"grpc_code\":13,\"details\":[]}}"; + Map> headers = new HashMap<>(); + + SkyflowException ex = new SkyflowException(500, new RuntimeException("fail"), headers, json); + + Assert.assertNotNull(ex.getDetails()); + Assert.assertEquals(0, ex.getDetails().size()); + } + + @Test + public void testToStringWithNullFields() { + SkyflowException ex = new SkyflowException("msg"); + String str = ex.toString(); + Assert.assertTrue(str.contains("requestId: null")); + Assert.assertTrue(str.contains("grpcCode: null")); + Assert.assertTrue(str.contains("httpCode: null")); + Assert.assertTrue(str.contains("httpStatus: null")); + Assert.assertTrue(str.contains("details: null")); + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/serviceaccount/util/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..4bfb697c --- /dev/null +++ b/src/test/java/com/skyflow/serviceaccount/util/BearerTokenTests.java @@ -0,0 +1,225 @@ +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( + Utils.parameterizedString(ErrorMessage.FileNotFound.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( + Utils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), invalidFilePath), + 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..04083077 --- /dev/null +++ b/src/test/java/com/skyflow/serviceaccount/util/SignedDataTokensTests.java @@ -0,0 +1,229 @@ +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(Utils.parameterizedString(ErrorMessage.FileNotFound.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( + Utils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), invalidFilePath), + 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 = "{" + + "\"token\":\"" + dataToken + "\"," + + "\"signedToken\":\"signed_token_" + signedToken + "\"" + + "}"; + + Assert.assertEquals(responseString, response.toString()); + Assert.assertEquals(dataToken, response.getToken()); + Assert.assertEquals("signed_token_" + signedToken, response.getSignedToken()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} diff --git a/src/test/java/com/skyflow/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 70% rename from src/test/java/com/skyflow/common/utils/HttpUtilityTest.java rename to src/test/java/com/skyflow/utils/HttpUtilityTests.java index e473ee1f..f7214690 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,33 +19,31 @@ 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 { expected = "{\"status\":\"success\"}"; - expectedError = "{\"status\":\"something went wrong\"}"; + expectedError = "{\"error\":{\"grpc_code\":123,\"http_code\":500,\"message\":\"something went wrong\",\"http_status\":\"internal server error\",\"details\":[]}}\n"; mockConnection = Mockito.mock(HttpURLConnection.class); given(mockConnection.getInputStream()).willReturn(new ByteArrayInputStream(expected.getBytes())); given(mockConnection.getErrorStream()).willReturn(new ByteArrayInputStream(expectedError.getBytes())); @@ -65,88 +60,66 @@ 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()); + Assert.assertEquals(500, e.getHttpCode()); + Assert.assertEquals(new Integer(123), e.getGrpcCode()); + Assert.assertEquals("internal server error", e.getHttpStatus()); + Assert.assertEquals("something went wrong", e.getMessage()); + Assert.assertTrue(e.getDetails().isEmpty()); } catch (Exception e) { fail(INVALID_EXCEPTION_THROWN); } diff --git a/src/test/java/com/skyflow/utils/UtilsTests.java b/src/test/java/com/skyflow/utils/UtilsTests.java new file mode 100644 index 00000000..83e5a6ff --- /dev/null +++ b/src/test/java/com/skyflow/utils/UtilsTests.java @@ -0,0 +1,219 @@ +package com.skyflow.utils; + +import com.google.gson.JsonObject; +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( + Utils.parameterizedString(ErrorMessage.FileNotFound.getMessage(), filePath), + 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() + .method(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); + } + } + + @Test + public void testGetMetrics() { + try { + JsonObject metrics = Utils.getMetrics(); + Assert.assertNotNull(metrics.get(Constants.SDK_METRIC_NAME_VERSION)); + Assert.assertNotNull(metrics.get(Constants.SDK_METRIC_CLIENT_DEVICE_MODEL)); + Assert.assertNotNull(metrics.get(Constants.SDK_METRIC_CLIENT_OS_DETAILS)); + Assert.assertNotNull(metrics.get(Constants.SDK_METRIC_RUNTIME_DETAILS)); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testGetMetricsWithException() { + try { + // Clearing System Properties explicitly to throw exception + System.clearProperty("os.name"); + System.clearProperty("os.version"); + System.clearProperty("java.version"); + + JsonObject metrics = Utils.getMetrics(); + Assert.assertEquals("skyflow-java@v2", metrics.get(Constants.SDK_METRIC_NAME_VERSION).getAsString()); + Assert.assertEquals("Java@", metrics.get(Constants.SDK_METRIC_RUNTIME_DETAILS).getAsString()); + Assert.assertTrue(metrics.get(Constants.SDK_METRIC_CLIENT_DEVICE_MODEL).getAsString().isEmpty()); + Assert.assertTrue(metrics.get(Constants.SDK_METRIC_CLIENT_OS_DETAILS).getAsString().isEmpty()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} diff --git a/src/test/java/com/skyflow/vault/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..63717b5c --- /dev/null +++ b/src/test/java/com/skyflow/vault/connection/InvokeConnectionTests.java @@ -0,0 +1,440 @@ +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() + .method(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.getMethod()); + Assert.assertNotNull(request.getRequestBody()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testValidInputInInvokeConnectionRequestValidationsWithNullRequestBody() { + queryParams.put("query_param", "value"); + pathParams.put("path_param", "value"); + requestHeaders.put("header", "value"); + try { + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .method(null) + .requestHeaders(requestHeaders) + .pathParams(pathParams) + .queryParams(queryParams) + .requestBody(null) + .build(); + Validations.validateInvokeConnectionRequest(request); + Assert.assertEquals(1, request.getQueryParams().size()); + Assert.assertEquals(1, request.getPathParams().size()); + Assert.assertEquals(1, request.getRequestHeaders().size()); + Assert.assertEquals(RequestMethod.POST.toString(), request.getMethod().toString()); + Assert.assertNull(request.getRequestBody()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testEmptyRequestHeadersInInvokeConnectionRequestValidations() { + try { + InvokeConnectionRequest request = InvokeConnectionRequest.builder() + .method(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() + .method(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() + .method(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() + .method(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() + .method(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() + .method(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() + .method(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() + .method(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() + .method(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() + .method(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() + .method(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() + .method(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() + .method(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() + .method(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() + .method(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() + .method(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 data = new JsonObject(); + data.addProperty("test_key_1", "test_value_1"); + data.addProperty("test_key_2", "test_value_2"); + HashMap metadata = new HashMap<>(); + metadata.put("requestId", "12345"); + InvokeConnectionResponse connectionResponse = new InvokeConnectionResponse(data, metadata, null); + String responseString = "{\"data\":{\"test_key_1\":\"test_value_1\",\"test_key_2\":\"test_value_2\"}," + + "\"metadata\":{\"requestId\":\"12345\"}," + + "\"errors\":null}"; + + Assert.assertNotNull(connectionResponse.getData()); + Assert.assertEquals(responseString, connectionResponse.toString()); + Assert.assertEquals(1, connectionResponse.getMetadata().size()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} diff --git a/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java b/src/test/java/com/skyflow/vault/controller/ConnectionControllerTests.java new file mode 100644 index 00000000..b121280a --- /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/DetectControllerFileTests.java b/src/test/java/com/skyflow/vault/controller/DetectControllerFileTests.java new file mode 100644 index 00000000..da8494e1 --- /dev/null +++ b/src/test/java/com/skyflow/vault/controller/DetectControllerFileTests.java @@ -0,0 +1,409 @@ +package com.skyflow.vault.controller; + +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.detect.AudioBleep; +import com.skyflow.vault.detect.DeidentifyFileRequest; +import com.skyflow.vault.detect.FileInput; +import com.skyflow.vault.detect.GetDetectRunRequest; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.nio.file.Files; +import java.util.ArrayList; + +public class DetectControllerFileTests { + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static VaultConfig vaultConfig = null; + private static DetectController detectController = null; + + @BeforeClass + public static void setup() { + vaultID = "vault123"; + clusterID = "cluster123"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(com.skyflow.enums.Env.DEV); + vaultConfig.setCredentials(credentials); + + detectController = new DetectController(vaultConfig, credentials); + } + + @Test + public void testUnreadableFileInDeidentifyFileRequest() { + try { + File file = new File("unreadable.txt") { + @Override + public boolean exists() { return true; } + @Override + public boolean isFile() { return true; } + @Override + public boolean canRead() { return false; } + }; + FileInput fileInput = FileInput.builder().file(file).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException | RuntimeException e) { + // Depending on implementation, could be SkyflowException or RuntimeException + Assert.assertTrue(e.getMessage().contains("not readable") || e.getMessage().contains("unreadable.txt")); + } + } + + @Test + public void testNullEntitiesInDeidentifyFileRequest() { + try { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(new ArrayList<>()) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testNullRequest() { + try { + detectController.deidentifyFile(null); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testFileInputBothFileAndFilePathNull() { + try { + FileInput fileInput = FileInput.builder().build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail("Should have thrown an exception for both file and filePath being null"); + } catch (Exception e) { + Assert.assertTrue(e.getMessage().contains(ErrorMessage.EmptyFileAndFilePathInDeIdentifyFile.getMessage())); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testFileInputBothFileAndFilePathProvided() { + try { + java.io.File file = java.io.File.createTempFile("test", ".txt"); + String filePath = file.getAbsolutePath(); + FileInput fileInput = FileInput.builder().file(file).filePath(filePath).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail("Should have thrown an exception for both file and filePath being provided"); + } catch (Exception e) { + Assert.assertTrue(e.getMessage().contains(ErrorMessage.BothFileAndFilePathProvided.getMessage())); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testFileInputEmptyFilePath() { + try { + FileInput fileInput = FileInput.builder().filePath("").build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail("Should have thrown an exception for empty filePath"); + } catch (Exception e) { + Assert.assertTrue(e.getMessage().contains(ErrorMessage.InvalidFilePath.getMessage())); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testFileInputNonExistentFile() { + try { + java.io.File file = new java.io.File("nonexistent.txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail("Should have thrown an exception for non-existent file"); + } catch (Exception e) { + Assert.assertTrue(e.getMessage().contains(ErrorMessage.FileNotFoundToDeidentify.getMessage())); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testFileInputUnreadableFile() { + try { + java.io.File file = new java.io.File("unreadable.txt") { + @Override + public boolean exists() { return true; } + @Override + public boolean isFile() { return true; } + @Override + public boolean canRead() { return false; } + }; + FileInput fileInput = FileInput.builder().file(file).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail("Should have thrown an exception for unreadable file"); + } catch (Exception e) { + Assert.assertTrue(e.getMessage().contains(ErrorMessage.FileNotReadableToDeidentify.getMessage())); + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testNonExistentFileInDeidentifyFileRequest() { + try { + File file = new File("nonexistent.txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder().file(fileInput).build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testInvalidPixelDensity() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .pixelDensity(-1) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testInvalidMaxResolution() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .maxResolution(-1) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testInvalidBleepFrequency() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + AudioBleep bleep = AudioBleep.builder().build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .bleep(bleep) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testInvalidOutputDirectory() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .outputDirectory("not/a/real/dir") + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testInvalidWaitTime() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .waitTime(-1) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testWaitTimeExceedsLimit() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .waitTime(100) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testNullGetDetectRunRequest() { + try { + detectController.getDetectRun(null); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testEmptyRunIdInGetDetectRunRequest() { + try { + GetDetectRunRequest request = GetDetectRunRequest.builder().build(); + detectController.getDetectRun(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testNullRunIdInGetDetectRunRequest() { + try { + GetDetectRunRequest request = GetDetectRunRequest.builder().runId(null).build(); + detectController.getDetectRun(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + } + + @Test + public void testInvalidBleepGain() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + AudioBleep bleep = AudioBleep.builder().frequency(440.0).gain(-1.0).startPadding(0.1).stopPadding(0.1).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .bleep(bleep) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testInvalidBleepStartPadding() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + AudioBleep bleep = AudioBleep.builder().frequency(440.0).gain(0.5).startPadding(-0.1).stopPadding(0.1).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .bleep(bleep) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testInvalidBleepStopPadding() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + try { + AudioBleep bleep = AudioBleep.builder().frequency(440.0).gain(0.5).startPadding(0.1).stopPadding(-0.1).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .bleep(bleep) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + } + + @Test + public void testOutputDirectoryNotDirectory() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + File notADir = File.createTempFile("notadir", ".txt"); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .outputDirectory(notADir.getAbsolutePath()) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } + file.delete(); + notADir.delete(); + } + + @Test + public void testOutputDirectoryNotWritable() throws Exception { + File file = File.createTempFile("test", ".txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + File dir = Files.createTempDirectory("notwritabledir").toFile(); + dir.setWritable(false); + try { + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .outputDirectory(dir.getAbsolutePath()) + .build(); + detectController.deidentifyFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (Exception e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), 400); + } finally { + dir.setWritable(true); + file.delete(); + dir.delete(); + } + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/controller/DetectControllerTests.java b/src/test/java/com/skyflow/vault/controller/DetectControllerTests.java new file mode 100644 index 00000000..aae713b1 --- /dev/null +++ b/src/test/java/com/skyflow/vault/controller/DetectControllerTests.java @@ -0,0 +1,121 @@ +package com.skyflow.vault.controller; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.HttpStatus; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.vault.detect.DeidentifyTextRequest; +import com.skyflow.vault.detect.ReidentifyTextRequest; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class DetectControllerTests { + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String vaultID = null; + private static String clusterID = null; + private static VaultConfig vaultConfig = null; + private static Skyflow skyflowClient = null; + + @BeforeClass + public static void setup() throws SkyflowException, NoSuchMethodException { + vaultID = "vault123"; + clusterID = "cluster123"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.DEV); + vaultConfig.setCredentials(credentials); + + + skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addVaultConfig(vaultConfig) + .build(); + } + + + @Test + public void testNullTextInRequestInDeidentifyStringMethod() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder().text(null).build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.detect(vaultID).deidentifyText(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.InvalidTextInDeIdentify.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertNull(e.getRequestId()); + Assert.assertNull(e.getGrpcCode()); + Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + } + } + + @Test + public void testEmptyTextInRequestInDeidentifyStringMethod() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder().text("").build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.detect(vaultID).deidentifyText(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.InvalidTextInDeIdentify.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertNull(e.getRequestId()); + Assert.assertNull(e.getGrpcCode()); + Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + } + } + + @Test + public void testNullTextInRequestInReidentifyStringMethod() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder().text(null).build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.detect(vaultID).reidentifyText(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.InvalidTextInReIdentify.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertNull(e.getRequestId()); + Assert.assertNull(e.getGrpcCode()); + Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + } + } + + @Test + public void testEmptyTextInRequestInReidentifyStringMethod() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder().text("").build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.detect(vaultID).reidentifyText(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.InvalidTextInReIdentify.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertNull(e.getRequestId()); + Assert.assertNull(e.getGrpcCode()); + Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + } + } + +} + diff --git a/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java new file mode 100644 index 00000000..4115bc2c --- /dev/null +++ b/src/test/java/com/skyflow/vault/controller/VaultControllerTests.java @@ -0,0 +1,188 @@ +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.HttpStatus; +import com.skyflow.errors.SkyflowException; +import com.skyflow.generated.rest.ApiClient; +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; + + @BeforeClass + public static void setup() throws SkyflowException, NoSuchMethodException { + vaultID = "vault123"; + clusterID = "cluster123"; + + Credentials credentials = new Credentials(); + credentials.setToken("valid-token"); + + vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(vaultID); + vaultConfig.setClusterId(clusterID); + vaultConfig.setEnv(Env.DEV); + vaultConfig.setCredentials(credentials); + + + skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.DEBUG) + .addVaultConfig(vaultConfig) + .build(); + + } + + @Test + public void testInvalidRequestInInsertMethod() { + try { + InsertRequest request = InsertRequest.builder().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.InvalidDetokenizeData.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.assertTrue(e.getDetails().isEmpty()); + Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + } + } + + @Test + public void testInvalidRequestInFileUploadMethod() { + try { + FileUploadRequest request = FileUploadRequest.builder().build(); + skyflowClient = Skyflow.builder().setLogLevel(LogLevel.DEBUG).addVaultConfig(vaultConfig).build(); + skyflowClient.vault().uploadFile(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertNull(e.getRequestId()); + Assert.assertNull(e.getGrpcCode()); + Assert.assertTrue(e.getDetails().isEmpty()); + Assert.assertEquals(HttpStatus.BAD_REQUEST.getHttpStatus(), e.getHttpStatus()); + } + } + +} diff --git a/src/test/java/com/skyflow/vault/data/DeleteTests.java b/src/test/java/com/skyflow/vault/data/DeleteTests.java new file mode 100644 index 00000000..befc3d26 --- /dev/null +++ b/src/test/java/com/skyflow/vault/data/DeleteTests.java @@ -0,0 +1,173 @@ +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.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 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() { + 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); + 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() { + 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 testNullIdInIdsInDeleteRequestValidations() { + ids.add(skyflowID); + ids.add(null); + DeleteRequest request = DeleteRequest.builder().ids(ids).table(table).build(); + try { + Validations.validateDeleteRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyIdInIds.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyIdInIdsInDeleteRequestValidations() { + ids.add(skyflowID); + 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.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.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 = "{\"deletedIds\":[\"" + skyflowID + "\"],\"errors\":null}"; + 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/FileUploadTests.java b/src/test/java/com/skyflow/vault/data/FileUploadTests.java new file mode 100644 index 00000000..7758fe36 --- /dev/null +++ b/src/test/java/com/skyflow/vault/data/FileUploadTests.java @@ -0,0 +1,222 @@ +package com.skyflow.vault.data; + +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; + +public class FileUploadTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static String table; + private static String skyflowId; + private static String columnName; + private static String filePath; + private static String base64Content; + private static File fileObject; + private static String fileName; + + @BeforeClass + public static void setup() { + table = "test_table"; + skyflowId = "test_id"; + columnName = "file_column"; + filePath = "src/test/resources/notJson.txt"; + base64Content = "SGVsbG8gV29ybGQ="; + fileObject = new File(filePath); + fileName = "notJson.txt"; + } + + @Test + public void testValidFileUploadRequestWithFilePath() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId(skyflowId) + .columnName(columnName) + .filePath(filePath) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.assertEquals(table, request.getTable()); + Assert.assertEquals(skyflowId, request.getSkyflowId()); + Assert.assertEquals(columnName, request.getColumnName()); + Assert.assertEquals(filePath, request.getFilePath()); + Assert.assertEquals(fileName, request.getFileName()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testValidFileUploadRequestWithBase64() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId(skyflowId) + .columnName(columnName) + .base64(base64Content) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.assertEquals(base64Content, request.getBase64()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testValidFileUploadRequestWithFileObject() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId(skyflowId) + .columnName(columnName) + .fileObject(fileObject) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.assertEquals(fileObject, request.getFileObject()); + } catch (SkyflowException e) { + System.out.println("## e:" + e.getMessage()); + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testMissingTable() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .skyflowId(skyflowId) + .columnName(columnName) + .filePath(filePath) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.TableKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testMissingSkyflowId() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .columnName(columnName) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.SkyflowIdKeyError.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptySkyflowId() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId("") + .columnName(columnName) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptySkyflowId.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testMissingColumnName() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId(skyflowId) + .filePath(filePath) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.ColumnNameKeyErrorFileUpload.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testMissingFileData() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId(skyflowId) + .columnName(columnName) + .fileName(fileName) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.MissingFileSourceInUploadFileRequest.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testMissingFileNameWithBase64Invalid() { + try { + FileUploadRequest request = FileUploadRequest.builder() + .table(table) + .skyflowId(skyflowId) + .columnName(columnName) + .base64(base64Content) + .build(); + + Validations.validateFileUploadRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.FileNameMustBeProvidedWithFileObject.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + +} diff --git a/src/test/java/com/skyflow/vault/data/GetTests.java b/src/test/java/com/skyflow/vault/data/GetTests.java new file mode 100644 index 00000000..74306d4b --- /dev/null +++ b/src/test/java/com/skyflow/vault/data/GetTests.java @@ -0,0 +1,528 @@ +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.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; +import java.util.HashMap; + +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() { + + 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_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) + .redactionType(null) + .downloadURL(false) + .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.getReturnTokens()); + Assert.assertFalse(request.getDownloadURL()); + 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(null) + .offset("2") + .limit("1") + .fields(fields) + .orderBy(null) + .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 testNullIdInIdsInGetRequestValidations() { + ids.add(skyflowID); + ids.add(null); + GetRequest request = GetRequest.builder().ids(ids).table(table).build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyIdInIds.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyIdInIdsInGetRequestValidations() { + ids.add(skyflowID); + 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 testNullFieldInFieldsInGetRequestValidations() { + ids.add(skyflowID); + fields.add(field); + fields.add(null); + GetRequest request = GetRequest.builder().ids(ids).table(table).fields(fields).build(); + try { + Validations.validateGetRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyFieldInFields.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyFieldInFieldsInGetRequestValidations() { + ids.add(skyflowID); + 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).returnTokens(false).redactionType(null).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 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).redactionType(null).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).redactionType(null).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 = "{\"data\":[" + + "{\"test_column_1\":\"test_value_1\"," + + "\"test_column_2\":\"test_value_2\"}," + + "{\"test_column_1\":\"test_value_1\"," + + "\"test_column_2\":\"test_value_2\"}]" + + ",\"errors\":" + errors + "}"; + Assert.assertEquals(2, response.getData().size()); + Assert.assertTrue(response.getErrors().isEmpty()); + Assert.assertEquals(responseString, response.toString()); + } 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..00399f00 --- /dev/null +++ b/src/test/java/com/skyflow/vault/data/InsertTests.java @@ -0,0 +1,434 @@ +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.TokenMode; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; + +public class InsertTests { + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + private static final String requestId = "95be08fc-4d13-4335-8b8d-24e85d53ed1d"; + private static String vaultID = null; + private static String clusterID = null; + private static String table = null; + 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() { + + 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); + + 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(TokenMode.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(TokenMode.ENABLE, request.getTokenMode()); + Assert.assertTrue(request.getContinueOnError()); + Assert.assertTrue(request.getReturnTokens()); + Assert.assertFalse(request.getHomogeneous()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testValidInputInInsertRequestValidationsWithTokenModeDisable() { + try { + values.add(valueMap); + tokens.add(tokenMap); + InsertRequest request = InsertRequest.builder() + .table(table) + .continueOnError(null) + .returnTokens(null) + .homogeneous(false) + .upsert(upsert) + .values(values) + .tokenMode(null) + .build(); + Validations.validateInsertRequest(request); + + Assert.assertEquals(table, request.getTable()); + Assert.assertEquals(upsert, request.getUpsert()); + Assert.assertEquals(1, request.getValues().size()); + Assert.assertEquals(TokenMode.DISABLE, request.getTokenMode()); + Assert.assertNull(request.getTokens()); + Assert.assertFalse(request.getReturnTokens()); + Assert.assertFalse(request.getContinueOnError()); + Assert.assertFalse(request.getHomogeneous()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoTableInInsertRequestValidations() { + InsertRequest request = InsertRequest.builder().build(); + 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.TokensPassedForTokenModeDisable.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoTokensWithTokenStrictEnableInInsertRequestValidations() { + values.add(valueMap); + InsertRequest request = InsertRequest.builder() + .table(table).values(values).tokenMode(TokenMode.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.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE.toString()), + e.getMessage() + ); + } + } + + @Test + public void testNoTokensWithTokenStrictEnableStrictInInsertRequestValidations() { + values.add(valueMap); + InsertRequest request = InsertRequest.builder() + .table(table).values(values).tokenMode(TokenMode.ENABLE_STRICT) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE_STRICT.toString()), + e.getMessage() + ); + } + } + + @Test + public void testEmptyTokensWithTokenStrictEnableInInsertRequestValidations() { + values.add(valueMap); + InsertRequest request = InsertRequest.builder() + .table(table).values(values).tokens(tokens).tokenMode(TokenMode.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).tokenMode(TokenMode.ENABLE_STRICT) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForTokenModeEnableStrict.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).tokenMode(TokenMode.ENABLE_STRICT) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForTokenModeEnableStrict.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).tokenMode(TokenMode.ENABLE_STRICT) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.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).tokenMode(TokenMode.ENABLE_STRICT) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.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).tokenMode(TokenMode.ENABLE_STRICT) + .build(); + try { + Validations.validateInsertRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyValueInTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testInsertResponse() { + try { + ArrayList> errorFields = new ArrayList<>(); + HashMap error = new HashMap<>(); + error.put("requestIndex", 0); + error.put("requestId", requestId); + error.put("error", "Insert failed"); + errorFields.add(error); + values.add(valueMap); + values.add(valueMap); + InsertResponse response = new InsertResponse(values, errorFields); + String responseString = "{\"insertedFields\":[" + + "{\"test_column_1\":\"test_value_1\"," + + "\"test_column_2\":\"test_value_2\"}," + + "{\"test_column_1\":\"test_value_1\"," + + "\"test_column_2\":\"test_value_2\"}]" + + ",\"errors\":[{\"requestIndex\":0,\"requestId\":\"" + requestId + "\",\"error\":\"Insert failed\"}]}"; + Assert.assertEquals(2, response.getInsertedFields().size()); + Assert.assertEquals(1, response.getErrors().size()); + Assert.assertEquals(responseString, response.toString()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + +} diff --git a/src/test/java/com/skyflow/vault/data/QueryTests.java b/src/test/java/com/skyflow/vault/data/QueryTests.java new file mode 100644 index 00000000..c8e453f5 --- /dev/null +++ b/src/test/java/com/skyflow/vault/data/QueryTests.java @@ -0,0 +1,107 @@ +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.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 java.util.ArrayList; +import java.util.HashMap; + +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() { + 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"); + } + + @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 = "{\"fields\":" + + "[{\"card_number\":\"test_card_number\",\"name\":\"test_name\",\"tokenizedData\":{}}," + + "{\"card_number\":\"test_card_number\",\"name\":\"test_name\",\"tokenizedData\":{}}]," + + "\"errors\":null}"; + 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..be702d4e --- /dev/null +++ b/src/test/java/com/skyflow/vault/data/UpdateTests.java @@ -0,0 +1,459 @@ +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.TokenMode; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.ErrorMessage; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.HashMap; + +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() { + 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) + .tokenMode(TokenMode.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 testValidInputInUpdateRequestValidationsWithTokenModeDisable() { + try { + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); + UpdateRequest request = UpdateRequest.builder() + .table(table) + .data(dataMap) + .returnTokens(null) + .tokenMode(null) + .build(); + Validations.validateUpdateRequest(request); + Assert.assertEquals(table, request.getTable()); + Assert.assertEquals(3, request.getData().size()); + Assert.assertFalse(request.getReturnTokens()); + Assert.assertNull(request.getTokens()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoSkyflowIdInUpdateRequestValidations() { + dataMap.put("test_column_1", "test_value_1"); + 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 testNullKeyInValuesInUpdateRequestValidations() { + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); + dataMap.put(null, "test_value_3"); + UpdateRequest request = UpdateRequest.builder().table(table).data(dataMap).build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyKeyInValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyKeyInValuesInUpdateRequestValidations() { + dataMap.put("skyflow_id", skyflowID); + 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 testNullValueInValuesInUpdateRequestValidations() { + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); + dataMap.put("test_column_3", null); + UpdateRequest request = UpdateRequest.builder().table(table).data(dataMap).build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyValueInValues.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testEmptyValueInValuesInUpdateRequestValidations() { + dataMap.put("skyflow_id", skyflowID); + 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 testTokensWithTokenModeDisableInUpdateRequestValidations() { + 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).tokenMode(TokenMode.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.TokensPassedForTokenModeDisable.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + } + } + + @Test + public void testNoTokensWithTokenModeEnableInUpdateRequestValidations() { + 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).tokenMode(TokenMode.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.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE.toString()), + e.getMessage() + ); + } + } + + @Test + public void testNoTokensWithTokenModeEnableStrictInUpdateRequestValidations() { + 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).tokenMode(TokenMode.ENABLE_STRICT) + .build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.NoTokensWithTokenMode.getMessage(), TokenMode.ENABLE_STRICT.toString()), + e.getMessage() + ); + } + } + + @Test + public void testEmptyTokensWithTokenModeEnableInUpdateRequestValidations() { + 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).tokenMode(TokenMode.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 testInsufficientTokensWithTokenModeEnableStrictInUpdateRequestValidations() { + 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).tokenMode(TokenMode.ENABLE_STRICT) + .build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.InsufficientTokensPassedForTokenModeEnableStrict.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).tokenMode(TokenMode.ENABLE_STRICT) + .build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.MismatchOfFieldsAndTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testNullKeyInTokensInUpdateRequestValidations() { + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); + tokenMap.put("test_column_1", "test_token_1"); + tokenMap.put(null, "test_token_2"); + UpdateRequest request = UpdateRequest.builder() + .table(table).data(dataMap).tokens(tokenMap).tokenMode(TokenMode.ENABLE_STRICT) + .build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyKeyInTokens.getMessage(), e.getMessage()); + } + } + + @Test + public void testNullValueInTokensInUpdateRequestValidations() { + dataMap.put("skyflow_id", skyflowID); + dataMap.put("test_column_1", "test_value_1"); + dataMap.put("test_column_2", "test_value_2"); + tokenMap.put("test_column_1", "test_token_1"); + tokenMap.put("test_column_2", null); + UpdateRequest request = UpdateRequest.builder() + .table(table).data(dataMap).tokens(tokenMap).tokenMode(TokenMode.ENABLE_STRICT) + .build(); + try { + Validations.validateUpdateRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.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 = "{\"updatedField\":{\"skyflowId\":\"" + skyflowID + "\"," + + "\"test_column_1\":\"test_token_1\",\"test_column_2\":\"test_token_2\"}" + + ",\"errors\":null}"; + 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/detect/DeidentifyFileRequestTest.java b/src/test/java/com/skyflow/vault/detect/DeidentifyFileRequestTest.java new file mode 100644 index 00000000..1b19d9d9 --- /dev/null +++ b/src/test/java/com/skyflow/vault/detect/DeidentifyFileRequestTest.java @@ -0,0 +1,99 @@ +package com.skyflow.vault.detect; + +import com.skyflow.enums.DetectEntities; +import com.skyflow.enums.DetectOutputTranscriptions; +import com.skyflow.enums.MaskingMethod; +import org.junit.Assert; +import org.junit.Test; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; + +public class DeidentifyFileRequestTest { + + @Test + public void testBuilderAndGetters() { + File file = new File("test.txt"); + FileInput fileInput = FileInput.builder().file(file).build(); + DetectEntities entity = DetectEntities.DOB; + MaskingMethod maskingMethod = MaskingMethod.BLACKBOX; + DetectOutputTranscriptions transcription = DetectOutputTranscriptions.TRANSCRIPTION; + String outputDir = "/tmp/output"; + int waitTime = 42; + + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(Arrays.asList(entity)) + .allowRegexList(Arrays.asList("a.*")) + .restrictRegexList(Arrays.asList("b.*")) + .maskingMethod(maskingMethod) + .outputProcessedImage(true) + .outputOcrText(true) + .outputProcessedAudio(true) + .outputTranscription(transcription) + .outputDirectory(outputDir) + .waitTime(waitTime) + .build(); + + Assert.assertEquals(entity, request.getEntities().get(0)); + Assert.assertEquals("a.*", request.getAllowRegexList().get(0)); + Assert.assertEquals("b.*", request.getRestrictRegexList().get(0)); + Assert.assertEquals(maskingMethod, request.getMaskingMethod()); + Assert.assertTrue(request.getOutputProcessedImage()); + Assert.assertTrue(request.getOutputOcrText()); + Assert.assertTrue(request.getOutputProcessedAudio()); + Assert.assertEquals(transcription, request.getOutputTranscription()); + Assert.assertEquals(outputDir, request.getOutputDirectory()); + Assert.assertEquals(Integer.valueOf(waitTime), request.getWaitTime()); + } + + @Test + public void testBuilderDefaults() { + DeidentifyFileRequest request = DeidentifyFileRequest.builder().build(); + Assert.assertFalse(request.getOutputProcessedImage()); + Assert.assertFalse(request.getOutputOcrText()); + Assert.assertFalse(request.getOutputProcessedAudio()); + Assert.assertNull(request.getOutputDirectory()); + Assert.assertNull(request.getWaitTime()); + } + + @Test + public void testBuilderWithFilePath() { + String filePath = "/tmp/test.txt"; + FileInput fileInput = FileInput.builder().filePath(filePath).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(Collections.singletonList(DetectEntities.DOB)) + .build(); + + Assert.assertEquals(filePath, request.getFileInput().getFilePath()); + Assert.assertNull(request.getFileInput().getFile()); + } + + @Test + public void testBuilderWithFileAndFilePath() { + File file = new File("test.txt"); + String filePath = "/tmp/test.txt"; + FileInput fileInput = FileInput.builder().file(file).filePath(filePath).build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(Collections.singletonList(DetectEntities.DOB)) + .build(); + + Assert.assertEquals(file, request.getFileInput().getFile()); + Assert.assertEquals(filePath, request.getFileInput().getFilePath()); + } + + @Test + public void testBuilderWithNullFileAndFilePath() { + FileInput fileInput = FileInput.builder().build(); + DeidentifyFileRequest request = DeidentifyFileRequest.builder() + .file(fileInput) + .entities(Collections.singletonList(DetectEntities.DOB)) + .build(); + + Assert.assertNull(request.getFileInput().getFile()); + Assert.assertNull(request.getFileInput().getFilePath()); + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java b/src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java new file mode 100644 index 00000000..89cf5114 --- /dev/null +++ b/src/test/java/com/skyflow/vault/detect/DeidentifyFileResponseTest.java @@ -0,0 +1,57 @@ +package com.skyflow.vault.detect; + +import com.skyflow.generated.rest.types.DeidentifyFileOutputProcessedFileType; +import org.junit.Assert; +import org.junit.Test; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; + +public class DeidentifyFileResponseTest { + + @Test + public void testAllGettersAndToString() { + File fileObject = new File("test-path.txt"); + String file = "test-path.txt"; + String type = "pdf"; + String extension = ".pdf"; + Integer wordCount = 100; + Integer charCount = 500; + Double sizeInKb = 123.45; + Double durationInSeconds = 12.3; + Integer pageCount = 5; + Integer slideCount = 0; + FileEntityInfo entityInfo = new FileEntityInfo("PERSON", DeidentifyFileOutputProcessedFileType.ENTITIES, "John Doe"); + java.util.List entities = Collections.singletonList(entityInfo); + String runId = "run-123"; + String status = "SUCCESS"; + FileInfo fileInfo = new FileInfo(fileObject); + + DeidentifyFileResponse response = new DeidentifyFileResponse( + fileInfo, file, type, extension, wordCount, charCount, sizeInKb, + durationInSeconds, pageCount, slideCount, entities, runId, status + ); + + Assert.assertEquals(type, response.getType()); + Assert.assertEquals(extension, response.getExtension()); + Assert.assertEquals(wordCount, response.getWordCount()); + Assert.assertEquals(charCount, response.getCharCount()); + Assert.assertEquals(sizeInKb, response.getSizeInKb()); + Assert.assertEquals(durationInSeconds, response.getDurationInSeconds()); + Assert.assertEquals(pageCount, response.getPageCount()); + Assert.assertEquals(slideCount, response.getSlideCount()); + Assert.assertEquals(entities, response.getEntities()); + Assert.assertEquals(runId, response.getRunId()); + Assert.assertEquals(status, response.getStatus()); + + // toString should return a JSON string containing all fields + String json = response.toString(); + Assert.assertTrue(json.contains(file)); + Assert.assertTrue(json.contains(type)); + Assert.assertTrue(json.contains(extension)); + Assert.assertTrue(json.contains(runId)); + Assert.assertTrue(json.contains(status)); + Assert.assertTrue(json.contains("PERSON")); + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/detect/DeidentifyTextTests.java b/src/test/java/com/skyflow/vault/detect/DeidentifyTextTests.java new file mode 100644 index 00000000..08cde4c3 --- /dev/null +++ b/src/test/java/com/skyflow/vault/detect/DeidentifyTextTests.java @@ -0,0 +1,217 @@ +package com.skyflow.vault.detect; + +import com.skyflow.enums.DetectEntities; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static com.skyflow.errors.ErrorMessage.InvalidTextInDeIdentify; + +public class DeidentifyTextTests { + + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + + private static final String text = "Sensitive data to deidentify"; + private static final List detectEntities = new ArrayList<>(); + private static final List allowRegexList = new ArrayList<>(); + private static final List restrictRegexList = new ArrayList<>(); + private static final TokenFormat tokenFormat = TokenFormat.builder() + .vaultToken(detectEntities) + .entityUniqueCounter(detectEntities) + .entityOnly(detectEntities) + .build(); + + private static Transformations transformations = null; + + + @BeforeClass + public static void setup() { + detectEntities.add(DetectEntities.NAME); + detectEntities.add(DetectEntities.DOB); + + allowRegexList.add("^[A-Za-z]+$"); + restrictRegexList.add("([0-9]{3}-[0-9]{2}-[0-9]{4})"); + + transformations = new Transformations( + new DateTransformation(20, 5, detectEntities) + ); + } + + + @Test + public void testValidInputInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .entities(detectEntities) + .allowRegexList(allowRegexList) + .restrictRegexList(restrictRegexList) + .tokenFormat(tokenFormat) + .transformations(transformations) + .build(); + + Validations.validateDeidentifyTextRequest(request); + Assert.assertEquals(detectEntities, request.getEntities()); + Assert.assertEquals(allowRegexList, request.getAllowRegexList()); + Assert.assertEquals(restrictRegexList, request.getRestrictRegexList()); + Assert.assertEquals(tokenFormat, request.getTokenFormat()); + Assert.assertEquals(transformations, request.getTransformations()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + + @Test + public void testNullTextInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder().text(null).build(); + Validations.validateDeidentifyTextRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(InvalidTextInDeIdentify.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyTextInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder().text("").build(); + Validations.validateDeidentifyTextRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(InvalidTextInDeIdentify.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyEntitiesInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .entities(new ArrayList<>()) + .build(); + Validations.validateDeidentifyTextRequest(request); + Assert.assertTrue(request.getEntities().isEmpty()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + + @Test + public void testNoEntitiesInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder().text("").build(); + Validations.validateDeidentifyTextRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + + @Test + public void testEmptyAllowRegexListInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .allowRegexList(new ArrayList<>()) + .build(); + Validations.validateDeidentifyTextRequest(request); + Assert.assertTrue(request.getAllowRegexList().isEmpty()); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + @Test + public void testEmptyRestrictRegexListInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .restrictRegexList(new ArrayList<>()) + .build(); + Validations.validateDeidentifyTextRequest(request); + Assert.assertTrue(request.getRestrictRegexList().isEmpty()); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + + @Test + public void testNullTokenFormatInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .entities(detectEntities) + .allowRegexList(allowRegexList) + .restrictRegexList(restrictRegexList) + .tokenFormat(null) + .build(); + Validations.validateDeidentifyTextRequest(request); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + @Test + public void testNoTransformationsInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .entities(detectEntities) + .allowRegexList(allowRegexList) + .restrictRegexList(restrictRegexList) + .tokenFormat(tokenFormat) + .build(); + Validations.validateDeidentifyTextRequest(request); + Assert.assertNull(request.getTransformations()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNullOrEmptyTransformationsInDeidentifyTextRequestValidations() { + try { + DeidentifyTextRequest request = DeidentifyTextRequest.builder() + .text(text) + .entities(detectEntities) + .allowRegexList(allowRegexList) + .restrictRegexList(restrictRegexList) + .tokenFormat(tokenFormat) + .transformations(null) + .build(); + Validations.validateDeidentifyTextRequest(request); + Assert.assertNull(request.getTransformations()); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + @Test + public void testDeidentifyResponse() { + try { + List entityInfos = new ArrayList<>(); + int wordCount = 5; + int charCount = 30; + DeidentifyTextResponse response = new DeidentifyTextResponse(text, entityInfos, wordCount, charCount); + Assert.assertEquals(text, response.getProcessedText()); + Assert.assertEquals(wordCount, response.getWordCount()); + Assert.assertEquals(charCount, response.getCharCount()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} diff --git a/src/test/java/com/skyflow/vault/detect/FileEntityInfoTest.java b/src/test/java/com/skyflow/vault/detect/FileEntityInfoTest.java new file mode 100644 index 00000000..e1f1e152 --- /dev/null +++ b/src/test/java/com/skyflow/vault/detect/FileEntityInfoTest.java @@ -0,0 +1,21 @@ +package com.skyflow.vault.detect; + +import com.skyflow.generated.rest.types.DeidentifyFileOutputProcessedFileType; +import org.junit.Assert; +import org.junit.Test; + +public class FileEntityInfoTest { + + @Test + public void testConstructorAndGetters() { + String file = "entity.pdf"; + DeidentifyFileOutputProcessedFileType type = DeidentifyFileOutputProcessedFileType.ENTITIES; + String extension = ".pdf"; + + FileEntityInfo info = new FileEntityInfo(file, type, extension); + + Assert.assertEquals(file, info.getFile()); + Assert.assertEquals(type.toString(), info.getType()); + Assert.assertEquals(extension, info.getExtension()); + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/detect/FileInfoTest.java b/src/test/java/com/skyflow/vault/detect/FileInfoTest.java new file mode 100644 index 00000000..29a81f6a --- /dev/null +++ b/src/test/java/com/skyflow/vault/detect/FileInfoTest.java @@ -0,0 +1,41 @@ +package com.skyflow.vault.detect; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +public class FileInfoTest { + + @Test + public void testFileInfoFields() throws IOException { + // Create a temp file + File tempFile = File.createTempFile("testfileinfo", ".txt"); + tempFile.deleteOnExit(); + + // Write some content to ensure size > 0 + FileWriter writer = new FileWriter(tempFile); + writer.write("Hello Skyflow!"); + writer.close(); + + FileInfo fileInfo = new FileInfo(tempFile); + + Assert.assertEquals(tempFile.getName(), fileInfo.getName()); + Assert.assertEquals(tempFile.length(), fileInfo.getSize()); + Assert.assertEquals("", fileInfo.getType()); + Assert.assertEquals(tempFile.lastModified(), fileInfo.getLastModified()); + } + + @Test + public void testFileInfoWithNonExistentFile() { + File fakeFile = new File("nonexistentfile.txt"); + FileInfo fileInfo = new FileInfo(fakeFile); + + Assert.assertEquals("nonexistentfile.txt", fileInfo.getName()); + Assert.assertEquals(0, fileInfo.getSize()); + Assert.assertEquals("", fileInfo.getType()); + Assert.assertEquals(0, fileInfo.getLastModified()); + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/detect/ReidentifyTextTests.java b/src/test/java/com/skyflow/vault/detect/ReidentifyTextTests.java new file mode 100644 index 00000000..e96a6422 --- /dev/null +++ b/src/test/java/com/skyflow/vault/detect/ReidentifyTextTests.java @@ -0,0 +1,149 @@ +package com.skyflow.vault.detect; + +import com.skyflow.enums.DetectEntities; +import com.skyflow.errors.ErrorCode; +import com.skyflow.errors.SkyflowException; +import com.skyflow.utils.validations.Validations; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static com.skyflow.errors.ErrorMessage.InvalidTextInReIdentify; + +public class ReidentifyTextTests { + + private static final String INVALID_EXCEPTION_THROWN = "Should not have thrown any exception"; + private static final String EXCEPTION_NOT_THROWN = "Should have thrown an exception"; + + private static final String text = "Sensitive data to reidentify"; + private static final List redactedEntities = new ArrayList<>(); + private static final List maskedEntities = new ArrayList<>(); + private static final List plainTextEntities = new ArrayList<>(); + + @BeforeClass + public static void setup() { + redactedEntities.add(DetectEntities.NAME); + redactedEntities.add(DetectEntities.DOB); + + maskedEntities.add(DetectEntities.USERNAME); + + plainTextEntities.add(DetectEntities.PHONE_NUMBER); + } + + @Test + public void testValidInputInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder() + .text(text) + .redactedEntities(redactedEntities) + .maskedEntities(maskedEntities) + .plainTextEntities(plainTextEntities) + .build(); + + Validations.validateReidentifyTextRequest(request); + Assert.assertEquals(text, request.getText()); + Assert.assertEquals(redactedEntities, request.getRedactedEntities()); + Assert.assertEquals(maskedEntities, request.getMaskedEntities()); + Assert.assertEquals(plainTextEntities, request.getPlainTextEntities()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testNoTextInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder().build(); + Validations.validateReidentifyTextRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + @Test + public void testNullTextInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder() + .text(null) + .build(); + Validations.validateReidentifyTextRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(InvalidTextInReIdentify.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyTextInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder() + .text("") + .build(); + Validations.validateReidentifyTextRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(InvalidTextInReIdentify.getMessage(), e.getMessage()); + } + } + + + @Test + public void testEmptyRedactedEntitiesInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder() + .text(text) + .redactedEntities(new ArrayList<>()) + .build(); + Validations.validateReidentifyTextRequest(request); + Assert.assertTrue(request.getRedactedEntities().isEmpty()); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + + @Test + public void testEmptyMaskedEntitiesInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder() + .text(text) + .maskedEntities(new ArrayList<>()) + .build(); + Validations.validateReidentifyTextRequest(request); + Assert.assertTrue(request.getMaskedEntities().isEmpty()); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + @Test + public void testEmptyPlainTextEntitiesInReidentifyTextRequestValidations() { + try { + ReidentifyTextRequest request = ReidentifyTextRequest.builder() + .text(text) + .plainTextEntities(new ArrayList<>()) + .build(); + Validations.validateReidentifyTextRequest(request); + Assert.assertTrue(request.getPlainTextEntities().isEmpty()); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + } + } + + + @Test + public void testReidentifyResponse() { + try { + ReidentifyTextResponse response = new ReidentifyTextResponse(text); + Assert.assertEquals(text, response.getProcessedText()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} \ No newline at end of file diff --git a/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java new file mode 100644 index 00000000..d417aeb7 --- /dev/null +++ b/src/test/java/com/skyflow/vault/tokens/DetokenizeTests.java @@ -0,0 +1,191 @@ +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.types.DetokenizeRecordResponseValueType; +import com.skyflow.generated.rest.types.V1DetokenizeRecordResponse; +import com.skyflow.utils.Constants; +import com.skyflow.utils.Utils; +import com.skyflow.utils.validations.Validations; +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 final String requestId = "95be08fc-4d13-4335-8b8d-24e85d53ed1d"; + private static ArrayList detokenizeData = null; + private static DetokenizeData maskedRedactionRecord = null; + private static DetokenizeData plainRedactionRecord = null; + + @BeforeClass + public static void setup() throws SkyflowException, NoSuchMethodException { + detokenizeData = new ArrayList<>(); + maskedRedactionRecord = new DetokenizeData("test_token_1", RedactionType.MASKED); + plainRedactionRecord = new DetokenizeData("test_token_2"); + } + + @Before + public void setupTest() { + detokenizeData.clear(); + } + + @Test + public void testValidInputInDetokenizeRequestValidations() { + try { + detokenizeData.add(maskedRedactionRecord); + DetokenizeRequest request = DetokenizeRequest.builder() + .detokenizeData(detokenizeData).continueOnError(false).downloadURL(true).build(); + Validations.validateDetokenizeRequest(request); + Assert.assertEquals(1, request.getDetokenizeData().size()); + Assert.assertEquals(RedactionType.MASKED.toString(), request.getDetokenizeData().get(0).getRedactionType().toString()); + Assert.assertFalse(request.getContinueOnError()); + Assert.assertTrue(request.getDownloadURL()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @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.InvalidDetokenizeData.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertFalse(request.getContinueOnError()); + Assert.assertFalse(request.getDownloadURL()); + } + } + + @Test + public void testEmptyTokensInDetokenizeRequestValidations() { + DetokenizeRequest request = DetokenizeRequest.builder().detokenizeData(detokenizeData).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.EmptyDetokenizeData.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertFalse(request.getContinueOnError()); + Assert.assertFalse(request.getDownloadURL()); + } + } + + @Test + public void testEmptyTokenInDetokenizeRequestValidations() { + DetokenizeData detokenizeDataRecord = new DetokenizeData(""); + detokenizeData.add(maskedRedactionRecord); + detokenizeData.add(detokenizeDataRecord); + + DetokenizeRequest request = DetokenizeRequest.builder().detokenizeData(detokenizeData).build(); + try { + Validations.validateDetokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyTokenInDetokenizeData.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertFalse(request.getContinueOnError()); + Assert.assertFalse(request.getDownloadURL()); + } + } + + @Test + public void testNullTokenInDetokenizeRequestValidations() { + DetokenizeData detokenizeDataRecord = new DetokenizeData(null); + detokenizeData.add(maskedRedactionRecord); + detokenizeData.add(detokenizeDataRecord); + + DetokenizeRequest request = DetokenizeRequest.builder().detokenizeData(detokenizeData).build(); + try { + Validations.validateDetokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals( + Utils.parameterizedString(ErrorMessage.EmptyTokenInDetokenizeData.getMessage(), Constants.SDK_PREFIX), + e.getMessage() + ); + Assert.assertFalse(request.getContinueOnError()); + Assert.assertFalse(request.getDownloadURL()); + } + } + + @Test + public void testRedactionAndContinueOnErrorInDetokenizeRequestValidations() { + detokenizeData.add(plainRedactionRecord); + + DetokenizeRequest request = DetokenizeRequest.builder(). + detokenizeData(detokenizeData).continueOnError(null).build(); + try { + Validations.validateDetokenizeRequest(request); + Assert.assertEquals(RedactionType.DEFAULT, request.getDetokenizeData().get(0).getRedactionType()); + Assert.assertFalse(request.getContinueOnError()); + Assert.assertFalse(request.getDownloadURL()); + } catch (SkyflowException e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } + + @Test + public void testDetokenizeResponse() { + try { + V1DetokenizeRecordResponse record1 = V1DetokenizeRecordResponse.builder() + .token("1234-5678-9012-3456") + .value("4111111111111111") + .valueType(DetokenizeRecordResponseValueType.STRING) + .build(); + DetokenizeRecordResponse field = new DetokenizeRecordResponse(record1); + + V1DetokenizeRecordResponse record2 = V1DetokenizeRecordResponse.builder() + .token("3456-7890-1234-5678") + .value("") + .error("Invalid token") + .build(); + + DetokenizeRecordResponse error = new DetokenizeRecordResponse(record2, requestId); + + 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 = "{\"detokenizedFields\":[{" + + "\"token\":\"1234-5678-9012-3456\",\"value\":\"4111111111111111\",\"type\":\"STRING\"}," + + "{\"token\":\"1234-5678-9012-3456\",\"value\":\"4111111111111111\",\"type\":\"STRING\"}]," + + "\"errors\":[{\"token\":\"3456-7890-1234-5678\",\"error\":\"Invalid token\",\"requestId\":\"" + requestId + "\"}," + + "{\"token\":\"3456-7890-1234-5678\",\"error\":\"Invalid token\",\"requestId\":\"" + requestId + "\"}]}"; + Assert.assertEquals(2, response.getDetokenizedFields().size()); + Assert.assertEquals(2, response.getErrors().size()); + Assert.assertEquals("1234-5678-9012-3456", response.getDetokenizedFields().get(0).getToken()); + Assert.assertEquals("4111111111111111", response.getDetokenizedFields().get(0).getValue()); + Assert.assertEquals("STRING", response.getDetokenizedFields().get(0).getType()); + Assert.assertEquals("Invalid token", response.getErrors().get(0).getError()); + Assert.assertEquals(requestId, response.getErrors().get(0).getRequestId()); + Assert.assertEquals(responseString, response.toString()); + } catch (Exception e) { + Assert.fail(INVALID_EXCEPTION_THROWN); + } + } +} 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..4c279fde --- /dev/null +++ b/src/test/java/com/skyflow/vault/tokens/TokenizeTests.java @@ -0,0 +1,169 @@ +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 testNullColumnValueInColumnValuesInTokenizeRequestValidations() { + try { + columnValue = ColumnValue.builder().value(null).columnGroup(group).build(); + columnValues.add(columnValue); + TokenizeRequest request = TokenizeRequest.builder().values(columnValues).build(); + Validations.validateTokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyValueInColumnValues.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyColumnValueInColumnValuesInTokenizeRequestValidations() { + try { + 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 testNullColumnGroupInColumnValuesInTokenizeRequestValidations() { + try { + columnValue = ColumnValue.builder().value(value).columnGroup(null).build(); + columnValues.add(columnValue); + TokenizeRequest request = TokenizeRequest.builder().values(columnValues).build(); + Validations.validateTokenizeRequest(request); + Assert.fail(EXCEPTION_NOT_THROWN); + } catch (SkyflowException e) { + Assert.assertEquals(ErrorCode.INVALID_INPUT.getCode(), e.getHttpCode()); + Assert.assertEquals(ErrorMessage.EmptyColumnGroupInColumnValue.getMessage(), e.getMessage()); + } + } + + @Test + public void testEmptyColumnGroupInColumnValuesInTokenizeRequestValidations() { + try { + 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 = "{\"tokens\":[" + + "{\"token\":\"1234-5678-9012-3456\"},{\"token\":\"5678-9012-3456-7890\"}]" + + ",\"errors\":null}"; + 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