From b5b3ce4dc55451d09515f4b185f331ceaf3f7b0b Mon Sep 17 00:00:00 2001 From: skyflow-vivek Date: Fri, 5 Sep 2025 21:14:50 +0530 Subject: [PATCH] SK-2283 Add README and Samples --- README.md | 2863 ++--------------- samples/pom.xml | 2 +- .../connection/InvokeConnectionExample.java | 101 - .../example/detect/DeidentifyFileExample.java | 114 - .../example/detect/DeidentifyTextExample.java | 142 - .../example/detect/GetDetectRunExample.java | 55 - .../BearerTokenExpiryExample.java | 86 - .../BearerTokenGenerationExample.java | 66 - ...rerTokenGenerationUsingThreadsExample.java | 72 - ...arerTokenGenerationWithContextExample.java | 61 - .../ScopedTokenGenerationExample.java | 66 - .../SignedTokenGenerationExample.java | 74 - .../example/vault/BulkDetokenizeAsync.java | 81 + .../com/example/vault/BulkDetokenizeSync.java | 74 + .../com/example/vault/BulkInsertAsync.java | 81 + .../com/example/vault/BulkInsertSync.java | 74 + .../com/example/vault/ClientOperations.java | 95 - .../com/example/vault/CredentialsOptions.java | 84 - .../java/com/example/vault/DeleteExample.java | 64 - .../com/example/vault/DetokenizeExample.java | 87 - .../java/com/example/vault/GetExample.java | 82 - .../java/com/example/vault/InsertExample.java | 99 - .../java/com/example/vault/QueryExample.java | 56 - .../com/example/vault/TokenizeExample.java | 63 - .../java/com/example/vault/UpdateExample.java | 91 - 25 files changed, 590 insertions(+), 4143 deletions(-) delete mode 100644 samples/src/main/java/com/example/connection/InvokeConnectionExample.java delete mode 100644 samples/src/main/java/com/example/detect/DeidentifyFileExample.java delete mode 100644 samples/src/main/java/com/example/detect/DeidentifyTextExample.java delete mode 100644 samples/src/main/java/com/example/detect/GetDetectRunExample.java delete mode 100644 samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java delete mode 100644 samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java delete mode 100644 samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java delete mode 100644 samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java delete mode 100644 samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java delete mode 100644 samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java create mode 100644 samples/src/main/java/com/example/vault/BulkDetokenizeAsync.java create mode 100644 samples/src/main/java/com/example/vault/BulkDetokenizeSync.java create mode 100644 samples/src/main/java/com/example/vault/BulkInsertAsync.java create mode 100644 samples/src/main/java/com/example/vault/BulkInsertSync.java delete mode 100644 samples/src/main/java/com/example/vault/ClientOperations.java delete mode 100644 samples/src/main/java/com/example/vault/CredentialsOptions.java delete mode 100644 samples/src/main/java/com/example/vault/DeleteExample.java delete mode 100644 samples/src/main/java/com/example/vault/DetokenizeExample.java delete mode 100644 samples/src/main/java/com/example/vault/GetExample.java delete mode 100644 samples/src/main/java/com/example/vault/InsertExample.java delete mode 100644 samples/src/main/java/com/example/vault/QueryExample.java delete mode 100644 samples/src/main/java/com/example/vault/TokenizeExample.java delete mode 100644 samples/src/main/java/com/example/vault/UpdateExample.java diff --git a/README.md b/README.md index 7c80d174..b4f73bab 100644 --- a/README.md +++ b/README.md @@ -15,35 +15,12 @@ The Skyflow Java SDK is designed to help with integrating Skyflow into a Java ba - [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) -- [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) + - [Bulk insert data into the vault](#bulk-insert-data-into-the-vault) + - [Bulk Detokenize](#bulk-detokenize) - [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) @@ -56,8 +33,7 @@ The Skyflow Java SDK is designed to help with integrating Skyflow into a Java ba # 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. +- Perform Vault API operations such as inserting, and detokenizing sensitive data with ease. # Install @@ -74,7 +50,7 @@ The Skyflow Java SDK is designed to help with integrating Skyflow into a Java ba Add this dependency to your project's `build.gradle` file: ``` -implementation 'com.skyflow:skyflow-java:2.0.0' +implementation 'com.skyflow:skyflow-java:3.0.0-beta.3' ``` ### Maven users @@ -85,277 +61,15 @@ Add this dependency to your project's `pom.xml` file: com.skyflow skyflow-java - 2.0.0 + 3.0.0-beta.3 ``` --- -# Migrate from v1 to v2 - -Below are the steps to migrate the java sdk from v1 to v2. - -### Authentication options - -In V2, we have introduced multiple authentication options. You can now provide credentials in the following ways: - -- Passing credentials in ENV. (`SKYFLOW_CREDENTIALS`) _(Recommended)_ -- API Key -- Path to your credentials JSON file -- Stringified JSON of your credentials -- Bearer token - -These options allow you to choose the authentication method that best suits your use case. - -**V1 (Old)** - -```java -static class DemoTokenProvider implements TokenProvider { - @Override - public String getBearerToken() throws Exception { - ResponseToken res = null; - try { - String filePath = ""; - res = Token.generateBearerToken(filePath); - } catch (SkyflowException e) { - e.printStackTrace(); - } - return res.getAccessToken(); - } -} -``` - -**V2 (New): Passing one of the following:** - -```java -// Option 1: API Key (Recommended) -Credentials skyflowCredentials = new Credentials(); -skyflowCredentials.setApiKey(""); // Replace with your actual API key - -// Option 2: Environment Variables (Recommended) -// Set SKYFLOW_CREDENTIALS in your environment - -// Option 3: Credentials File -skyflowCredentials.setPath(""); // Replace with the path to credentials file - -// Option 4: Stringified JSON -skyflowCredentials.setCredentialsString(""); // Replace with the credentials string - -// Option 5: Bearer Token -skyflowCredentials.setToken(""); // Replace with your actual authentication token. -``` - -Notes: - -- Use only ONE authentication method. -- API Key or environment variables are recommended for production use. -- Secure storage of credentials is essential. -- For overriding behavior and priority order of credentials, please refer to [Initialize the client](#initialize-the-client) section in [Quickstart](#quickstart). - ---- - -### Initializing the client - -In V2, we have introduced a builder design pattern for client initialization and added support for multi-vault. This allows you to configure multiple vaults during client initialization. In V2, the log level is tied to each individual client instance. During client initialization, you can pass the following parameters: - -- `vaultId` and `clusterId`: These values are derived from the vault ID & vault URL. -- `env`: Specify the environment (e.g., SANDBOX or PROD). -- `credentials`: The necessary authentication credentials. - -**V1 (Old)** - -```java -// DemoTokenProvider class is an implementation of the TokenProvider interface -DemoTokenProvider demoTokenProvider = new DemoTokenProvider(); -SkyflowConfiguration skyflowConfig = new SkyflowConfiguration("","", demoTokenProvider); -Skyflow skyflowClient = Skyflow.init(skyflowConfig); -``` - -**V2 (New)** - -```java -Credentials credentials = new Credentials(); -credentials.setPath(""); // Replace with the path to the credentials file - -// Configure the first vault (Blitz) -VaultConfig config = new VaultConfig(); -config.setVaultId(""); // Replace with the ID of the first vault -config.setClusterId(""); // Replace with the cluster ID of the first vault -config.setEnv(Env.DEV); // Set the environment (e.g., DEV, STAGE, PROD) -config.setCredentials(credentials); // Associate the credentials with the vault - -// Set up credentials for the Skyflow client -Credentials skyflowCredentials = new Credentials(); -skyflowCredentials.setPath(""); // Replace with the path to another credentials file - -// Create a Skyflow client and add vault configurations -Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs - .addVaultConfig(config) // Add the first vault configuration - .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials - .build(); -``` - -**Key Changes:** - -- `vaultUrl` replaced with `clusterId`. -- Added environment specification (`env`). -- Instance-specific log levels. - ---- - -### Request & response structure - -In V2, we have removed the use of JSON objects from a third-party package. Instead, we have transitioned to accepting native ArrayList and HashMap data structures and adopted the builder pattern for request creation. This request needs: - -- `table`: The name of the table. -- `values`: An array list of objects containing the data to be inserted. - -The response will be of type `InsertResponse` class, which contains `insertedFields` and `errors`. - -**V1 (Old):** Request building - -```java -JSONObject recordsJson = new JSONObject(); -JSONArray recordsArrayJson = new JSONArray(); - -JSONObject recordJson = new JSONObject(); -recordJson.put("table", "cards"); - -JSONObject fieldsJson = new JSONObject(); -fields.put("cardNumber", "41111111111"); -fields.put("cvv", "123"); - -recordJson.put("fields", fieldsJson); -recordsArrayJson.add(record); -recordsJson.put("records", recordsArrayJson); -try { - JSONObject insertResponse = skyflowClient.insert(records); - System.out.println(insertResponse); -} catch (SkyflowException exception) { - System.out.println(exception); -} -``` - -**V2 (New):** Request building - -```java -ArrayList> values = new ArrayList<>(); -HashMap value = new HashMap<>(); -value.put("", ""); // Replace with column name and value -value.put("", ""); // Replace with another column name and value -values.add(values); - -ArrayList> tokens = new ArrayList<>(); -HashMap token = new HashMap<>(); -token.put("", ""); // Replace with the token for COLUMN_NAME_2 -tokens.add(token); - -InsertRequest insertRequest = InsertRequest.builder() - .table("") // Replace with the table name - .continueOnError(true) // Continue inserting even if some records fail - .tokenMode(TokenMode.ENABLE) // Enable BYOT for token validation - .values(values) // Data to insert - .tokens(tokens) // Provide tokens for BYOT columns - .returnTokens(true) // Return tokens along with the response - .build(); -``` - -**V1 (Old):** Response structure - -```json -{ - "records": [ - { - "table": "cards", - "fields": { - "skyflow_id": "16419435-aa63-4823-aae7-19c6a2d6a19f", - "cardNumber": "f3907186-e7e2-466f-91e5-48e12c2bcbc1", - "cvv": "1989cb56-63da-4482-a2df-1f74cd0dd1a5" - } - } - ] -} -``` - -**V2 (New):** Response structure - -```json -{ - "insertedFields": [ - { - "card_number": "5484-7829-1702-9110", - "request_index": "0", - "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", - "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b" - } - ], - "errors": [] -} -``` - ---- - -### Request options - -In V2, with the introduction of the builder design pattern has made handling optional fields in Java more efficient and straightforward. - -**V1 (Old)** - -```java -InsertOptions insertOptions = new InsertOptions(true); -``` - -**V2 (New)** - -```java -InsertRequest upsertRequest = new InsertRequest.builder() - .table("") // Replace with the table name - .continueOnError(false) // Stop inserting if any record fails - .tokenMode(TokenMode.DISABLE) // Disable BYOT - .values(values) // Data to insert - .returnTokens(false) // Do not return tokens - .upsert("") // Replace with the column name used for upsert logic - .build(); -``` - ---- - -### Error structure - -In V2, we have enriched the error details to provide better debugging capabilities. -The error response now includes: - -- `httpStatus`: The HTTP status code. -- `grpcCode`: The gRPC code associated with the error. -- `details` & `message`: A detailed description of the error. -- `requestId`: A unique request identifier for easier debugging. - -**V1 (Old):** Error structure - -```json -{ - "code": "", - "description": "" -} -``` - -**V2 (New):** Error structure - -```js -{ - "httpStatus": "", - "grpcCode": , - "httpCode": , - "message": "", - "requestId": "", - "details": ["
"] -} -``` - # 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. +Get started quickly with the essential steps: authenticate and initialize the client. This section provides a minimal setup to help you integrate the SDK efficiently. ### Authenticate @@ -394,7 +108,7 @@ import com.skyflow.enums.LogLevel; import com.skyflow.errors.SkyflowException; /** - * Example program to initialize the Skyflow client with various configurations. + * Example program to initialize the Skyflow client with a vault configuration. * The Skyflow client facilitates secure interactions with the Skyflow vault, * such as securely managing sensitive data. */ @@ -408,16 +122,16 @@ public class InitSkyflowClient { // - 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. + Credentials credentials = new Credentials(); + credentials.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. + VaultConfig config = new VaultConfig(); + primaryConfig.setVaultId(""); // Replace with your 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. + primaryConfig.setCredentials(credentials); // Attach the 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. @@ -433,46 +147,18 @@ public class InitSkyflowClient { 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. + // Step 5: 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. + .addVaultConfig(config) // Add the vault configuration. .addSkyflowCredentials(skyflowCredentials) // Add JSON-formatted credentials if applicable. .build(); // The Skyflow client is now fully initialized. // Use the `skyflowClient` object to perform secure operations such as: // - Inserting data - // - Retrieving data - // - Deleting data + // - Detokenizing data // within the configured Skyflow vaults. } } @@ -484,86 +170,13 @@ Notes: - 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 - -To insert data into your vault, use the `insert` method. The `InsertRequest` class creates an insert request, which includes the values to be inserted as a list of records. Below is a simple example to get started. For advanced options, check out [Insert data into the vault](#insert-data-into-the-vault-1) section. - -```java -import com.skyflow.errors.SkyflowException; -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 - } - } -} -``` - -Skyflow returns tokens for the record that was just inserted. - -```json -{ - "insertedFields": [ - { - "card_number": "5484-7829-1702-9110", - "request_index": "0", - "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", - "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b" - } - ], - "errors": [] -} -``` - # Vault -The [Vault](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault) module performs operations on the vault, including inserting records, detokenizing tokens, and retrieving tokens associated with a `skyflow_id`. +The [Vault](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault) module performs operations on the vault, including inserting records and detokenizing tokens. -## Insert data into the vault +## Bulk insert data into the vault -Apart from using the `insert` method to insert data into your vault covered in [Quickstart](#quickstart), you can also specify options in `InsertRequest`, such as returning tokenized data, upserting records, or continuing the operation in case of errors. +To insert data into your vault, use the `bulkinsert` or `bulkInsertAsync` methods. The `InsertRequest` class creates an insert request, which includes the values to be inserted as a list of records. ### Construct an insert request @@ -582,7 +195,8 @@ import java.util.HashMap; public class InsertSchema { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client + // Step 1: Prepare the data to be inserted into the Skyflow vault ArrayList> insertData = new ArrayList<>(); @@ -606,9 +220,8 @@ public class InsertSchema { .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 + // Step 3: Use the Skyflow client to perform the sync bulk insert operation + InsertResponse insertResponse = skyflowClient.vault().bulkInsert(insertRequest); // Print the response from the insert operation System.out.println("Insert Response: " + insertResponse); @@ -621,95 +234,107 @@ public class InsertSchema { } ``` -### Insert call [example](https://github.com/skyflowapi/skyflow-java/blob/SK-1893-update-readme-for-v2/samples/src/main/java/com/example/vault/InsertExample.java) with `continueOnError` option +### An [example](https://github.com/skyflowapi/skyflow-java/blob/v3/samples/src/main/java/com/example/vault/BulkInsertSync.java) of a sync bulkInsert call -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. +The `bulkInsert` operation operation will insert the data synchronously into the vault. ```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. + * Example program to demonstrate how to perform a synchronous bulk insert operation using the Skyflow Java SDK. + * The process involves: + * 1. Setting up credentials and vault configuration + * 2. Creating multiple records to be inserted + * 3. Building and executing a bulk insert request + * 4. Handling the insert response or any potential errors */ -public class InsertExample { +public class BulkInsertSync { 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 + // Initialize Skyflow client + + // Step 1: Prepare the data to be inserted into the Skyflow vault ArrayList> insertData = new ArrayList<>(); - // Step 2: Create the first record with card number and cardholder name + // Create the first record with field names and their respective values 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) + insertRecord1.put("name", "John doe"); // Replace with actual field name and value + insertRecord1.put("email", "john.doe@example.com"); // Replace with actual field name and value - // Step 3: Create the second record with card number and cardholder name + // Create the second record with field names and their respective values 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) + insertRecord2.put("name", "Jane doe"); // Replace with actual field name and value + insertRecord2.put("email", "jane.doe@example.com"); // Replace with actual field name and value - // Step 4: Add the records to the insertData list + // Add the records to the list of data to be inserted insertData.add(insertRecord1); insertData.add(insertRecord2); - // Step 5: Build the InsertRequest object with the data records to insert + // Step 2: Build an InsertRequest object with the table name and the data 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); + .table("table1") // 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 sync bulk insert operation + InsertResponse insertResponse = skyflowClient.vault().bulkInsert(insertRequest); + + // Print the response from the insert operation + System.out.println("Insert Response: " + 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 + // 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 } } } ``` -Sample response: +Skyflow returns tokens and data for the records that were just inserted. ```json { - "insertedFields": [ + "summary": { + "totalRecords": 2, + "totalInserted": 2, + "totalFailed": 0 + }, + "sucess": [ { - "card_number": "5484-7829-1702-9110", - "request_index": "0", + "index": 0, "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", - "cardholder_name": "b2308e2a-c1f5-469b-97b7-1f193159399b" - } - ], - "errors": [ + "tokens": { + "name": [{ "token": "token_name", "tokenGroupName": "deterministic_string" }], + "email": [ + { + "token": "augn0@xebggri.lmp", + "tokenGroupName": "nondeterministic_string" + } + ] + }, + "data": { "email": "john.doe@example.com", "name": "john doe" } + }, { - "request_index": "1", - "error": "Insert failed. Column card_numbe is invalid. Specify a valid column." - } - ] + "index": 1, + "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd3", + "tokens": { + "name": [{ "token": "token_name", "tokenGroupName": "deterministic_string" }], + "email": [ + { + "token": "buhn0@xebggrj.lmt", + "tokenGroupName": "nondeterministic_string" + } + ] + }, + "data": { "email": "jane.doe@example.com", "name": "Jane doe" } + }, + ], + "errors": [] } ``` -### Insert call example with `upsert` option +### An [example](https://github.com/skyflowapi/skyflow-java/blob/v3/samples/src/main/java/com/example/vault/BulkInsertAsync.java) of an async bulkInsert call -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. +The `bulkInsertAsync` operation operation will insert the data asynchronously into the vault. ```java import com.skyflow.errors.SkyflowException; @@ -720,42 +345,49 @@ 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. + * Example program to demonstrate how to perform an asynchronous bulk insert operation using the Skyflow Java SDK. + * The process involves: + * 1. Setting up credentials and vault configuration + * 2. Creating multiple records to be inserted + * 3. Building and executing an async bulk insert request + * 4. Handling the insert response or errors using CompletableFuture */ -public class UpsertExample { +public class BulkInsertAsync { 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 1: Prepare the data to be inserted into the Skyflow vault + ArrayList> insertData = 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 + // Create the first record with field names and their respective values + HashMap insertRecord1 = new HashMap<>(); + insertRecord1.put("name", "John doe"); // Replace with actual field name and value + insertRecord1.put("email", "john.doe@example.com"); // Replace with actual field name and value + + // Create the second record with field names and their respective values + HashMap insertRecord2 = new HashMap<>(); + insertRecord2.put("name", "Jane doe"); // Replace with actual field name and value + insertRecord2.put("email", "jane.doe@example.com"); // Replace with actual field name and value - // Step 3: Add the record to the upsertData list - upsertData.add(upsertRecord); + // Add the records to the list of data to be inserted + insertData.add(insertRecord1); + insertData.add(insertRecord2); - // Step 4: Build the InsertRequest object with the upsertData + // Step 2: Build an InsertRequest object with the table name and the data to insert 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); + .table("table1") // Replace with the actual table name in your Skyflow vault + .values(insertData) // Attach the data to be inserted + .build(); + + // Step 3: Perform the async bulk insert operation using the Skyflow client + CompletableFuture future = skyflowClient.vault().bulkInsertAsync(insertRequest); + // Add success and error callbacks + future.thenAccept(response -> { + System.out.println("Async bulk insert resolved with response:\t" + response); + }).exceptionally(throwable -> { + System.err.println("Async bulk insert rejected with error:\t" + throwable.getMessage()); + throw new CompletionException(throwable); + }); } catch (SkyflowException e) { // Step 7: Handle any exceptions that may occur during the insert/upsert operation System.out.println("Error occurred: "); @@ -765,23 +397,55 @@ public class UpsertExample { } ``` -Skyflow returns tokens, with `upsert` support, for the record you just inserted. +Skyflow returns tokens and data for the records you just inserted. ```json { - "insertedFields": [ + "summary": { + "totalRecords": 2, + "totalInserted": 2, + "totalFailed": 0 + }, + "sucess": [ { - "skyflowId": "9fac9201-7b8a-4446-93f8-5244e1213bd1", - "cardholder_name": "73ce45ce-20fd-490e-9310-c1d4f603ee83" - } + "index": 0, + "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd1", + "tokens": { + "name": [{ "token": "token_name", "tokenGroupName": "deterministic_string" }], + "email": [ + { + "token": "augn0@xebggri.lmp", + "tokenGroupName": "nondeterministic_string" + } + ] + }, + "data": { "email": "john.doe@example.com", "name": "john doe" } + }, + { + "index": 1, + "skyflow_id": "9fac9201-7b8a-4446-93f8-5244e1213bd3", + "tokens": { + "name": [{ "token": "token_name", "tokenGroupName": "deterministic_string" }], + "email": [ + { + "token": "buhn0@xebggrj.lmt", + "tokenGroupName": "nondeterministic_string" + } + ] + }, + "data": { "email": "jane.doe@example.com", "name": "Jane doe" } + }, ], "errors": [] } ``` -## Detokenize +## Bulk detokenize -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. +To retrieve tokens from your vault, use the `bulkDetokenize` or `bulkDetokenizeAsync` methods. You can specify how the data should be redacted based on token groups. The `DetokenizeRequest` has two main components: + +- `tokens`: List of token strings to detokenize +- `tokenGroupRedactions`: List of redaction rules for specific token groups ### Construct a detokenize request @@ -800,23 +464,28 @@ import java.util.ArrayList; public class DetokenizeSchema { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client // Step 1: Initialize a list of tokens to be detokenized (replace with actual tokens) ArrayList tokens = new ArrayList<>(); tokens.add(""); // Replace with your actual token value tokens.add(""); // Replace with your actual token value tokens.add(""); // Replace with your actual token value - // Step 2: Create the DetokenizeRequest object with the tokens and redaction type + TokenGroupRedactions tokenGroupRedaction = TokenGroupRedactions.builder() + .tokenGroupName("") + .redaction("") + .build(); + List tokenGroupRedactions = new ArrayList<>(); + tokenGroupRedactions.add(tokenGroupRedaction); + + // Step 2: Create the DetokenizeRequest object with the tokens and token group redactions DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() - .tokens(tokens) // Provide the list of tokens to be detokenized - .continueOnError(true) // Continue even if one token cannot be detokenized - .redactionType(RedactionType.PLAIN_TEXT) // Specify how the detokenized data should be returned (plain text) - .build(); // Build the detokenization request + .tokens(tokens) // Provide the list of tokens to be detokenized + .tokenGroupredactions(tokenGroupRedactions) // Provide a list of token grpup redactions + .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 + DetokenizeResponse detokenizeResponse = skyflowClient.vault().bulkDetokenize(detokenizeRequest); // Step 4: Print the detokenization response, which contains the detokenized data System.out.println(detokenizeResponse); @@ -829,50 +498,50 @@ public class DetokenizeSchema { } ``` -Notes: - -- `redactionType` defaults to [`RedactionType.PLAIN_TEXT`](#redaction-types). -- `continueOnError` defaults to `true`. - -### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/DetokenizeExample.java) of a detokenize call: +### An [example](https://github.com/skyflowapi/skyflow-java/blob/v3/samples/src/main/java/com/example/vault/BulkDetokenizeSync.java) of a sync bulkDetokenize call: ```java -import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.tokens.DetokenizeRequest; -import com.skyflow.vault.tokens.DetokenizeResponse; +import com.skyflow.vault.data.DetokenizeRequest; +import com.skyflow.vault.data.DetokenizeResponse; +import com.skyflow.vault.data.TokenGroupRedactions; import java.util.ArrayList; +import java.util.List; /** - * 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. + * This sample demonstrates how to perform a synchronous bulk detokenize operation using the Skyflow Java SDK. + * The process involves: + * 1. Setting up credentials and vault configuration + * 2. Creating a list of tokens to detokenize + * 3. Configuring token group redactions + * 4. Building and executing a bulk detokenize request + * 5. Handling the detokenize response or any potential errors */ -public class DetokenizeExample { +public class BulkDetokenizeSync { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client // Step 1: Initialize a list of tokens to be detokenized (replace with actual token values) ArrayList tokens = new ArrayList<>(); - tokens.add("9738-1683-0486-1480"); // Replace with your actual token value - tokens.add("6184-6357-8409-6668"); // Replace with your actual token value - tokens.add("4914-9088-2814-3840"); // Replace with your actual token value + tokens.add("b8eea77a-47e1-4d67-a560-fd395cabc82f"); // Replace with your actual token value + tokens.add("6ffb412b-a79d"); // Replace with your actual token value - // Step 2: Create the DetokenizeRequest object with the tokens and redaction type + TokenGroupRedactions tokenGroupRedaction = TokenGroupRedactions.builder() + .tokenGroupName("deterministic_regex") + .redaction("MASKED") + .build(); + List tokenGroupRedactions = new ArrayList<>(); + tokenGroupRedactions.add(tokenGroupRedaction); + + // Step 2: Create the DetokenizeRequest object with the tokens and token group redactions DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() - .tokens(tokens) // Provide the list of tokens to be detokenized - .continueOnError(false) // Stop the process if any token cannot be detokenized - .redactionType(RedactionType.PLAIN_TEXT) // Specify how the detokenized data should be returned (plain text) - .build(); // Build the detokenization request + .tokens(tokens) // Provide the list of tokens to be detokenized + .tokenGroupredactions(tokenGroupRedactions) // Provide a list of token grpup redactions + .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 3: Call the Skyflow vault to bulk detokenize the provided tokens synchronously + DetokenizeResponse detokenizeResponse = skyflowClient.vault().bulkDetokenizeAsync(detokenizeRequest); // Step 4: Print the detokenization response, which contains the detokenized data System.out.println(detokenizeResponse); @@ -889,65 +558,80 @@ Sample response: ```json { - "detokenizedFields": [{ - "token": "9738-1683-0486-1480", - "value": "4111111111111115", - "type": "STRING", - }, { - "token": "6184-6357-8409-6668", - "value": "4111111111111119", - "type": "STRING", - }, { - "token": "4914-9088-2814-3840", - "value": "4111111111111118", - "type": "STRING", - }] - "errors": [] + "summary": { + "total_tokens": 2, + "total_detokenized": 2, + "total_failed": 0, + }, + "success": [ + { + "index": 0, + "token": "b8eea77a-47e1-4d67-a560-fd395cabc82f", + "value": "xxxx@skyflow.com", + "tokenGroupName": "nondeterministic_regex", + "metadata": { + "skyflowID": "5ddc71a6-3bdb-47e4-9723-259452946349", + "tableName": "table1" + } + }, + ], + "errors": [ + { + "index": 1, + "code": 404, + "error": "Detokenize failed. Token 6ffb412b-a79d is invalid. Specify a valid token.", + } + ] } - ``` -### An example of a detokenize call with `continueOnError` option: +### An [example]() of an async bulkDetokenize call + ```java -import com.skyflow.enums.RedactionType; import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.tokens.DetokenizeRequest; -import com.skyflow.vault.tokens.DetokenizeResponse; +import com.skyflow.vault.data.DetokenizeRequest; +import com.skyflow.vault.data.DetokenizeResponse; +import com.skyflow.vault.data.TokenGroupRedactions; import java.util.ArrayList; +import java.util.List; /** - * 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. + * This sample demonstrates how to perform an asynchronous bulk detokenize operation using the Skyflow Java SDK. + * The process involves: + * 1. Setting up credentials and vault configuration + * 2. Creating a list of tokens to detokenize + * 3. Configuring token group redactions + * 4. Building and executing a bulk detokenize request + * 5. Handling the detokenize response or errors using CompletableFuture */ -public class DetokenizeExample { +public class BulkDetokenizeAsync { public static void main(String[] args) { try { - // Initialize Skyflow client + // Initialize Skyflow client // Step 1: Initialize a list of tokens to be detokenized (replace with actual token values) ArrayList tokens = new ArrayList<>(); - tokens.add("9738-1683-0486-1480"); // Example token value 1 - tokens.add("6184-6357-8409-6668"); // Example token value 2 - tokens.add("4914-9088-2814-384"); // Example token value 3 + tokens.add("b8eea77a-47e1-4d67-a560-fd395cabc82f"); // Replace with your actual token value + tokens.add("6ffb412b-a79d"); // Replace with your actual token value + + TokenGroupRedactions tokenGroupRedaction = TokenGroupRedactions.builder() + .tokenGroupName("deterministic_string") + .redaction("MASKED") + .build(); + List tokenGroupRedactions = new ArrayList<>(); + tokenGroupRedactions.add(tokenGroupRedaction); // Step 2: Create the DetokenizeRequest object with the tokens and redaction type DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() - .tokens(tokens) // Provide the list of tokens to detokenize - .continueOnError(true) // Continue even if some tokens cannot be detokenized - .redactionType(RedactionType.PLAIN_TEXT) // Specify the format for the detokenized data (plain text) - .build(); // Build the detokenization request + .tokens(tokens) // Provide the list of tokens to be detokenized + .tokenGroupredactions(tokenGroupRedactions) // Provide a list of token grpup redactions + .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 3: Call the Skyflow vault to bulk detokenize the provided tokens asynchronously + DetokenizeResponse detokenizeResponse = skyflowClient.vault().bulkDetokenizeAsync(detokenizeRequest); - // Step 4: Print the detokenization response, which contains the detokenized data or errors + // 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 @@ -962,2022 +646,33 @@ 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. - -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 - -```java -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 - - // Add the created column values to the list - columnValues.add(columnValue1); - columnValues.add(columnValue2); - - // Step 3: Build the TokenizeRequest with the column values - TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); - - // Step 4: Call the Skyflow vault to tokenize the sensitive data - TokenizeResponse tokenizeResponse = skyflowClient.vault("").tokenize(tokenizeRequest); - // Replace with your actual Skyflow vault ID - - // Step 5: Print the tokenization response, which contains the generated tokens or errors - System.out.println(tokenizeResponse); - } catch (SkyflowException e) { - // Step 6: Handle any errors that occur during the tokenization process - System.out.println("Error occurred: "); - e.printStackTrace(); // Print the exception for debugging purposes - } - } -} -``` - -### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/TokenizeExample.java) of Tokenize call: - -```java -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<>(); - - // Step 2: Create a column value for the sensitive data (e.g., card number with its column group) - ColumnValue columnValue = ColumnValue.builder() - .value("4111111111111111") // Replace with the actual sensitive data (e.g., card number) - .columnGroup("card_number_cg") // Replace with the actual column group name - .build(); - - // Add the created column value to the list - columnValues.add(columnValue); - - // Step 3: Build the TokenizeRequest with the column value - TokenizeRequest tokenizeRequest = TokenizeRequest.builder().values(columnValues).build(); - - // Step 4: Call the Skyflow vault to tokenize the sensitive data - TokenizeResponse tokenizeResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").tokenize(tokenizeRequest); - // Replace "9f27764a10f7946fe56b3258e117" with your actual Skyflow vault ID - - // Step 5: Print the tokenization response, which contains the generated token or any errors - System.out.println(tokenizeResponse); - } catch (SkyflowException e) { - // Step 6: Handle any errors that occur during the tokenization process - System.out.println("Error occurred: "); - e.printStackTrace(); // Print the exception for debugging purposes - } - } -} -``` - -Sample response: - -```json -{ - "tokens": [5479-4229-4622-1393] -} -``` - -## 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 - -```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 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 - } - } -} -``` - -### 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 -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 - - } 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 - } - } -} -``` - -Sample response: - -```json -{ - "data": [ - { - "card_number": "4555555555555553", - "email": "john.doe@gmail.com", - "name": "john doe", - "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6" - }, - { - "card_number": "4555555555555559", - "email": "jane.doe@gmail.com", - "name": "jane doe", - "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a" - } - ], - "errors": [] -} -``` - -### Get tokens - -Return tokens for records. Ideal for securely processing sensitive data while maintaining data privacy. - -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/getExample.java) of get call to retrieve tokens using Skyflow IDs: - -```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 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 - - } 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 - } - } -} -``` - -Sample response: - -```json -{ - "data": [ + "summary": { + "total_tokens": 2, + "total_detokenized": 2, + "total_failed": 0, + }, + "success": [ { - "card_number": "3998-2139-0328-0697", - "email": "c9a6c9555060@82c092e7.bd52", - "name": "82c092e7-74c0-4e60-bd52-c9a6c9555060", - "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6" + "index": 0, + "token": "b8eea77a-47e1-4d67-a560-fd395cabc82f", + "value": "xxxx@skyflow.com", + "tokenGroupName": "nondeterministic_regex", + "metadata": { + "skyflowID": "5ddc71a6-3bdb-47e4-9723-259452946349", + "tableName": "table1" + } }, - { - "card_number": "3562-0140-8820-7499", - "email": "6174366e2bc6@59f82e89.93fc", - "name": "59f82e89-138e-4f9b-93fc-6174366e2bc6", - "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a" - } ], - "errors": [] -} -``` - -### Get By column name and column values - -Retrieve records by unique column values. Ideal for querying data without knowing Skyflow IDs, using alternate unique identifiers. - -An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/GetExample.java) of get call to retrieve data using column name and column values: - -```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 - } - } -} -``` - -Sample response: - -```json -{ - "data": [ - { - "card_number": "4555555555555553", - "email": "john.doe@gmail.com", - "name": "john doe", - "skyflow_id": "a581d205-1969-4350-acbe-a2a13eb871a6" - }, + "errors": [ { - "card_number": "4555555555555559", - "email": "jane.doe@gmail.com", - "name": "jane doe", - "skyflow_id": "5ff887c3-b334-4294-9acc-70e78ae5164a" - } - ], - "errors": [] -} -``` - -### Redaction types - -Redaction types determine how sensitive data is displayed when retrieved from the vault. - -#### **Available Redaction Types** - -- `DEFAULT`: Applies the vault-configured default redaction setting. -- `REDACTED`: Completely removes sensitive data from view. -- `MASKED`: Partially obscures sensitive information. -- `PLAIN_TEXT`: Displays the full, unmasked data. - -#### **Choosing the Right Redaction Type** - -- Use `REDACTED` for scenarios requiring maximum data protection to prevent exposure of sensitive information. -- Use `MASKED` to provide partial visibility of sensitive data for less critical use cases. -- Use `PLAIN_TEXT` for internal, authorized access where full data visibility is necessary. - -## Update - -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. - -### Construct an update request - -```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 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 - - } 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 - } - } -} -``` - -### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/UpdateExample.java) of update call - -```java -import com.skyflow.enums.TokenMode; -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" -} -``` - -- When `returnTokens` is set to `false` - -```json -{ - "skyflowId": "5b699e2c-4301-4f9f-bcff-0a8fd3057413" -} -``` - -## 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: - -### Construct a delete request - -```java -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 - } - } -} -``` - -### An [example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/vault/DeleteExample.java) of delete call: - -```java -import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.data.DeleteRequest; -import com.skyflow.vault.data.DeleteResponse; - -import java.util.ArrayList; - -/** - * 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 - - } 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: - -```json -{ - "deletedIds": [ - "9cbf66df-6357-48f3-b77b-0f1acbb69280", - "ea74bef4-f27e-46fe-b6a0-a28e91b4477b", - "47700796-6d3b-4b54-9153-3973e281cafb" - ] -} -``` - -## 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.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'" - - // Step 2: Create a QueryRequest with the specified SQL query - QueryRequest queryRequest = QueryRequest.builder() - .query(query) // SQL query to execute - .build(); - - // Step 3: Execute the query request on the specified Skyflow vault - QueryResponse queryResponse = skyflowClient.vault("").query(queryRequest); // Replace with your actual Vault ID - System.out.println(queryResponse); // Print the response containing the query results - - } catch (SkyflowException e) { - // Step 4: Handle any exceptions that occur during the query execution - System.out.println("Error occurred: "); - 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/QueryExample.java) of query call - -```java -import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.data.QueryRequest; -import com.skyflow.vault.data.QueryResponse; - -/** - * This example demonstrates how to execute a SQL query on a Skyflow vault to retrieve data. - * - * 1. Initializes the Skyflow client with the Vault ID. - * 2. Constructs a query request with a specified SQL query. - * 3. Executes the query against the Skyflow vault. - * 4. Prints the response from the query execution. - */ -public class QueryExample { - public static void main(String[] args) { - try { - // Initialize Skyflow client - // 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'"; - - // Step 2: Create a QueryRequest with the SQL query - QueryRequest queryRequest = QueryRequest.builder() - .query(query) // SQL query to execute - .build(); - - // Step 3: Execute the query request on the specified Skyflow vault - QueryResponse queryResponse = skyflowClient.vault("9f27764a10f7946fe56b3258e117").query(queryRequest); // Vault ID: 9f27764a10f7946fe56b3258e117 - System.out.println(queryResponse); // Print the query response (contains query results) - - } catch (SkyflowException e) { - // Step 4: Handle any exceptions that occur during the query execution - System.out.println("Error occurred: "); - e.printStackTrace(); // Print the exception stack trace for debugging - } - } -} -``` - -Sample response: - -```json -{ - "fields": [ - { - "card_number": "XXXXXXXXXXXX1112", - "name": "S***ar", - "skyflow_id": "3ea3861-x107-40w8-la98-106sp08ea83f", - "tokenizedData": null + "index": 1, + "code": 404, + "error": "Detokenize failed. Token 6ffb412b-a79d is invalid. Specify a valid token.", } ] } ``` -# Detect -Skyflow Detect enables you to deidentify and reidentify sensitive data in text and files, supporting advanced privacy-preserving workflows. The Detect API supports the following operations: - -## Deidentify Text -To deidentify text, use the `deidentifyText` method. The `DeidentifyTextRequest` class creates a deidentify text request, which includes the text to be deidentified. Additionally, you can provide optional parameters using the `DeidentifyTextOptions` class. - -### Construct an deidentify text request - -```java -import com.skyflow.enums.DetectEntities; -import com.skyflow.vault.detect.DateTransformation; -import com.skyflow.vault.detect.DeidentifyTextRequest; -import com.skyflow.vault.detect.TokenFormat; -import com.skyflow.vault.detect.Transformations; -import com.skyflow.vault.detect.DeidentifyTextResponse; - -import java.util.ArrayList; -import java.util.List; - -/** - * This example demonstrate to build deidentify text request. - */ -public class DeidentifyTextSchema { - - public static void main(String[] args) { - - // Step 1: Initialise the Skyflow client by configuring the credentials & vault config. - - // Step 2: Configure the options for deidentify text - - // Replace with the entity you want to detect - List detectEntitiesList = new ArrayList<>(); - detectEntitiesList.add(DetectEntities.SSN); - - // Replace with the entity you want to detect with vault token - List vaultTokenList = new ArrayList<>(); - vaultTokenList.add(DetectEntities.CREDIT_CARD); - - // Replace with the entity you want to detect with entity only - List entityOnlyList = new ArrayList<>(); - entityOnlyList.add(DetectEntities.SSN); - - // Replace with the entity you want to detect with entity unique counter - List entityUniqueCounterList = new ArrayList<>(); - entityUniqueCounterList.add(DetectEntities.SSN); - - // Replace with the regex patterns you want to allow during deidentification - List allowRegexList = new ArrayList<>(); - allowRegexList.add(""); - - // Replace with the regex patterns you want to restrict during deidentification - List restrictRegexList = new ArrayList<>(); - restrictRegexList.add("YOUR_RESTRICT_REGEX_LIST"); - - // Configure Token Format - TokenFormat tokenFormat = TokenFormat.builder() - .vaultToken(vaultTokenList) - .entityOnly(entityOnlyList) - .entityUniqueCounter(entityUniqueCounterList) - .build(); - - // Configure Transformation - List detectEntitiesTransformationList = new ArrayList<>(); - detectEntitiesTransformationList.add(DetectEntities.DOB); // Replace with the entity you want to transform - - DateTransformation dateTransformation = new DateTransformation(20, 5, detectEntitiesTransformationList); - Transformations transformations = new Transformations(dateTransformation); - - // Step 3: Create a deidentify text request for the vault - DeidentifyTextRequest deidentifyTextRequest = DeidentifyTextRequest.builder() - .text("") // Replace with the text you want to deidentify - .entities(detectEntitiesList) - .allowRegexList(allowRegexList) - .restrictRegexList(restrictRegexList) - .tokenFormat(tokenFormat) - .transformations(transformations) - .build(); - - // Step 4: Use the Skyflow client to perform the deidentifyText operation - // Replace with your actual vault ID - DeidentifyTextResponse deidentifyTextResponse = skyflowClient.detect("").deidentifyText(deidentifyTextRequest); - - // Step 5: Print the response - System.out.println("Deidentify text Response: " + deidentifyTextResponse); - } -} - -``` - -## An [example](https://github.com/skyflowapi/skyflow-java/blob/beta-release/25.6.2/samples/src/main/java/com/example/detect/DeidentifyTextExample.java) of deidentify text: -```java -import java.util.ArrayList; -import java.util.List; - -import com.skyflow.enums.DetectEntities; -import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.detect.DateTransformation; -import com.skyflow.vault.detect.DeidentifyTextRequest; -import com.skyflow.vault.detect.DeidentifyTextResponse; -import com.skyflow.vault.detect.TokenFormat; -import com.skyflow.vault.detect.Transformations; - -/** - * Skyflow Deidentify Text Example - *

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

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

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

- * This example demonstrates how to: - * 1. Configure credentials - * 2. Set up vault configuration - * 3. Create a get detect run request - * 4. Call getDetectRun to poll for file processing results - * 5. Handle response and errors - */ -public class GetDetectRunExample { - public static void main(String[] args) throws SkyflowException { - // Step 1: Initialise the Skyflow client by configuring the credentials & vault config. - try { - - // Step 2: Create a get detect run request - GetDetectRunRequest getDetectRunRequest = GetDetectRunRequest.builder() - .runId("e0038196-4a20-422b-bad7-e0477117f9bb") // Replace with the runId from deidentifyFile call - .build(); - - // Step 3: Call getDetectRun to poll for file processing results - // Replace `9f27764a10f7946fe56b3258e117` with the acutal vault id - DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect("9f27764a10f7946fe56b3258e117").getDetectRun(getDetectRunRequest); - System.out.println("Get Detect Run Response: " + deidentifyFileResponse); - } catch (SkyflowException e) { - System.err.println("Error occurred during get detect run: "); - e.printStackTrace(); - } - } -} -``` - -Sample Response: - -```json -{ - "file": "bmFtZTogW05BTET0JfMV0K", - "type": "redacted_file", - "extension": "txt", - "wordCount": 11, - "charCount": 61, - "sizeInKb": 0.0, - "entities": [ - { - "file": "gW05BTUVfMV0gCmNhcmQ0K", - "type": "entities", - "extension": "json" - } - ], - "runId": "e0038196-4a20-422b-bad7-e0477117f9bb", - "status": "success" -} - -``` - -# Connections - -Skyflow Connections is a gateway service that uses tokenization to securely send and receive data between your systems and first- or third-party services. The [connections](https://github.com/skyflowapi/skyflow-java/tree/main/src/main/java/com/skyflow/vault/connection) module invokes both inbound and/or outbound connections. - -- **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/v2/src/main/java/com/skyflow/serviceaccount/util) Java module generates service account tokens using a service account credentials file, which is provided when a service account is created. The tokens generated by this module are valid for 60 minutes and can be used to make API calls to the [Data](https://docs.skyflow.com/record/) and [Management](https://docs.skyflow.com/management/) APIs, depending on the permissions assigned to the service account. - -The `BearerToken` utility class generates bearer tokens using a credentials JSON file. Alternatively, you can pass the credentials as a string. - -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java): - -```java -/** - * Example program to generate a Bearer Token using Skyflow's BearerToken utility. - * The token can be generated in two ways: - * 1. Using the file path to a credentials.json file. - * 2. Using the JSON content of the credentials file as a string. - */ -public class BearerTokenGenerationExample { - public static void main(String[] args) { - // Variable to store the generated token - String token = null; - - // Example 1: Generate Bearer Token using a credentials.json file - try { - // Specify the full file path to the credentials.json file - String filePath = ""; - - // Check if the token is either not initialized or has expired - if (Token.isExpired(token)) { - // Create a BearerToken object using the credentials file - BearerToken bearerToken = BearerToken.builder() - .setCredentials(new File(filePath)) // Set credentials from the file path - .build(); - - // Generate a new Bearer Token - token = bearerToken.getBearerToken(); - } - - // Print the generated Bearer Token to the console - System.out.println("Generated Bearer Token (from file): " + token); - } catch (SkyflowException e) { - // Handle any exceptions encountered during the token generation process - e.printStackTrace(); - } - - // Example 2: Generate Bearer Token using the credentials JSON as a string - try { - // Provide the credentials JSON content as a string - String fileContents = ""; - - // Check if the token is either not initialized or has expired - if (Token.isExpired(token)) { - // Create a BearerToken object using the credentials string - BearerToken bearerToken = BearerToken.builder() - .setCredentials(fileContents) // Set credentials from the string - .build(); - - // Generate a new Bearer Token - token = bearerToken.getBearerToken(); - } - - // Print the generated Bearer Token to the console - System.out.println("Generated Bearer Token (from string): " + token); - } catch (SkyflowException e) { - // Handle any exceptions encountered during the token generation process - e.printStackTrace(); - } - } -} -``` - -## Generate bearer tokens with context - -**Context-aware authorization** embeds context values into a bearer token during its generation and so you can reference those values in your policies. This enables more flexible access controls, such as helping you track end-user identity when making API calls using service accounts, and facilitates using signed data tokens during detokenization. . - -A service account with the `context_id` identifier generates bearer tokens containing context information, represented as a JWT claim in a Skyflow-generated bearer token. Tokens generated from such service accounts include a `context_identifier` claim, are valid for 60 minutes, and can be used to make API calls to the Data and Management APIs, depending on the service account's permissions. - -[Example](https://github.com/skyflowapi/skyflow-java/blob/main/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java): - -```java -import com.skyflow.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/v2/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java): - -```java -package com.example.serviceaccount; - -import com.skyflow.Skyflow; -import com.skyflow.config.Credentials; -import com.skyflow.config.VaultConfig; -import com.skyflow.enums.Env; -import com.skyflow.enums.LogLevel; -import com.skyflow.enums.RedactionType; -import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.tokens.DetokenizeRequest; -import com.skyflow.vault.tokens.DetokenizeResponse; -import io.github.cdimascio.dotenv.Dotenv; -import java.util.ArrayList; - -/** - * This example demonstrates how to configure and use the Skyflow SDK - * to detokenize sensitive data stored in a Skyflow vault. - * It includes setting up credentials, configuring the vault, and - * making a detokenization request. The code also implements a retry - * mechanism to handle unauthorized access errors (HTTP 401). - */ -public class DetokenizeExample { - public static void main(String[] args) { - try { - // Setting up credentials for accessing the Skyflow vault - Credentials vaultCredentials = new Credentials(); - vaultCredentials.setCredentialsString(""); - - // Configuring the Skyflow vault with necessary details - VaultConfig vaultConfig = new VaultConfig(); - vaultConfig.setVaultId(""); // Vault ID - vaultConfig.setClusterId(""); // Cluster ID - vaultConfig.setEnv(Env.PROD); // Environment (e.g., DEV, PROD) - vaultConfig.setCredentials(vaultCredentials); // Setting credentials - - // Creating a Skyflow client instance with the configured vault - Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.ERROR) // Setting log level to ERROR - .addVaultConfig(vaultConfig) // Adding vault configuration - .build(); - - // Attempting to detokenize data using the Skyflow client - try { - detokenizeData(skyflowClient); - } catch (SkyflowException e) { - // Retry detokenization if the error is due to unauthorized access (HTTP 401) - if (e.getHttpCode() == 401) { - detokenizeData(skyflowClient); - } else { - // Rethrow the exception for other error codes - throw e; - } - } - } catch (SkyflowException e) { - // Handling any exceptions that occur during the process - System.out.println("An error occurred: " + e.getMessage()); - } - } - - /** - * Method to detokenize data using the Skyflow client. - * It sends a detokenization request with a list of tokens and prints the response. - * - * @param skyflowClient The Skyflow client instance used for detokenization. - * @throws SkyflowException If an error occurs during the detokenization process. - */ - public static void detokenizeData(Skyflow skyflowClient) throws SkyflowException { - // Creating a list of tokens to be detokenized - ArrayList tokenList = new ArrayList<>(); - tokenList.add(""); // First token - tokenList.add(""); // Second token - - // Building a detokenization request with the token list and configuration - DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() - .tokens(tokenList) // Adding tokens to the request - .continueOnError(false) // Stop on error - .redactionType(RedactionType.PLAIN_TEXT) // Redaction type (e.g., PLAIN_TEXT) - .build(); - - // Sending the detokenization request and receiving the response - DetokenizeResponse detokenizeResponse = skyflowClient.vault().detokenize(detokenizeRequest); - - // Printing the detokenized response - System.out.println(detokenizeResponse); - } -} -``` - # Logging The SDK provides logging with Java's built-in logging library. By default, the SDK's logging level is set to `LogLevel.ERROR`. This can be changed using the `setLogLevel(logLevel)` method, as shown below: @@ -3058,4 +753,4 @@ public class ChangeLogLevel { # 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. \ No newline at end of file diff --git a/samples/pom.xml b/samples/pom.xml index c48ba302..96f921ee 100644 --- a/samples/pom.xml +++ b/samples/pom.xml @@ -18,7 +18,7 @@ com.skyflow skyflow-java - 1.15.0 + 3.0.0-beta.3 diff --git a/samples/src/main/java/com/example/connection/InvokeConnectionExample.java b/samples/src/main/java/com/example/connection/InvokeConnectionExample.java deleted file mode 100644 index b2e80924..00000000 --- a/samples/src/main/java/com/example/connection/InvokeConnectionExample.java +++ /dev/null @@ -1,101 +0,0 @@ -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 deleted file mode 100644 index 7f573d33..00000000 --- a/samples/src/main/java/com/example/detect/DeidentifyFileExample.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.example.detect; - -import java.io.File; - -import com.skyflow.Skyflow; -import com.skyflow.config.Credentials; -import com.skyflow.config.VaultConfig; -import com.skyflow.enums.Env; -import com.skyflow.enums.LogLevel; -import com.skyflow.enums.MaskingMethod; -import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.detect.DeidentifyFileRequest; -import com.skyflow.vault.detect.DeidentifyFileResponse; -import com.skyflow.vault.detect.FileInput; - -/** - * Skyflow Deidentify File Example - *

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

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

- * This example demonstrates how to: - * 1. Configure credentials - * 2. Set up vault configuration - * 3. Create a get detect run request - * 4. Call getDetectRun to poll for file processing results - * 5. Handle response and errors - */ -public class GetDetectRunExample { - public static void main(String[] args) throws SkyflowException { - // Step 1: Configure credentials - Credentials credentials = new Credentials(); - credentials.setPath(""); // Replace with the path to the credentials file - - // Step 2: Configure the vault config - VaultConfig vaultConfig = new VaultConfig(); - vaultConfig.setVaultId(""); // Replace with the ID of the vault - vaultConfig.setClusterId(""); // Replace with the cluster ID of the vault - vaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) - vaultConfig.setCredentials(credentials); // Associate the credentials with the vault - - // Step 3: Create a Skyflow client - Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.DEBUG) // Enable debugging for detailed logs - .addVaultConfig(vaultConfig) // Add the vault configuration - .build(); - - try { - // Step 4: Create a get detect run request - GetDetectRunRequest getDetectRunRequest = GetDetectRunRequest.builder() - .runId("") // Replace with the runId from deidentifyFile call - .build(); - - // Step 5: Call getDetectRun to poll for file processing results - DeidentifyFileResponse deidentifyFileResponse = skyflowClient.detect(vaultConfig.getVaultId()).getDetectRun(getDetectRunRequest); - System.out.println("Get Detect Run Response: " + deidentifyFileResponse); - } catch (SkyflowException e) { - System.err.println("Error occurred during get detect run: "); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java deleted file mode 100644 index 1f56296d..00000000 --- a/samples/src/main/java/com/example/serviceaccount/BearerTokenExpiryExample.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.example.serviceaccount; - -import com.skyflow.Skyflow; -import com.skyflow.config.Credentials; -import com.skyflow.config.VaultConfig; -import com.skyflow.enums.Env; -import com.skyflow.enums.LogLevel; -import com.skyflow.enums.RedactionType; -import com.skyflow.errors.SkyflowException; -import com.skyflow.vault.tokens.DetokenizeRequest; -import com.skyflow.vault.tokens.DetokenizeResponse; -import io.github.cdimascio.dotenv.Dotenv; -import java.util.ArrayList; - -/** - * This example demonstrates how to configure and use the Skyflow SDK - * to detokenize sensitive data stored in a Skyflow vault. - * It includes setting up credentials, configuring the vault, and - * making a detokenization request. The code also implements a retry - * mechanism to handle unauthorized access errors (HTTP 401). - */ -public class BearerTokenExpiryExample { - public static void main(String[] args) { - try { - // Setting up credentials for accessing the Skyflow vault - Credentials vaultCredentials = new Credentials(); - vaultCredentials.setCredentialsString(""); - - // Configuring the Skyflow vault with necessary details - VaultConfig vaultConfig = new VaultConfig(); - vaultConfig.setVaultId(""); // Vault ID - vaultConfig.setClusterId(""); // Cluster ID - vaultConfig.setEnv(Env.PROD); // Environment (e.g., DEV, PROD) - vaultConfig.setCredentials(vaultCredentials); // Setting credentials - - // Creating a Skyflow client instance with the configured vault - Skyflow skyflowClient = Skyflow.builder() - .setLogLevel(LogLevel.ERROR) // Setting log level to ERROR - .addVaultConfig(vaultConfig) // Adding vault configuration - .build(); - - // Attempting to detokenize data using the Skyflow client - try { - detokenizeData(skyflowClient); - } catch (SkyflowException e) { - // Retry detokenization if the error is due to unauthorized access (HTTP 401) - if (e.getHttpCode() == 401) { - detokenizeData(skyflowClient); - } else { - // Rethrow the exception for other error codes - throw e; - } - } - } catch (SkyflowException e) { - // Handling any exceptions that occur during the process - System.out.println("An error occurred: " + e.getMessage()); - } - } - - /** - * Method to detokenize data using the Skyflow client. - * It sends a detokenization request with a list of tokens and prints the response. - * - * @param skyflowClient The Skyflow client instance used for detokenization. - * @throws SkyflowException If an error occurs during the detokenization process. - */ - public static void detokenizeData(Skyflow skyflowClient) throws SkyflowException { - // Creating a list of tokens to be detokenized - ArrayList tokenList = new ArrayList<>(); - tokenList.add(""); // First token - tokenList.add(""); // Second token - - // Building a detokenization request with the token list and configuration - DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() - .tokens(tokenList) // Adding tokens to the request - .continueOnError(false) // Stop on error - .redactionType(RedactionType.PLAIN_TEXT) // Redaction type (e.g., PLAIN_TEXT) - .build(); - - // Sending the detokenization request and receiving the response - DetokenizeResponse detokenizeResponse = skyflowClient.vault().detokenize(detokenizeRequest); - - // Printing the detokenized response - System.out.println(detokenizeResponse); - } -} diff --git a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java b/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java deleted file mode 100644 index c4578545..00000000 --- a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationExample.java +++ /dev/null @@ -1,66 +0,0 @@ -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 deleted file mode 100644 index 30d8f9ba..00000000 --- a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationUsingThreadsExample.java +++ /dev/null @@ -1,72 +0,0 @@ -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 deleted file mode 100644 index 3ed9e267..00000000 --- a/samples/src/main/java/com/example/serviceaccount/BearerTokenGenerationWithContextExample.java +++ /dev/null @@ -1,61 +0,0 @@ -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 deleted file mode 100644 index 3cba8bd5..00000000 --- a/samples/src/main/java/com/example/serviceaccount/ScopedTokenGenerationExample.java +++ /dev/null @@ -1,66 +0,0 @@ -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 deleted file mode 100644 index 98f552f3..00000000 --- a/samples/src/main/java/com/example/serviceaccount/SignedTokenGenerationExample.java +++ /dev/null @@ -1,74 +0,0 @@ -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/BulkDetokenizeAsync.java b/samples/src/main/java/com/example/vault/BulkDetokenizeAsync.java new file mode 100644 index 00000000..9673ab81 --- /dev/null +++ b/samples/src/main/java/com/example/vault/BulkDetokenizeAsync.java @@ -0,0 +1,81 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.errors.SkyflowException; +import com.skyflow.vault.data.DetokenizeRequest; +import com.skyflow.vault.data.DetokenizeResponse; +import com.skyflow.vault.data.TokenGroupRedactions; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; + +/** + * This sample demonstrates how to perform an asynchronous bulk detokenize operation using the Skyflow Java SDK. + * The process involves: + * 1. Setting up credentials and vault configuration + * 2. Creating a list of tokens to detokenize + * 3. Configuring token group redactions + * 4. Building and executing an async bulk detokenize request + * 5. Handling the detokenize response or errors using CompletableFuture + */ +public class BulkDetokenizeAsync { + + public static void main(String[] args) { + try { + // Step 1: Initialize credentials using credentials string + String credentialsString = ""; + Credentials credentials = new Credentials(); + credentials.setCredentialsString(credentialsString); + + // Step 2: Configure the vault with required parameters + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); + vaultConfig.setClusterId(""); + vaultConfig.setEnv(Env.PROD); + vaultConfig.setCredentials(credentials); + + // Step 3: Create Skyflow client instance with error logging + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .build(); + + // Step 4: Prepare list of tokens to detokenize + ArrayList tokens = new ArrayList<>(); + tokens.add(""); + tokens.add(""); + + // Step 5: Configure token group redactions + TokenGroupRedactions tokenGroupRedaction = TokenGroupRedactions.builder() + .tokenGroupName("") + .redaction("") + .build(); + List tokenGroupRedactions = new ArrayList<>(); + tokenGroupRedactions.add(tokenGroupRedaction); + + // Step 6: Build the detokenize request + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .tokens(tokens) + .tokenGroupRedactions(tokenGroupRedactions) + .build(); + + // Step 7: Execute the async bulk detokenize operation and handle response using callbacks + CompletableFuture future = skyflowClient.vault().bulkDetokenizeAsync(detokenizeRequest); + future.thenAccept(response -> { + System.out.println("Async bulk detokenize resolved with response:\t" + response); + }).exceptionally(throwable -> { + System.err.println("Async bulk detokenize rejected with error:\t" + throwable.getMessage()); + throw new CompletionException(throwable); + }); + } catch (SkyflowException e) { + // Step 8: Handle any synchronous errors that occur during setup + System.err.println("Error in Skyflow operations: " + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/samples/src/main/java/com/example/vault/BulkDetokenizeSync.java b/samples/src/main/java/com/example/vault/BulkDetokenizeSync.java new file mode 100644 index 00000000..dbd3dee4 --- /dev/null +++ b/samples/src/main/java/com/example/vault/BulkDetokenizeSync.java @@ -0,0 +1,74 @@ +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.DetokenizeRequest; +import com.skyflow.vault.data.DetokenizeResponse; +import com.skyflow.vault.data.TokenGroupRedactions; + +import java.util.ArrayList; +import java.util.List; + +/** + * This sample demonstrates how to perform a synchronous bulk detokenize operation using the Skyflow Java SDK. + * The process involves: + * 1. Setting up credentials and vault configuration + * 2. Creating a list of tokens to detokenize + * 3. Configuring token group redactions + * 4. Building and executing a bulk detokenize request + * 5. Handling the detokenize response or any potential errors + */ +public class BulkDetokenizeSync { + + public static void main(String[] args) { + try { + // Step 1: Initialize credentials using credentials string + String credentialsString = ""; + Credentials credentials = new Credentials(); + credentials.setCredentialsString(credentialsString); + + // Step 2: Configure the vault with required parameters + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); + vaultConfig.setClusterId(""); + vaultConfig.setEnv(Env.PROD); + vaultConfig.setCredentials(credentials); + + // Step 3: Create Skyflow client instance with error logging + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .build(); + + // Step 4: Prepare list of tokens to detokenize + ArrayList tokens = new ArrayList<>(); + tokens.add(""); + tokens.add(""); + + // Step 5: Configure token group redactions + TokenGroupRedactions tokenGroupRedaction = TokenGroupRedactions.builder() + .tokenGroupName("") + .redaction("") + .build(); + List tokenGroupRedactions = new ArrayList<>(); + tokenGroupRedactions.add(tokenGroupRedaction); + + // Step 6: Build the detokenize request + DetokenizeRequest detokenizeRequest = DetokenizeRequest.builder() + .tokens(tokens) + .tokenGroupRedactions(tokenGroupRedactions) + .build(); + + // Step 7: Execute the bulk detokenize operation and print the response + DetokenizeResponse detokenizeResponse = skyflowClient.vault().bulkDetokenize(detokenizeRequest); + System.out.println(detokenizeResponse); + } catch (SkyflowException e) { + // Step 8: Handle any errors that occur during the process + System.err.println("Error in Skyflow operations: " + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/samples/src/main/java/com/example/vault/BulkInsertAsync.java b/samples/src/main/java/com/example/vault/BulkInsertAsync.java new file mode 100644 index 00000000..30e675c7 --- /dev/null +++ b/samples/src/main/java/com/example/vault/BulkInsertAsync.java @@ -0,0 +1,81 @@ +package com.example.vault; + +import com.skyflow.Skyflow; +import com.skyflow.config.Credentials; +import com.skyflow.config.VaultConfig; +import com.skyflow.enums.Env; +import com.skyflow.enums.LogLevel; +import com.skyflow.vault.data.InsertRequest; +import com.skyflow.vault.data.InsertResponse; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; + +/** + * This sample demonstrates how to perform an asynchronous bulk insert operation using the Skyflow Java SDK. + * The process involves: + * 1. Setting up credentials and vault configuration + * 2. Creating multiple records to be inserted + * 3. Building and executing an async bulk insert request + * 4. Handling the insert response or errors using CompletableFuture + */ +public class BulkInsertAsync { + + public static void main(String[] args) { + try { + // Step 1: Initialize credentials with the path to your service account key file + String filePath = ""; + Credentials credentials = new Credentials(); + credentials.setPath(filePath); + + // Step 2: Configure the vault with required parameters + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); + vaultConfig.setClusterId(""); + vaultConfig.setEnv(Env.PROD); + vaultConfig.setCredentials(credentials); + + // Step 3: Create Skyflow client instance with error logging + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .build(); + + // Step 4: Prepare first record for insertion + HashMap record1 = new HashMap<>(); + record1.put("", ""); + record1.put("", ""); + + // Step 5: Prepare second record for insertion + HashMap record2 = new HashMap<>(); + record2.put("", ""); + record2.put("", ""); + + // Step 6: Combine records into a single list + ArrayList> values = new ArrayList<>(); + values.add(record1); + values.add(record2); + + // Step 7: Build the insert request with table name and values + InsertRequest request = InsertRequest.builder() + .table("") + .values(values) + .build(); + + // Step 8: Execute the async bulk insert operation and handle response using callbacks + CompletableFuture future = skyflowClient.vault().bulkInsertAsync(request); + // Add success and error callbacks + future.thenAccept(response -> { + System.out.println("Async bulk insert resolved with response:\t" + response); + }).exceptionally(throwable -> { + System.err.println("Async bulk insert rejected with error:\t" + throwable.getMessage()); + throw new CompletionException(throwable); + }); + } catch (Exception e) { + // Step 9: Handle any synchronous errors that occur during setup + System.err.println("Error in Skyflow operations:\t" + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/samples/src/main/java/com/example/vault/BulkInsertSync.java b/samples/src/main/java/com/example/vault/BulkInsertSync.java new file mode 100644 index 00000000..ab27e8c1 --- /dev/null +++ b/samples/src/main/java/com/example/vault/BulkInsertSync.java @@ -0,0 +1,74 @@ +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.InsertRequest; +import com.skyflow.vault.data.InsertResponse; + +import java.util.ArrayList; +import java.util.HashMap; + +/** + * This sample demonstrates how to perform a synchronous bulk insert operation using the Skyflow Java SDK. + * The process involves: + * 1. Setting up credentials and vault configuration + * 2. Creating multiple records to be inserted + * 3. Building and executing a bulk insert request + * 4. Handling the insert response or any potential errors + */ +public class BulkInsertSync { + + public static void main(String[] args) { + try { + // Step 1: Initialize credentials with the path to your service account key file + String filePath = ""; + Credentials credentials = new Credentials(); + credentials.setPath(filePath); + + // Step 2: Configure the vault with required parameters + VaultConfig vaultConfig = new VaultConfig(); + vaultConfig.setVaultId(""); + vaultConfig.setClusterId(""); + vaultConfig.setEnv(Env.PROD); + vaultConfig.setCredentials(credentials); + + // Step 3: Create Skyflow client instance with error logging + Skyflow skyflowClient = Skyflow.builder() + .setLogLevel(LogLevel.ERROR) + .addVaultConfig(vaultConfig) + .build(); + + // Step 4: Prepare first record for insertion + HashMap record1 = new HashMap<>(); + record1.put("", ""); + record1.put("", ""); + + // Step 5: Prepare second record for insertion + HashMap record2 = new HashMap<>(); + record2.put("", ""); + record2.put("", ""); + + // Step 6: Combine records into a single list + ArrayList> values = new ArrayList<>(); + values.add(record1); + values.add(record2); + + // Step 7: Build the insert request with table name and values + InsertRequest request = InsertRequest.builder() + .table("") + .values(values) + .build(); + + // Step 8: Execute the bulk insert operation and print the response + InsertResponse response = skyflowClient.vault().bulkInsert(request); + System.out.println(response); + } catch (SkyflowException e) { + // Step 9: Handle any errors that occur during the process + System.err.println("Error in Skyflow operations: " + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/samples/src/main/java/com/example/vault/ClientOperations.java b/samples/src/main/java/com/example/vault/ClientOperations.java deleted file mode 100644 index 7931db34..00000000 --- a/samples/src/main/java/com/example/vault/ClientOperations.java +++ /dev/null @@ -1,95 +0,0 @@ -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 deleted file mode 100644 index 8a3ebc6a..00000000 --- a/samples/src/main/java/com/example/vault/CredentialsOptions.java +++ /dev/null @@ -1,84 +0,0 @@ -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 deleted file mode 100644 index 9fe41f61..00000000 --- a/samples/src/main/java/com/example/vault/DeleteExample.java +++ /dev/null @@ -1,64 +0,0 @@ -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 first vault - VaultConfig primaryVaultConfig = new VaultConfig(); - primaryVaultConfig.setVaultId(""); // Replace with the ID of the first vault - primaryVaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault - primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) - primaryVaultConfig.setCredentials(credentials); // Associate the credentials with the vault - - // Step 3: 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(primaryVaultConfig) // Add the first vault configuration - .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials - .build(); - - // Step 5: Delete a record from the first 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 deleted file mode 100644 index b5d87d49..00000000 --- a/samples/src/main/java/com/example/vault/DetokenizeExample.java +++ /dev/null @@ -1,87 +0,0 @@ -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.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 first vault - VaultConfig primaryVaultConfig = new VaultConfig(); - primaryVaultConfig.setVaultId(""); // Replace with the ID of the first vault - primaryVaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault - primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) - primaryVaultConfig.setCredentials(credentials); // Associate the credentials with the vault - - // Step 3: 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(primaryVaultConfig) // Add the first vault configuration - .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials - .build(); - - // Step 5: Detokenize tokens from the first 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 the tokens to detokenize with specified redaction types - .continueOnError(true) // Continue processing even if an error occurs for some tokens - .build(); - - DetokenizeResponse detokenizeResponse1 = skyflowClient.vault().detokenize(detokenizeRequest1); // Perform detokenization - System.out.println("Detokenize Response (Vault 1): " + detokenizeResponse1); - } catch (SkyflowException e) { - System.out.println("Error during detokenization in Vault 1:"); - e.printStackTrace(); - } - - // Example 2: Detokenize tokens from the second vault - try { - ArrayList detokenizeData2 = new ArrayList<>(); - DetokenizeData detokenizeDataRecord3 = new DetokenizeData("", RedactionType.DEFAULT); // Replace with a token to detokenize - DetokenizeData detokenizeDataRecord4 = new DetokenizeData(""); // Replace with another token to detokenize - detokenizeData2.add(detokenizeDataRecord3); - detokenizeData2.add(detokenizeDataRecord4); - - DetokenizeRequest detokenizeRequest2 = DetokenizeRequest.builder() - .detokenizeData(detokenizeData2) // Specify the tokens to detokenize with specified redaction types - .continueOnError(false) // Stop processing on the first error - .downloadURL(true) // Specify whether to return URLs for file data type - .build(); - - DetokenizeResponse detokenizeResponse2 = skyflowClient.vault("").detokenize(detokenizeRequest2); // Perform detokenization - System.out.println("Detokenize Response (Vault 2): " + detokenizeResponse2); - } catch (SkyflowException e) { - System.out.println("Error during detokenization in Vault: " + e); - } - } -} diff --git a/samples/src/main/java/com/example/vault/GetExample.java b/samples/src/main/java/com/example/vault/GetExample.java deleted file mode 100644 index 6d300752..00000000 --- a/samples/src/main/java/com/example/vault/GetExample.java +++ /dev/null @@ -1,82 +0,0 @@ -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 first vault - VaultConfig primaryVaultConfig = new VaultConfig(); - primaryVaultConfig.setVaultId(""); // Replace with the ID of the first vault - primaryVaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault - primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) - primaryVaultConfig.setCredentials(credentials); // Associate the credentials with the vault - - // Step 3: 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(primaryVaultConfig) // Add the first vault configuration - .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials - .build(); - - // Example 1: Fetch records by Skyflow IDs from the first vault - try { - ArrayList ids = new ArrayList<>(); - ids.add(""); // Replace with the Skyflow ID to fetch the record - - GetRequest getByIdRequest = GetRequest.builder() - .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 second vault - try { - ArrayList columnValues = new ArrayList<>(); - columnValues.add(""); // Replace with the column value to fetch the record - - GetRequest getByColumnRequest = GetRequest.builder() - .table("") // Replace with the table name - .columnName("") // Replace with the column name - .columnValues(columnValues) // Specify the list of column values - .redactionType(RedactionType.PLAIN_TEXT) // Fetch the data in plain text format - .build(); - - GetResponse getByColumnResponse = skyflowClient.vault().get(getByColumnRequest); // Fetch 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 deleted file mode 100644 index 25610b2b..00000000 --- a/samples/src/main/java/com/example/vault/InsertExample.java +++ /dev/null @@ -1,99 +0,0 @@ -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 first vault - VaultConfig primaryVaultConfig = new VaultConfig(); - primaryVaultConfig.setVaultId(""); // Replace with the first vault ID - primaryVaultConfig.setClusterId(""); // Replace with the first vault cluster ID - primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, SANDBOX) - primaryVaultConfig.setCredentials(credentials); // Associate credentials with the vault - - // Step 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(primaryVaultConfig) // Add the vault configuration - .addSkyflowCredentials(skyflowCredentials) // Add general Skyflow credentials - .build(); - - // Example 1: Insert records into the first 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 first 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 deleted file mode 100644 index bde5c697..00000000 --- a/samples/src/main/java/com/example/vault/QueryExample.java +++ /dev/null @@ -1,56 +0,0 @@ -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 deleted file mode 100644 index 2c390be8..00000000 --- a/samples/src/main/java/com/example/vault/TokenizeExample.java +++ /dev/null @@ -1,63 +0,0 @@ -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 deleted file mode 100644 index d5c5ed02..00000000 --- a/samples/src/main/java/com/example/vault/UpdateExample.java +++ /dev/null @@ -1,91 +0,0 @@ -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 first vault - VaultConfig primaryVaultConfig = new VaultConfig(); - primaryVaultConfig.setVaultId(""); // Replace with the ID of the first vault - primaryVaultConfig.setClusterId(""); // Replace with the cluster ID of the first vault - primaryVaultConfig.setEnv(Env.PROD); // Set the environment (e.g., DEV, STAGE, PROD) - primaryVaultConfig.setCredentials(credentials); // Associate the credentials with the vault - - // Step 3: 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(primaryVaultConfig) // Add the first 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); - } - } -}